text:
Q: i'm trying to join a channel but i get PlatformException(-17, request to join channel is rejected, null, null) I'm creating a channel from agora web demo as host and trying to join the channel from the flutter app as an audience i made sure both use the same channel name, app id, and I'm generating tokens through a server and Fech them to the app.
here's my code:

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:agora_rtc_engine/rtc_remote_view.dart' as rtc_remote_view;
import 'package:agora_rtm/agora_rtm.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import '../../utilities/agora_app_id.dart';

class StreamScreen extends StatefulWidget {
  static const routeName = '/stream';
  final String channelName;
  final String userName;
  final int userID;

  const StreamScreen({
    Key? key,
    required this.channelName,
    required this.userName,
    required this.userID,
  }) : super(key: key);

  @override
  State<StreamScreen> createState() => _StreamScreenState();
}

class _StreamScreenState extends State<StreamScreen> {
  final List<int> _audience = [];
  late RtcEngine _rtcEngine;
  AgoraRtmClient? _rtmClient;
  AgoraRtmChannel? _rtmChannel;
  String? _rtmToken;
  String? _rtcToken;

  Future<void> initAgora() async {
    _rtcEngine =
        await RtcEngine.createWithContext(RtcEngineContext(agoraAppID));
    _rtmClient = await AgoraRtmClient.createInstance(agoraAppID);

    await getRTMToken();

    await _rtcEngine.enableVideo();
    await _rtcEngine.startPreview();
    await _rtcEngine.setChannelProfile(ChannelProfile.LiveBroadcasting);
    await _rtcEngine.setClientRole(ClientRole.Audience);
    await getRTCToken();

    //join the RTC & RTM Channels

    await _rtcEngine.joinChannel(
      _rtcToken,
      widget.channelName,
      null,
      0,
    );

    //event handlers for RTC Engine
    _rtcEngine.setEventHandler(RtcEngineEventHandler(
      joinChannelSuccess: (channel, uid, elapsed) {
        //TODO: add joinChannel logic
        print('joinChannelSuccess $channel $uid');
      },
      userJoined: (uid, elapsed) {
        print('User $uid joined');
      },
      leaveChannel: (rtcStats) {
        setState(() {
          _audience.clear();
        });
      },
      tokenPrivilegeWillExpire: (rtcToken) async {
        await getRTCToken();
        await _rtcEngine.renewToken(rtcToken);
      },
    ));

    //event handlers for RTM Client
    _rtmClient?.onConnectionStateChanged = (state, reason) {
      print('Connection State changed: ' +
          state.toString() +
          ', reason: ' +
          reason.toString());
      if (state == 5) {
        _rtmChannel?.leave();
        _rtmClient?.logout();
        _rtmClient?.destroy();
        print('logged out.');
      }
    };

    //event handlers for RTM Channel
    _rtmChannel?.onMemberJoined = (member) {
      print('member joined: ' + member.userId + 'channel: ' + member.channelId);
    };

    _rtmChannel?.onMemberLeft = (member) {
      print('member left: ' + member.userId + 'channel: ' + member.channelId);
    };
  }

  @override
  void initState() {
    super.initState();
    initAgora();
  }

  @override
  void dispose() {
    _audience.clear();
    _rtcEngine.leaveChannel();
    _rtcEngine.destroy();
    _rtmChannel?.leave();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: rtc_remote_view.SurfaceView(
          channelId: widget.channelName,
          uid: widget.userID,
          zOrderOnTop: true,
          zOrderMediaOverlay: true,
        ),
        // const Toolbar(),
      ),
    );
  }

  Future<void> getRTMToken() async {
    final response = await http.get(
      Uri.parse(
          'https://*********************.com/rtm/${widget.userID}/?expiry=7000'),
    );

    if (response.statusCode == 200) {
      setState(() {
        _rtmToken = response.body;
        _rtmToken = jsonDecode(_rtmToken!)['rtmToken'];
      });
      print('rtm: ' + _rtmToken!);
    } else {
      print('Failed to fetch the token');
    }
  }

  Future<void> getRTCToken() async {
    final response = await http.get(
      Uri.parse(
          'https://******************.com/rtc/${widget.channelName}/audience/uid/${0}/?expiry=7000/'),
    );

    if (response.statusCode == 200) {
      setState(() {
        _rtcToken = response.body;
        _rtcToken = jsonDecode(_rtcToken!)['rtcToken'];
      });
      print('rtc: ' + _rtcToken!);
    } else {
      print('Failed to fetch the token');
    }
  }
}

i get this error:
#0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177:18)
<asynchronous suspension>
#2      _StreamScreenState.initAgora (package:malhamti_app/screens/stream/stream_screen.dart:58:5)
<asynchronous suspension>

*

*what am i doing wrong?

*do i need to set up the RTM channel/client, when I'm just wanting
video streaming?

*What does the number -17 in the error mean?

A: Error code 17 occurs when a user is already in the channel and you try to join the channel again. Make sure that you call leaveChannel()  method before leaving the channel.

A: Error code 17 happen when you are in test account in agora to solve this exception you must change account from test to live


text:
Q: Java n-node tree I'm trying to write Java code for the following figure. Where,
if node:4 will create following separate 4 trees. Number of node in
LEVEL1 (yellow) : 1 node
LEVEL2 (green) : n-1 node
LEVEL3 (blue) : n-2 node

see image for node:4

Another way if node : 5 then,
LEVEL1 (yellow) : 1 node
LEVEL2 (green) : n-1 node
LEVEL3 (blue) : n-2 node

see image for node:5

And so on. Thanks in advance for kind help.

A: How to solve is what is important here.
Start top-down, and work out the logic.
List<Tree> makeTrees(int n) {
    List<Tree> trees = new ArrayList<>();

    for (int i = 0; i < n; ++i) {
        Tree tree = makeYellow(n, i);
        trees.add(tree);
    }
    return trees;
}

private Tree makeYellow(int n, int yellow) {
    Tree tree = new Tree();
    Node node = new Node(yellow, Color.YELLOW);
    tree.add(node);
    for (int i = 0; i < n; ++i) {
        if (i != yellow) {
            Node green = makeGreen(n, yellow, i);
            node.add(green);
        }
    }
    return tree;
}

And so on.
As you see, at the top for the yellow nodes a simple for suffices. Instead of already working everything out in detail, anticipate the further solution, call makeGreen and determine what it should return and what info it needs.
Try to find patterns.
Such homework is best done oneself in order to train solving such puzzles, and being mentally rewarded.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automorphisms of $\mathbb C_p$ I am looking for a non-trivial automorphism $\sigma$ of $\mathbb C_p$ such that $\sigma(\mathbb Q_p)\subset\mathbb Q_p$.
If $\mathbb C_p$ were spherically complete, then by Hahn-Banach theorem, that would be impossible. But $\mathbb C_p$ is not spherically complete, so we can not apply Hahn-Banach. And my problem is still opened....
Does anyone have a hint or an example of such automorphism?
Thanks in advance

A: *

*Transcendence degree ℂp/ℚp=2ℵ0 which is enough to answer the question affirmatively.

*More explicitly: ℂp embeds into the field of p-adic Malcev-Neumann series = formal sums Σzipai with zi∈F̅p and {ai} well-ordered subset of ℚ.  This gives an injection of the semi-direct product Gal(F̅p/Fp) X ℤ̂  ⊂ Aut(ℂp/ℚp).

*Reference: http://deepblue.lib.umich.edu/bitstream/handle/2027.42/26390/0000477.pdf?sequence=1

A: If you strengthen the condition $\sigma(\mathbf Q_p) \subset \mathbf Q_p$ to  $\sigma$ being the identity on $\mathbf Q_p$, so $\sigma$ is a $\mathbf Q_p$-automorphism of $\mathbf C_p$, then a simple description is possible:
(1) every $\mathbf Q_p$-isomorphism between two finite extensions of $\mathbf Q_p$ extends (in many ways) to a field automorphism of $\overline{\mathbf Q_p}$, i.e., to an element of ${\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$,
(2) every element of ${\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$ extends uniquely to a continuous $\mathbf Q_p$-automorphism of $\mathbf C_p$,
(3) every continuous $\mathbf Q_p$-automorphism of $\mathbf C_p$ is an isometry of $\mathbf C_p$ and is the continuous extension of a unique element of ${\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$.
Therefore any $\mathbf Q_p$-isomorphism between two finite extensions of $\mathbf Q_p$ extends (in many ways) to a continuous automorphism of $\mathbf C_p$, so in particular for any finite Galois extension $K/\mathbf Q_p$ every element of ${\rm Gal}(K/\mathbf Q_p)$ extends (in many ways) to a continuous $\mathbf Q_p$-automorphism of $\mathbf C_p$. Therefore starting with any non-identity automorphism of a finite Galois extension of $\mathbf Q_p$ we can lift it to a non-identity continuous $\mathbf Q_p$-automorphism of $\mathbf C_p$. For example, the conjugation on $\mathbf Q_p(\sqrt{p})$ extends (in many ways) to a continuous $\mathbf Q_p$-automorphism of $\mathbf C_p$. We only need the first two properties above. The point of the third property is to show which $\mathbf Q_p$-automorphisms of $\mathbf C_p$ come from ${\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$: the automorphisms that are isometries (hence automatically continuous and thus automatically fixing $\mathbf Q_p$).
Proof of (1): This is a theorem from abstract algebra, having nothing to do with $p$-adic fields: every isomorphism between two fields extends (in many ways) to an isomorphism between their algebraic closures. The proof relies on Zorn's lemma, so it is not constructive. See Lang's Algebra, Theorem 2.8 of Chapter V. He proves any embedding $\sigma$ of a field $k$ into an algebraically closed field $L$ extends  (by Zorn's lemma) to an embedding of any algebraic extension $E$ of $k$ into the same field $L$, and if $E$ is an algebraic closure of $k$ and $L$ is an algebraic closure of $\sigma(k)$ then he shows that embedding of $E$ into $L$ must be an isomorphism. Apply this theorem with $k$ being a finite extension of $\mathbf Q_p$ and $E = L = \overline{\mathbf Q_p}$.
Proof of (2): Let $\sigma \in {\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$.
Any $\mathbf Q_p$-automorphism of a finite extension of $\mathbf Q_p$ preserves the $p$-adic absolute value on that finite extension, so by viewing two elements of $\overline{\mathbf Q_p}$ inside a finite Galois extension of $\mathbf Q_p$ we get that $\sigma$ is an isometry on $\overline{\mathbf Q_p}$: $|\sigma(\alpha) - \sigma(\beta)|_p = |\alpha - \beta|_p$ for all $\alpha$ and $\beta$ in $\overline{\mathbf Q_p}$. Thus $\sigma$ is uniformly continuous on $\overline{\mathbf Q_p}$, so it extends in exactly one way to a continuous function on $\mathbf C_p$, namely by $\sigma(z) := \lim_{n \rightarrow \infty} \sigma(\alpha_n)$, where $\alpha_n$ is any sequence in $\overline{\mathbf Q_p}$ converging to $z$. It is straightforward to check for all $z$ and $w$ in $\mathbf C_p$ that $|\sigma(z) - \sigma(w)|_p = |z - w|_p$ and then that $\sigma$ is additive and multiplicative on $\mathbf C_p$. To show $\sigma$ on $\mathbf C_p$ is surjective, write $z\in \mathbf C_p$ as a limit of $\alpha_n \in \overline{\mathbf Q_p}$. Since $\sigma$ is an isometry the sequence $\sigma^{-1}(\alpha_n)$ in $\overline{\mathbf Q_p}$ is Cauchy and its limit $w$ in $\mathbf C_p$ satisfies $\sigma(w) = z$.
Proof of (3): Let $\sigma$ be a continuous $\mathbf Q_p$-automorphism of $\mathbf C_p$. Since $\sigma$ fixes each element of $\mathbf Q_p$, we have $\sigma(\overline{\mathbf Q_p}) \subset \overline{\mathbf Q_p}$. The field $\sigma(\overline{\mathbf Q_p})$ is algebraically closed and lies between $\mathbf Q_p$ and $\overline{\mathbf Q_p}$, so $\sigma(\overline{\mathbf Q_p}) = \overline{\mathbf Q_p}$. Thus $\sigma$ restricts to an element of
${\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$, so $\sigma$ on $\mathbf C_p$ is the continuous extension of an element of ${\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$, and it can be the continuous extension of at most one element of the Galois group since $\overline{\mathbf Q_p}$ is dense in $\mathbf C_p$. By the proof of (2), the continuous extension to $\mathbf C_p$ of an automorphism in ${\rm Gal}(\overline{\mathbf Q_p}/\mathbf Q_p)$ is an isometry on $\mathbf C_p$, so $\sigma$ is an isometry on $\mathbf C_p$.


text:
Q: Condtionally set ASP.NET session and authentication cookies samesite value based on browsers I have done the following changes to my web.config and I'm able to server both the authentication and the session cookie with samesite=none and secure.
the problem is for browsers such as chrome 51-66 sending samesite=none invalidates the cookie and then the user does not have a session and is not able to login.
https://www.chromium.org/updates/same-site/incompatible-clients
is there a way to maybe extend the classes that create those cookies or some other way to conditionally set the samesite parameter based on the browser/useragent
<system.web>
    <httpCookies sameSite="None"/>
    <sessionState cookieSameSite="None" />
    <authentication mode="Forms">
        <forms cookieSameSite="None" />
    </authentication>

A: While not a complete solution (as it only covers the session cookie as in my use case I set my forms authentication cookie manually), I implemented the following in my MVC5 application to handle the setting of the SameSite attribute:
In Global.asax.cs
protected void Session_Start(object sender, EventArgs e)
{
    var cookie = Response.Cookies["ASP.NET_SessionId"];
    if (cookie != null)
        cookie.SameSite = SameSiteCookieUtils.GetSameSiteMode(Request.UserAgent, SameSiteMode.None);
}

// Ref https://learn.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1#supporting-older-browsers
public static class SameSiteCookieUtils
{
    /// <summary>
    /// -1 defines the unspecified value, which tells ASPNET to not send the SameSite attribute
    /// </summary>
    public const SameSiteMode Unspecified = (SameSiteMode) (-1);

    public static SameSiteMode GetSameSiteMode(string userAgent, SameSiteMode mode)
    {
        if (string.IsNullOrWhiteSpace(userAgent))
            return mode;

        if (mode == SameSiteMode.None && DisallowsSameSiteNone(userAgent))
            return Unspecified;

        return mode;
    }

    public static bool DisallowsSameSiteNone(string userAgent)
    {
        // Cover all iOS based browsers here. This includes:
        // - Safari on iOS 12 for iPhone, iPod Touch, iPad
        // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
        // - Chrome on iOS 12 for iPhone, iPod Touch, iPad
        // All of which are broken by SameSite=None, because they use the iOS networking
        // stack.
        if (userAgent.Contains("CPU iPhone OS 12") ||
            userAgent.Contains("iPad; CPU OS 12"))
        {
            return true;
        }

        // Cover Mac OS X based browsers that use the Mac OS networking stack.
        // This includes:
        // - Safari on Mac OS X.
        // This does not include:
        // - Chrome on Mac OS X
        // Because they do not use the Mac OS networking stack.
        if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") &&
            userAgent.Contains("Version/") && userAgent.Contains("Safari"))
        {
            return true;
        }

        // Cover Chrome 50-69, because some versions are broken by SameSite=None,
        // and none in this range require it.
        // Note: this covers some pre-Chromium Edge versions,
        // but pre-Chromium Edge does not require SameSite=None.
        if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))
        {
            return true;
        }

        return false;
    }
}

With the DisallowsSameSiteNone logic coming from the Microsoft Docs https://learn.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1#supporting-older-browsers
I also set the following in my web.config
<httpCookies httpOnlyCookies="true" requireSSL="true" />

Hopefully some of that is useful to you


text:
Q: OR instruction in assembly into ECX register in a book I'm reading, we are given the following snippet and problem:

This function uses a combination SCAS and STOS to do its work. First,
  explain what is the type of the [EBP+8] and [EBP+C] in line 1 and 8,
  respectively. Next, explain what this snippet does:

01: 8B 7D 08    mov edi, [ebp+8]
02: 8B D7       mov edx, edi
03: 33 C0       xor eax, eax
04: 83 C9 FF    or ecx, 0FFFFFFFFh
05: F2 AE       repne scasb
06: 83 C1 02    add ecx, 2
07: F7 D9       neg ecx
08: 8A 45 0C    mov al, [ebp+0Ch]
09: 8B AA       mov edi, edx
10: F3 AA       rep stosb
11: 8B C2       mov eax, edx

I had nearly figured out everything after checking with an online solution (https://johannesbader.ch/2014/05/practical-reverse-engineering-exercises-page-11/), however, one step in this snippet still does not make sense ot me.
According to the online solution, when we run the command or ecx, 0FFFFFFFFh at line 4, it says

We [now] interpret ECX as a signed integer -1

In order to know what the result is going to be for the or command, wouldn't we need to know previously what the value of ECX is? And why is the value -1?
Thanks

A: The 32-bit two's complement representation of -1 is 0xFFFFFFFF (all-ones).   1 OR x is always 1, so this unconditionally sets ecx to -1.  This trick only works for -1, because OR can only set bits, not clear them to zero.

The part of the solution that you quote, about interpreting "ecx as a signed integer -1", is only sensible in the context of the gdb command that follows:  (gdb) p/d $ecx  ->  $7 = -1.
rep prefixes treat ecx as an unsigned counter.  Setting ecx to -1 / UINT_MAX means repne scasb will only stop when it finds a zero in memory, not because ecx counted down all the way.  (In theory, if there was no zero, it would count down and end that way, but in practice it would segfault first.  -1 isn't a special-case for rep).

Why use or: code size
The "normal" way to set a register to anything other than zero is with a 5 byte mov r32, imm32 insn, for example  B9 FF FF FF FF       mov    ecx,-1.
If you care more about code-size than speed, or you know that a false dependency on ecx isn't a problem here, you can save two bytes by using a sign-extended 8-bit immediate: or r/m32, imm8.
83 C9 FF    or ecx, 0FFFFFFFFh

None of the bits in the result actually depend on the old value of ecx, because.  However, real CPUs don't special-case this, so out-of-order execution can't get started until ecx is ready.  This is a false dependency on the old value of ecx.  mov breaks the dependency on the previous value.  (For more about this, see the x86 tag wiki, especially Agner Fog's guides).
or ecx, imm8 needs a ModRM byte to encode the destination as ecx, unlike that form of mov where there's a separate opcode for each destination register.  There's unfortunately no opcode for mov r/m32, imm8, which would save 2 bytes of code in many instructions.
If Intel had been willing to drop backwards compatibility with undocumented instructions, they could have added it.  (8086 didn't have it, because it would only help 16-bit code when moving an immediate to memory.  They already dedicated 8 opcodes to mov r16, imm16, which is 3 bytes in 16-bit mode where it doesn't need an operand-size prefix, just like the non-existent mov r/m16, imm8 would be.)

So this is a useful idiom when optimizing for code-size, e.g. for a bootloader, or a machine-code answer on https://codegolf.stackexchange.com/.  (Yes, that's a thing.)
Another related trick is using a 3-byte lea to create a constant, if you already have another constant in another register.  e.g. for x86-64 Adler32, I needed two zeroed registers and a 1, so I used
401120:       31 c0          xor  eax,eax
401122:       99             cdq                 # zero rdx by sign-extending eax (0) into edx
401123:       8d 7a 01       lea  edi,[rdx+0x1]  # edi=0+1, using a reg + disp8 addressing mode

A: F in hex is 1111 in binary, so 0ffffffffh is a DWORD with all bits set to 1.
According to the truth table of OR, if you OR anything with 1, you still get 1.
So, no matter what ECX previously held, after this particular OR operation all of its bits will be set to 1, which is 0ffffffffh.  This is explained in the first link provided by Jose Manuel Abarca Rodriguez in a comment.
The Intel architecture (as well as most hardware architectures out there) use what is known as "two's complement representation" to establish a mapping between numbers and bit patterns in registers or in memory. In two's complement representation, -1 is represented as 0ffffffffh.  This is explained in the second link provided by Jose Manuel Abarca Rodriguez in a comment.


text:
Q: What is the difference between NAT and SNAT\DNAT? Following the question in subject, I guess there is a slight difference between NAT and the others.
Is it that NAT translates a complete private network, as SNAT\DNAT translate per package?
Thanks.

A: DNAT: Traffic from address IPs is  forwarded to a specific internal IP.
or redirects the incoming traffic for some IPs or Port to particular address of your choice.
SNAT:   matches for all traffic from a specific  network(internal Network) to the output interface (address source used as source for the packets that match, also the output address of your network).

A: "NAT" is a collective term for various translations - usually it's actually NAPT (involving the transport-layer/L4 port numbers as well).
Source NAT translates the source IP address (and L4 port number), usually when connecting from a private to a public IP address ("LAN  to Internet"). The router stores newly created translations ('sessions') and manipulates responses accordingly in a backward fashion.
Destination NAT translates the destination IP address (and possibly the L4 port), usually when connecting from a public IP to a private IP (aka port-forwarding, reverse NAT, expose host, "public server in LAN"). While the inbound mapping is static, the return traffic also requires 'sessions' to find the original source.
Both variants work very much alike but generally differ in the way that a connection (or rather a session) is established.

A: NAT is an abbreviation for Network Address Translation.
SNAT is Source NAT, or, NAT for traffic in the direction of Source, or Internal network, to a Public or other network IP translation.
DNAT, similarly, is Destination NAT, for traffic coming from an external Public or other network to a private networks destination, performing an IP address translation.

A: As mentioned elsewhere, NAT stands for Network Address Translation, and refers to several related functions, including some that involve port number translation as well.
The main reason NAT is required is because of private networks (like your home network, and like networks inside an enterprise.)  The IP addresses in the private network are not unique; the same addresses can be used in anyone else's private network.  Therefore, address translation is required so that hosts inside the private network can communicate with hosts outside the network.
In general, NAT changes the LOCAL address in a packet, which is the source address for outgoing packets and the destination for incoming packets.  (In unusual cases it can do other things, but that's beyond the scope here.)
The terms SNAT and DNAT are not defined in the RFCs, and mean different things to different people.  However, here are what I see as the most common definitions.
SNAT allows hosts in the private network to access public services in the Internet.
It stands for "source NAT" and is a misnomer.  It is also called "Traditional NAT" and "Outbound NAT" in rfc-2663.  This is the NAT function provided by default by a typical home router, where you have a private network, without any special configuration.  It also changes the local TCP/UDP port number (and therefore is often referred to as NAPT for Network Address and Port Translation.)  It allows multiple hosts to share the same single public IP address for the network.
DNAT allows hosts outside the private network to access public services in the private network.
It stands for Destination NAT, which is again a misnomer.  This can also be provided  by a typical home router but you have to set it up and have a clue what you're doing.  Normally it does not change the TCP/UDP port number, since that identifies the service being used (for example, TCP port 80 is for a web server.)
NAT was introduced because we were running out of IP addresses, so we were forced to adopt private networks to avoid every device on a home or enterprise network consuming a global public IP address.


text:
Q: lru_cache interferes with type checking done by single_dispatch I have a method dispatch decorator with three registered functions. One dispatches on int, which works fine. The second dispatched on a custom type, also works fine. The third is also a custom type, but the Class is wrapped with the lru_cache decorator.
(To make things a little more complicated, the class is instantiated in a roundabout way via a methoddispatch on the __call__ method of another class.)
@lru_cache(maxsize=None, typed=True)
class QualifiedInterval:
    # stuff that works

Inside the Pitch class:
@oph_utils.method_dispatch
def augmented(self, other):
    raise NotImplementedError

@augmented.register(int)
def _(self, other):
    return "works fine"

@augmented.register(Interval)
def _(self, other):
    return "works fine too"

@augmented.register(QualifiedInterval)
def _(self, other):
    return "only works if QualifiedInterval class does NOT have lru_cache"

(There's a lot more going on, but this is the bits that don't work.)
Basically - if I have lru_cache, and pass a QualifiedInterval into the function, it does not dispatch and raises NotImplementedError. If I comment out the cache decorator, it works. And manual type checking at the REPL shows the same type ("QualifiedInterval") either way. I've tried calling the command that created the QualifiedInterval several different ways, and tried assigning it to a variable. Still doesn't work. I've tried doing explicit typechecking in the Augmented function. The typecheck fails there as well, if caching is enabled.

A: Analysis of What is Going Wrong

Basically - if I have lru_cache, and pass a QualifiedInterval into the function, it does not dispatch

The lru_cache is function that returns a decorator that wraps any callable (including classes).  So when you apply the lru_cache to the QualifiedInterval class, that variable becomes assigned to the wrapper function rather than the class itself.
>>> @lru_cache(maxsize=None, typed=True)
class QualifiedInterval:
    pass

>>> type(QualifiedInterval)
<class 'functools._lru_cache_wrapper'>

Single dispatch works by matching the type of the first parameter to the appropriate method. However, when you pass in an instance of QualifiedInterval, its type doesn't match functools._lru_cache_wrapper, so single dispatch falls back to the base method(which raises NotImplemented.
Solution
Teach single dispatch to match on the actual original class (type) instead of the wrapped class:
@augmented.register(QualifiedInterval.__wrapped__)
def _(self, other):
    return "show now work QualifiedInterval class has an lru_cache"

Note the addition of the .__wrapped__ attribute which reaches through the wrapper function to get to the original unwrapped class.
Hope that clears it all up and shows the way forward :-)


text:
Q: Saving an NSDictionary of NSArrays of custom objects I have a dictionary (it's mutable if that makes a difference) which contains nsarrays, which in turn contain (subclass of NSObject)s
I have implemented initWithCoder and encodeWithCoder like this:
-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    self.Title = [aDecoder decodeObjectForKey:@"Title"];
    self.SiteAPIURL = [aDecoder decodeObjectForKey:@"SiteAPIURL"];
    self.ID = [aDecoder decodeObjectForKey:@"ID"];
    return self;
}

-(void) encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.Title forKey:@"Title"];
    [aCoder encodeObject:self.SiteAPIURL forKey:@"SiteAPIURL"];
    [aCoder encodeObject:self.ID forKey:@"ID"];
}

But it doesn't save properly when I do [dictionary writeToFile:savepath atomically:YES];
So what am I doing wrong, and what exactly is serialization and do I need I need to use NSKeyedArchiver or something?

A: [NSDictionary writeToFile: atomically:] uses NSPropertyListSerialization, which can only record a subset of primitive objects (numbers, strings, dates and data). So while you could use NSCoding along with NSKeyedArchiver to archive the objects, another option is to marshal your objects into a string or data representation, store that in the property list, and unmarshal them again on loading.

A: Yes, you want to use a NSKeyedArchiver
All the info you need can be found here:
http://developer.apple.com/library/ios/ipad/#documentation/Cocoa/Conceptual/Archiving/Archiving.html


text:
Q: OpenCL with Cloo: Profilers not working I'd like to profile my application which I've written in C# using Cloo as a wrapper for OpenCL.
I've tried a few things... gDEBugger, AMD APP SDK, CodeXL, KernelAnalyzer...
Copy-Pasting my Kernel Code as it is to KernelAnalyzer will indicate that the bottleneck are the ALU operations. However, since it's only a kernel analyzer I don't wholly trust the generated information.
To properly profile my application I tried the other tools. I tried to profile with APP SDK via console using sprofile.exe but I always get "Failed to start application: 0: the process has terminated successfully". I can't really guess what the issue might be.
When using the standalone tools CodeXL and gDEBugger I can see the Debugged Process Events (Threads starting, Messages) when running the .exe but that's about it. No function calls, memory info, statistics etc...  it's all empty as if I didn't run the application! So it's basically useless for me.
I don't really know what the problem might be. Could it be that using Cloo as a wrapper makes all the performed operations invisible to the profilers?
I'd appreciate any hints! Thanks in advance!

A: I just tried to profile Clootils.exe (the sample that comes with the Cloo distro) with CodeXL, and after some trial and error, I was able to get CodeXL to work.
I had to first rebuild both Cloo.dll and ClooUtils.exe with the Platform target set to x86.  Using the default setting of "Any CPU" gave me a "The application was unable to start correctly (0xc000007b)." error.  Trying "x64" gave me a "Failed to profile" error message, and left the ClooUtils.exe process in memory.  But trying with "x86" allowed me to profile just fine.  I tried both "GPU: Application Trace" and "GPU: Performance Counters" profile modes in CodeXL, and both worked.
So that may provide a workaround to allow using CodeXL.


text:
Q: How to get permissions in discord js when we do direct message I am trying to get a list of the permission that the user has in Discord. If it sends the message in the channel, it's fine as we can use message.member.hasPermission, etc.
But what if the message is DM? I want my users to send a DM to the bot and the bot be able to check and see if the user has certain permissions.
I cannot find anything anywhere. I keep getting redirected to message.member, or message.guild which both are null when it's in DM.

A: In DM no one has permissions. All you have is the permission to see messages and send messages which aren't shown visually, or to bots. To make sure that it isn't DM, just return if the channel type is dm, or guild is null.
if(!message.guild) return;
//before checking "perms"

If you want the permissions for a certain guild if the message is from DM, use this code
if(message.channel.type === 'dm') {
let guild = await client.guilds.fetch('THE ID OF THE GUILD YOU WANT TO SEE THE USER'S PERMS IN')
let member = await guild.members.fetch(message.author.id);
//you can now access member.permissions
}

Keep in mind await must be in an async callback.
You did not provide any code so I cannot give any more code than this.

A: You can fetch the member with the guild's context.
Fetching is recommended, as Guild#member() relies on cache and is also deprecated.
Member#hasPermission() will be deprecated as well, using MemberRoleManager#has() is recommended
The following example uses async/await, ensure you're inside an async function
// Inside async function
const guild = await client.guilds.fetch('guild-id');
const member = await guild.members.fetch(message.author.id);
const hasThisPermission = member.roles.cache.has('permission');


text:
Q: How should I test AWS S3 with moto on Travis? Moto needs a credentials file, which does not exist on Travis. Travis fails with
botocore.exceptions.NoCredentialsError: Unable to locate credentials

See example / code.
How can I fix this for travis? (Locally, it works)
What I tried
I added the following environment variables (source) to my .travis.yml:
env:
  global:
    - AWS_ACCESS_KEY_ID=dummy-access-key
    - AWS_SECRET_ACCESS_KEY=dummy-access-key-secret
    - AWS_DEFAULT_REGION=us-east-1

I still get the same error. The versions in this build are:

*

*boto: 2.49.0

*boto3: 1.9.41

*botocore: 1.12.41

*moto: 1.3.7


text:
Q: python + Semicolon written to file is written on the next line I have this simple python expression:
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1]))

And I would expect to receive output like this
update some_table va set active_id = 1 where id = 5;
update some_table va set active_id = 1 where id = 3;
...more lines...

However, i'm getting this
update some_table va set active_id = 1 where id = 5
;update some_table va set active_id = 1 where id = 3
...more lines....

Anything i'm missing ?
Thanks in advance

A: I would try adding a strip() to your latest parameter that could end with \n.
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1].strip()))

A: Some value of vl[1] is a string with a newline in it, not an integer.


text:
Q: Laravel 7. Attempt method return false I hope my english is good enough to explain my problem. I'm working with laravel 7, and I'm trying to implement my own AuthController, because I can't use migrations and I can't use a table 'users' because I have a db implemented. I've read all the documentation of laravel about authentication and spent days reading a lot of posts with this problem, and I tried everything but still does not work. The problem is with the attempt method. My register method is working fine, but I can't login, actually I tried to put manually the data(that's why credentials are commented) to find the problem but I don't know why is not working
My Regsiter method.
public function storeUser(Request $request)
    {
        //dd($request);
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:administradores,ADMIN_Correo',
            'password' => 'required|string|min:8|confirmed',
            'password_confirmation' => 'required',
        ]);

        Administrador::create([
            'ADMIN_Nombre' => $request->name,
            'ADMIN_Correo' => $request->email,
            'ADMIN_Contrasena' => Hash::make($request->password),
        ]);

        //return redirect('home');
    }

My Login method.
public function authenticate(Request $request)
    {
        /*$request->validate([
            'ADMIN_Correo' => 'required|string|email',
            'ADMIN_Contrasena' => 'required|string',
        ]);*/

        //$credentials = $request->only('ADMIN_Correo', 'ADMIN_Contrasena');

        if (Auth::guard('admin')->attempt(['ADMIN_Correo' => 'edwin2@gmail.com
        ','ADMIN_Contrasena' => '12345678'])) {
            return redirect()->intended('home');
        }else{
            echo 'error';
        }

        //return redirect('login')->with('error', 'Oppes! You have entered invalid credentials');
    }

My config/auth.php file
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ]
    ],
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Administrador::class,
        ],

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Administrador::class,
         ],
    ],

My Model
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Administrador extends Authenticatable
{
    use Notifiable;
    protected $table = 'administradores';
    protected $primaryKey = 'ADMIN_Id';
    public $timestamps = false;
    public $incrementing = true;
    protected $fillable = ['ADMIN_Nombre','ADMIN_Correo','ADMIN_Contrasena'];
    protected $guard = 'admin';

    public function getAuthPassword()
    {
        return $this->ADMIN_Contrasena;
    }

}

NOTES The field for password:(ADMIN_Contrasena) is varchar 255


text:
Q: One of the angles of a trapezoid $ABCD$ is $30^\circ$ and its diagonals are perpendicular to each other One of the angles of a trapezoid $ABCD (AB\parallel CD)$ is $30^\circ$ and its diagonals are perpendicular to each other. If the midsegment is $10$ and one of the bases is $8$, find the other base, the diagonals and the legs of $ABCD$.
Let $\measuredangle ABC=30^\circ$ and $MN$ be the midsegment $(M;N \in AD;BC)$. Let's $AB=a;DC=b;AD=c;BC=d.$ So $$MN=\dfrac{AB+CD}{2}\iff 10=\dfrac{a+8}{2}\iff20=a+8\iff a=12.$$ Clearly $a>b$.
I am not completely sure how we are supposed to interpret the fact that the diagonals of the trapezoid are perpendicular. I have tried the following: let $AC\cap BD=O;AO=x;OC=y;BO=z;OD=t.$ Then $$x^2+z^2=a^2=144\\y^2+z^2=d^2\\y^2+t^2=b^2=64\\x^2+t^2=c^2$$ From here we can derive $$a^2+b^2=x^2+y^2+z^2+t^2=c^2+d^2\\c^2+d^2=144+64=208$$
Now we are searching for another relationship between $c$ and $d$. I wasn't able to find such.
Yet let $CC_1\perp AB,DD_1\perp AB$. Since $\measuredangle C_1BC=30^\circ\Rightarrow CC_1=DD_1=h=\dfrac{d}{2}$. Now I decided to see what happens if $AD_1=x\Rightarrow C_1B=4-x$. Nothing helpful, though.

A: Hint

The triangles $\Delta OCD$ and $\Delta OAB$ are similars with raio $8/12 = 2/3$. It means we can write $OD=2x$, $OB=3x$, $OC=2y$ and $OA=3y$.
We can also write $$\tan (OBA) = \frac yx \quad (1)$$ and $$\tan (OBC)=\tan (30-OBA)=\frac{\tan (30)-\tan(OBA)}{1+\tan(30)\tan(OBA)}=\frac 23 \frac yx.\quad (2)$$
Solve the system with equations $(1)$ and $(2)$, and find $y/x$.
You also know that $$4x^2+4y^2=64.$$
Can you finish?
EDIT:
Setting $\tan(OBA)=y/x=k$ on equation $(2)$
$$\frac{\sqrt(3)/3-k}{1+\sqrt(3)/3 k}=\frac 23 k.$$


text:
Q: Trying to capture the following string with regex I'm trying to capture this string with regex. It doesn't appear to be generating any matches.
  $property = "[[resource:76e9e8b2-788a-407f-a285-4728be19f71f:";

  if(!is_array($property)) {
  preg_match("\[\[resource:(\w+-\w-\w-\w-\w):", $property, $matches);
  print_r($matches[1]);
  }

As far as I can tell, the alphanumeric sequence with dashes should be put out to the $matches variable - but in fact, when I print_r() that variable out, I get nothing.
So how do I get a match inside the $matches array.
Ultimately what I want to be able to get is this:
76e9e8b2-788a-407f-a285-4728be19f71f

A: You forgot a bunch of + modifiers. You also forgot the delimiters at the beginning and end of the regexp.
preg_match('/\[\[resource:(\w+-\w+-\w+-\w+-\w+):/', $property, $matches);
                                 ^   ^   ^   ^

A: As an aside comment, you can use the character class [[:xdigit:]] that fits exactly the hexadecimal characters:
\[\[resource:([[:xdigit:]]+(?>-[[:xdigit:]]+){4}):


text:
Q:  expected got  in spring-data hibernate Working with spring-data and hibernate and trying to write this request in a repository :
    @Query("select u from AppUser u inner join u.roles r inner join u.contrats c where r = :role and not exists ( from c.project p where p = :project)")

My goal is to get List of AppUser (Users) from entity AppUer ,but with a condition , only those who don't have the entity project .
To explain more , there is an entity Contrat between Project and AppUser  , it contains Project project , AppUser appuser .
There is a mapping between one_to_many between AppUser and Contrat(AppUser can have multiple contrats) .
Also a mapping of one_to_many between Contrat and project ( One project can have multiple contrat ) .
The problme is that this request returns a empty list while it should return a list of 12 users as they don't have the specified project i passe to it.
I remark in this request (from c.project p where p = :project) 'from' is underlined with red line saying  :
<expression> expected got <from> in spring-data hibernate.

Any idea ?
Edit
Entity AppUser
@Entity
@Data
@AllArgsConstructor @NoArgsConstructor
public class AppUser implements Serializable {

    @Id @GeneratedValue
    private Long id;
    @Column(unique = true)
    private String username;
    private String password;
    private String prenom;
    private String nom;
    private Long tel;
    private String cin;
    private String email ;
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<AppRole> roles = new ArrayList<>();

    @OneToMany(mappedBy = "appUser" )
    @Fetch(value = FetchMode.SUBSELECT)
    @JsonManagedReference(value="appuser-contrat")
    private Collection<Contrat> contrats = new ArrayList<Contrat>();

    public void addToContrats(Contrat contrat){
        this.contrats.add(contrat);
    }

}

Entity Contrat
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Contrat implements Serializable{

        @Id @GeneratedValue
        private Long id;
        private Date dateDebut ;
        private Date dateFin ;
        private Long idDevloppeur;
        @ManyToOne
        @JoinColumn(name = "Id_Project")
        @JsonBackReference(value="projet-contrat")
        private Project project;

        @ManyToOne
        @JoinColumn(name = "Id_AppUser")
        @JsonBackReference(value="appuser-contrat")
        private AppUser appUser;

}

Entity Project
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Project implements Serializable{

        @Id @GeneratedValue
        private long id;
        private String intitule;
        private String description;

        @OneToMany(mappedBy = "project" )
        @Fetch(value = FetchMode.SUBSELECT)
        @JsonManagedReference(value="projet-contrat")
        private Collection<Contrat> contrats  = new ArrayList<Contrat>();

        public void addToContrats(Contrat contrat){
                this.contrats.add(contrat);
        }

 }

A: (Posting answer to summarize solution in comments)
In given select query "inner join u.contrats" was used, but there were no contracts entities for users. Solution: replace with "left join u.contrats".
Inner join vs left join already solved here
What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?


text:
Q: Java Why T is still calling default method when T extends the interface public class Draw<T extends Print> (Print is a interface)

Other classes:
public interface Print {
    static void info(String message) {
        System.out.println("failed");
    }
 }
public class Test implements Print {
    static void info(String message) {
        System.out.println(message);
    }
}

When use new Draw<Test>() and try to run T.info("Test");
it only printed "failed"
Am I did anything wrong?

A: Static methods don't get overridden. You have to call Test.info to call your method.
Static methods are on interfaces because it's a convenient place to put them. It's not something you can override, and it's not a default method. Default methods aren't static, and you have to use the default keyword.
If you want polymorphism, use instance methods, not static ones.


text:
Q: Minecraft webpage links in chat? I have seen links in servers that can send you to a page in a browser, is there any way to replicate this with command blocks?
I don't mean command links, I mean web pages.

A: The /tellraw command allows you to output to chat with more formatting options than /say. You'll need to use this, and the JSON format that it uses, to add clickable links to chat.
Here's a guide to the format tellraw (and signs, books and titles) use, if you are not already familiar with it.
Links can be added using the open_url click event. Example:
/tellraw @p {"text":"Arqade","clickEvent":{"action":"open_url","value":"http://gaming.stackexchange.com"}}

Here's a tellraw generator that allows you to add open_url click events, which is usually easier than writing it manually.


text:
Q: How can I sort variables based on part of a string variable? I have a dataset with string variables and I am trying to generate a new binary variable based on the first two characters. All strings are 5 characters long, but I'm only concerned with the first two in order to sort.
For example, I could have 22001 and 22005. Since both are of the form 22XXX, I want to assign value 1 for both in the variable type_A. And if I have 25001 and 25005, since both are not of the form 22XXX, I want to assign value 0 for both in the variable type_A.

A: This should do the job:
clear
set obs 4

generate str5 var1 = "22001" in 1
replace var1 = "22005" in 2
replace var1 = "25001" in 3
replace var1 = "25005" in 4

gen type_A = substr(var1, 1, 2) == "22"

Please note that as you explain your problem it looks like you you are storing 22005 as text - which may not necessarily be the best idea..


text:
Q: How to tune a Ruby on Rails application running on Heroku which uses production level Heroku Postgres? The Company I work for decided on moving their entire stack to Heroku. The main motivation was it's ease of use: No sysAdmin, no cry. But I still have some questions about it...
I'm making some load and stress tests on both application platform and Postgres service. I'm using blitz as an addon of Heroku. I attack on the site with number of users between 1 to 250. There are some very interesting results I got and I need help on evaluating them.
The Test Stack:
Application specifications
It hasn't anything that much special at all.

*

*Rails 4.0.4

*Unicorn

*database.yml set up to connect to Heroku postgres.

*Not using cache.

Database
It's a Standard Tengu (naming conventions of Heroku will kill me one day :) properly connected to the application.
Heroku configs
I applied everything on unicorn.rb as told in "Deploying Rails Applications With Unicorn" article. I have 2 regular web dynos.
WEB_CONCURRENCY  : 2
DB_POOL          : 5

Data

*

*episodes table counts 100.000~

*episode_urls table counts 300.000~

*episode_images table counts 75.000~

Code
episodes_controller.rb
  def index
    @episodes = Episode.joins(:program).where(programs: {channel_id: 1}).limit(100).includes(:episode_image, :episode_urls)
  end

episodes/index.html.erb
<% @episodes.each do |t| %>
<% if !t.episode_image.blank? %>

<%= image_tag(t.episode_image.image(:thumb)) %>

<% end %>

<%= t.episode_urls.first.mas_path if !t.episode_urls.first.blank?%>

<%= t.title %>

<% end %>

Scenario #1:
Web dynos   : 2
Duration    : 30 seconds
Timeout     : 8000 ms
Start users : 10
End users   : 10

Result:
HITS 100.00% (484)
ERRORS 0.00% (0)
TIMEOUTS 0.00% (0)

This rush generated 218 successful hits in 30.00 seconds and we
  transferred 6.04 MB of data in and out of your app. The average hit
  rate of 7.27/second translates to about 627,840 hits/day.

Scenario #2:
Web dynos   : 2
Duration    : 30 seconds
Timeout     : 8000 ms
Start users : 20
End users   : 20

Result:
HITS 100.00% (484)
ERRORS 0.00% (0)
TIMEOUTS 0.00% (0)

This rush generated 365 successful hits in 30.00 seconds and we
  transferred 10.12 MB of data in and out of your app. The average hit
  rate of 12.17/second translates to about 1,051,200 hits/day. The
  average response time was 622 ms.

Scenario #3:
Web dynos   : 2
Duration    : 30 seconds
Timeout     : 8000 ms
Start users : 50
End users   : 50

Result:
HITS 100.00% (484)
ERRORS 0.00% (0)
TIMEOUTS 0.00% (0)

This rush generated 371 successful hits in 30.00 seconds and we
  transferred 10.29 MB of data in and out of your app. The average hit
  rate of 12.37/second translates to about 1,068,480 hits/day. The
  average response time was 2,631 ms.

Scenario #4:
Web dynos   : 4
Duration    : 30 seconds
Timeout     : 8000 ms
Start users : 50
End users   : 50

Result:
HITS 100.00% (484)
ERRORS 0.00% (0)
TIMEOUTS 0.00% (0)

This rush generated 484 successful hits in 30.00 seconds and we
  transferred 13.43 MB of data in and out of your app. The average hit
  rate of 16.13/second translates to about 1,393,920 hits/day. The
  average response time was 1,856 ms.

Scenario #5:
Web dynos   : 4
Duration    : 30 seconds
Timeout     : 8000 ms
Start users : 150
End users   : 150

Result:
HITS 71.22% (386)
ERRORS 0.00% (0)
TIMEOUTS 28.78% (156)

This rush generated 386 successful hits in 30.00 seconds and we
  transferred 10.76 MB of data in and out of your app. The average hit
  rate of 12.87/second translates to about 1,111,680 hits/day. The
  average response time was 5,446 ms.

Scenario #6:
Web dynos   : 10
Duration    : 30 seconds
Timeout     : 8000 ms
Start users : 150
End users   : 150

Result:
HITS 73.79% (428)
ERRORS 0.17% (1)
TIMEOUTS 26.03% (151)

This rush generated 428 successful hits in 30.00 seconds and we
  transferred 11.92 MB of data in and out of your app. The average hit
  rate of 14.27/second translates to about 1,232,640 hits/day. The
  average response time was 4,793 ms. You've got bigger problems,
  though: 26.21% of the users during this rush experienced timeouts or
  errors!

General Summary:

*

*The "Hit Rate" never  goes beyond the number of 15 even though 150 users sends request to the application.

*Increasing number of web dynos does not help handling requests.

Questions:

*

*When I use caching and memcached (Memcachier add-on from Heroku) even 2 web dynos can handle >180 hits per second. I'm just trying to understand what can dynos and the postgres service can do without cache. This way I'm trying to understand how to tune them. How to do it?

*Standard Tengu is said to have 200 concurrent connections. So why it never reaches that number?

*If having a prdouction level db and increasing web dynos won't help to scale my app, what's the point to use Heroku?

*Probably the most important question: What am I doing wrong? :)
Thank you for even reading this crazy question!

A: I particularly figured out the issue.
Firstly, remember my code in the view:
<% @episodes.each do |t| %>
<% if !t.episode_image.blank? %>

<%= image_tag(t.episode_image.image(:thumb)) %>

<% end %>

<%= t.episode_urls.first.mas_path if !t.episode_urls.first.blank?%>

<%= t.title %>

<% end %>

Here I'm getting each episodes episode_image inside my iteration. Even though I've been using includes in my controller, there was a big mistake at my table schema. I did not have index for episode_id in my episode_images table!. This was causing an extremely high query time. I've found it using New Relic's database reports. All other query times were 0.5ms or 2-3ms but episode.episode_image was causing almost 6500ms!
I don't know much about the relationship between query time and application execution but as I added index to my episode_images table, now I can clearly see the difference. If you have your database schema properly, you'll probably won't face any problem with scaling via Heroku. But any dyno can not help you with a badly designed database.
For people who might run into same problem, I would like to tell you about some of my findings of relationship between Heroku web dynos, Unicorn workers and Postgresql active connections:
Basically, Heroku provides you a dyno which is some kind of a small virtual machine having 1 core and 512MB ram. Inside that little virtual machine, your Unicorn server runs. Unicorn has a master process and worker processes. Each of your Unicorn workers has their own permanent connection to your existing Postgresql server (Don't forget to check out this) It basically means that when you have a Heroku dyno up with 3 Unicorn workers running on it, you have at least 4 active connections. If you have 2 web dynos, you have at least 8 active connections.
Let's say you have a Standard Tengu Postgres with 200 concurrent connections limit. If you have problematic queries with bad db design neither can db nor more dynos can save you without cache... If you have long running queries you have no choice other than caching, I think.
All above is my own findings, if there is anything wrong with them please warn me by your comments.


text:
Q: Inherited return type with contravariant type parameter I have a trait with covariant type A that declares (among others) this method:
sealed trait MaxPQ[+U] {
...
def insert[K >: U : Ordering](v: K): this.type
...
}

abstract class AbstractMaxPQ[U : Ordering] extends MaxPQ[U]

I also have this mix-in that I need to use:
trait FindMin[U] {

  self: AbstractMaxPQ[U] =>

I am returning this.type because I want Node or Array based implementations of the priority queue to return current types and not MaxPQ[U].
In the array based implementation I have the following:
class ArrayMaxPQ[U : Ordering : ClassTag] ...extends AbstractMaxPQ[U] with FindMin[U]{
...
override def insert[K >: U : Ordering](v: K): ArrayMaxPQ[U] = ???
...

this is what is auto-generated by my IDE. Of course I need this method to return ArrayMaxPQ[K].
this.type doesn't take type parameters. Using higher-kinded types here also wouldn't work
def insert[K >: U : Ordering, G[_] <: MaxPQ[_]](v: K): G[K]

since G cannot be parameterized with self type in children.
I am a bit confused since this feels like a simple requirement but I cannot find language feature/syntax required to implement it.

A: You can actually use higher-kinded types to do this. It's called F-bounded polymorphism.
sealed trait MaxPQ[+U, F[_]] { self: F[_ <: U] =>
  def insert[K >: U: Ordering](v: K): F[K]
}

abstract class AbstractMaxPQ[U: Ordering, F[_]] extends MaxPQ[U, F] {
  self: F[U] =>
}

class ArrayMaxPQ[U: Ordering: ClassTag] extends AbstractMaxPQ[U, ArrayMaxPQ] {
  override def insert[K >: U: Ordering](v: K): ArrayMaxPQ[K] = ???
}

Scastie demo
Instead of passing G into insert, use it as a type parameter of the class/trait itself, and then make sure that this extends that. That's what the self-type is for (self: F[U]). Another useful question

A: Maybe you want the return type to be wider than this.type but narrower than just MaxPQ[U]. Then try to introduce a type member
sealed trait MaxPQ[+U] {
  type This <: MaxPQ[U]
  // type This >: this.type <: MaxPQ[U] { type This = MaxPQ.this.This }

  def insert[K >: U : Ordering](v: K): This
}

abstract class AbstractMaxPQ[U : Ordering] extends MaxPQ[U] {
  override type This <: AbstractMaxPQ[U]
  // override type This >: this.type <: AbstractMaxPQ[U] { type This = AbstractMaxPQ.this.This }
}

class ArrayMaxPQ[U : Ordering : ClassTag] extends AbstractMaxPQ[U] {
  override type This = ArrayMaxPQ[U]

  override def insert[K >: U : Ordering](v: K): ArrayMaxPQ[U] = ???
}

Returning the "Current" Type in Scala

If you want the return type to be parametrized with an upper bound of U try to make This higher-kinded
sealed trait MaxPQ[+U] {
  type This[K >: U] <: MaxPQ[K]
  // type This[K >: U] <: MaxPQ[K] { type This[K1 >: K] = MaxPQ.this.This[K1] }

  def insert[K >: U : Ordering](v: K): This[K]
}

abstract class AbstractMaxPQ[U : Ordering] extends MaxPQ[U] {
  override type This[K >: U] <: AbstractMaxPQ[K]
  // override type This[K >: U] <: AbstractMaxPQ[K] { type This[K1 >: K] = AbstractMaxPQ.this.This[K1] }
}

class ArrayMaxPQ[U : Ordering : ClassTag] extends AbstractMaxPQ[U] {
  override type This[K >: U] = ArrayMaxPQ[K]

  override def insert[K >: U : Ordering](v: K): ArrayMaxPQ[K] = ???
}


text:
Q: typescript debug / breakpoint does not work Since few days, debugger does not work anymore. I've tried several things without success.

*

*typescript 0.9.1

*VS2012

*IE10

*the source map, JS files are updated when I save the TS files

In Visual studio at the place of the breakpoint I've got:
'The breakpoint will not currently be hit. No symbols have been loaded for this document'

*

*Any help?

*How IE load the symbols? I assume it's related to the source map ...
Thank in advance
Richard

A: I had a similar problem, but with Visual Studio 2013. No breakpoints were hit, even though I was running in debug mode and with source maps generated.
I found out that after I included the compiled .js files in the project, my breakpoints in TypeScript started hitting.

A: Here is the answer (of my question ... with the help of WiredPrairie, ... ;-) )
This line
<Import Project="$(VSToolsPath)\TypeScript\Microsoft.TypeScript.targets" Condition="'$(BuildingInsideVisualStudio)' == 'true'" />

was preceeding my lines
 <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
    <TypeScriptTarget>ES5</TypeScriptTarget>
    <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
    <TypeScriptSourceMap>true</TypeScriptSourceMap>
    <TypeScriptModuleKind>AMD</TypeScriptModuleKind>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)' == 'Release'">
    <TypeScriptTarget>ES5</TypeScriptTarget>
    <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
    <TypeScriptSourceMap>true</TypeScriptSourceMap>
    <TypeScriptModuleKind>AMD</TypeScriptModuleKind>
  </PropertyGroup>

So I put it AFTER ( what a smart guys, isn't it ;-) ) in my *.csproj
I found the problem because:

*

*The //# sourceMappingURL=/path/to/file.js.map was generated at the end of the *.js files when saving, not when compiling.

*The build output was saying The TypeScript Compiler was given an empty configurations string, which is unusual and suspicious..
The solution comes from this post: TypeScript Compiler was given an empty configurations string.
The root cause of the problem appears when I tried to deploy my project to Azure. The js files were not uploaded/compiled, so i've added this tricky line in the csproj bad luck :-(
Thank and I hope it will help others.

A: The following is for people who are using Chrome or Firefox for the environment...
Apparently you just simply can't get it to work with VS but not all is lost as the author of this article shows.
Hope it helps some more struggles to get debugging :)

A: In my case the answer was that another script file was actually used by the html.
Once this was fixed, breakpoints started working, of course.


text:
Q: WiFi connection after resume from Hibernate My Windows 10 laptop uses the following power options for "Wireless Adapter Settings":

If I hibernate the laptop and return later, I typically find that the WiFi adapter is no longer connected.  I noticed that if I wait for a few minutes, the WiFi will reconnect.
Is there any way to prevent Windows from disconnecting the adapter when I hibernate?
Is there a way to speed up the reconnection for the adapter?


text:
Q: How to make different item list with jquery Its working but..  href= doesnt work , i dont know why. ANd when mouse hover of items.. I can not click button and i can not click the avatar ?.. Thank for answer.
You can check example from here.

A: Your description wasn't very helpful as the comments above mentioned. But I've created a jsFiddle here from your above code, and this seems to run fine. The only things I have changed are as follows.
On your on trigger you have targeted ".kisiliste<?=$sayfa?> .kisi"... I can only assume .kisiliste<?=$sayfa?> references a html element you have not included. So i changed this to simply .kisi.
Also I added a ; to the end of your fadeIn and fadeOut animations. Apart from that it works fine.
Please don't to forget to tick answers if they help.
EDIT-----------------------------------------------------------------
The issue is to do with your css. Please see this fixed link.
I have changed two elements.
From #kisiliste .kisi .sabitle{} I removed z-index:-1
and have added a block display on #kisiliste .kisi .sabitle .avatar a{display:block}
This seems to have sorted the issues for both the hover problem and the avatar click.


text:
Q: Export / Import tool with Google Spanner I have several questions regarding the Google Spanner Export / Import tool.  Apparently the tool creates a dataflow job.

*

*Can an import/export dataflow job be re-run after it had run successfully from the tool? If so, will it use the current timestamp?

*How to schedule a daily backup (export) of Spanner DBs?

*How to get notified of new enhancements within the GCP platform?   I was browsing the web for something else and I noticed that the export / import tool for GCP Spanner had been released 4 days earlier.
I am still browsing through the documentation for dataflow jobs and templates, etc..  Any suggestions to the above would be greatly appreciated.
Thx

A: My response based on limited experience with the Spanner Export tool.

*

*I have not seen a way to do this. There is no option in the GCP console, though that does not mean it cannot be done.

*There is no built-in scheduling capability. Perhaps this can be done via Google's managed Airflow service, Cloud Composer (https://console.cloud.google.com/composer)? I have yet to try this, but it is next step as I have similar needs.

*I've made this request to Google several times. I have yet to get a response. My best recommendation is to read the change logs when updating the gcloud CLI.
Finally-- there is an outstanding issue with the Export tool that causes it to fail if you export a table with 0 rows. I have filed a case with Google (Case #16454353) and they confirmed this issue. Specifically:

After running into a similar error message during my reproduction of
  the issue, I drilled down into the error message and discovered that
  there is something odd with the file path for the Cloud Storage folder
  [1]. There seems to be an issue with the Java File class viewing
  'gs://' as having a redundant '/' and that causes the 'No such file or
  directory' error message.
Fortunately for us, there is an ongoing internal investigation on this
  issue, and it seems like there is a fix being worked on. I have
  indicated your interest in a fix as well, however, I do not have any
  ETAs or guarantees of when a working fix will be rolled out.


text:
Q: Howto "git ls" files marked by git as "deleted by us" I started to use git cherrypick; and as a result of that I am now (very often) facing situations that give me a lot of files marked as "deleted by us".
I saw this other question, that mentioned how can use git ls-files --deleted to get a flat file list; which can then be piped to xargs rm.
Problem is: --deleted doesn't list those "deleted by us" files.
So, long story short: what is the easiest/straight forward way of removing the "deleted by us" files?
( I really liked the git ls-files approach; as that doesn't require sed/awk magic; so there is also no worrying about getting quotes right ...)
Update; just to explain why this not some "XY problem" situation:

*

*actually I am using git svn; to connect to some backend SVN server

*SVN trunk contains directories A, B, C

*I am making changes on trunk that affect all three directories

*But: the git where I run the cherry-pick ... actually resembles "product branches" created on the SVN server. These "product" branches do only contain subsets (so one has A and B; the other has B and C).

*I tried hard; but I really couldn't get to create a git svn clone that contains SVN trunk AND SVN product branches at the same time

A: I don't know of a "simple" command like that for this but you can use git status itself for this.
while read -d '' status file; do
    case "$status" in
        (D?)
            echo "Removing $file that was deleted by us."
            #rm "./$file"
            ;;
    esac
    #printf 'status: %q\nfilename: %q\n' "$status" "$file"
done < <(git status -sz)

To match only DU and not D? (D single-character) change the case pattern appropriately.
To run rm only once use files+=("$file") in the if block and then rm "${files[@]}" at the end.

A: To list unmerged files marked as "deleted by us" the following command can be used:
git status --porcelain --untracked-files=no | sed --silent 's/^DU //p'

or a slightly shorter variant:
git status --porcelain -uno | sed -n 's/^DU //p'

In the output of the command git status --porcelain the unmerged "deleted by us" files are marked with DU.
In sed, the option -n suppresses printing unless explicit requested, the command s/X/Y/ substitute X (a regexp) by Y, and due to the flag p the modified line is printed.


text:
Q: Win 7 Pro 64 will not recognize Keyboard & Mouse - defaults to OSK I am currently running Windows 7 Pro on my PC (new computer).  I have found that in the last couple of months my keyboard has ceased being recognized by the OS.  By this I mean, most of my special characters no longer work properly...  Everything from quotes to question marks, exclamation marks etc. are no longer working or I get completely foreign characters.  AFter considerable investigation I have determined what is actually happening is that the OS is not recognizing the actual keyboard and is defaulting to the On Screen Keyboard.  When looking at my device manager, it shows an ... HID Keyboard device and an HID compliant Mouse.  My keyboard and mouse are wireless (Dell KM714).  I have tried uninstalling both, working thru safe mode and uninstalling, I have tried re-installing the correct drivers, on several occasions and in several different ways but all to no avail.
The keyboard was even swapped out and tried on a 2nd computer...it worked properly on the 2nd computer so that eliminates it as the problem.
I have also tried installing a completely different wired keyboard on the malfunctioning computer with the same negative results.
Existing restore points have the same issue and consequently none work.  I have tried searching for an updated driver but it tells me the best driver is already installed and I have searched the internet for other suggestions all to no avail.  It is clear to me that it simply will not accept any other keyboard or mouse driver.  I have also tried disabling the OSK but that too fails....it still continues to go to the OSK even when configured not to.
Can anybody suggest something new for me to try?  I have even tried tech support for the computer manufacturer and their suggestion is to re-install windows.  This is NOT an option for me.  I feel my only recourse may be to go into the registry settings to try and fix (which Im not afraid to do) but I dont know where or what the correct settings would be.    Any and all suggestions are greatly appreciated.

A: Since a wired keyboard produced the same result, I'd be looking at the keymap.  Try a similar keymap, perhaps US-International, and see if that works.
Not the final answer, but it should be a good diagnostic step.


text:
Q: How to get data from google spread sheets in c# I want to read the data in google spread using c#.I am able to authenticate google drive but I am unable to read the data in google spread sheet.I have used following code
   SpreadsheetsService myService = new SpreadsheetsService("Sample ProjectSheets");
     myService.setUserCredentials(My emailid, My password);
    SpreadsheetQuery query = new SpreadsheetQuery();
    SpreadsheetFeed feed = myService.Query(query);

In the above code , I am getting exception at  myService.Query(query) as An unhandled exception of type 'Google.GData.Client.GDataRequestException' occurred in Google.GData.Client.dll  and build the above code by refering following link:Accessing Google Spreadsheets with C# using Google Data API.
I have one more doubt what to mention as application name in SpreadsheetsService object.


text:
Q: How can I refactor this code that tests if multiple array values are inside another arrays specific key? I have a class which returns rooms. I have a couple methods ( 4-5 ) which all extract "available" parameters the user can specify to this API to return unique results.
In one of these methods, I'm checking if the user-provided string of 'buildings' actually match "valid" buildings. In order to do this, currently I'm doing:
$buildings = $this->_getBuildings();

$buildingIds = array();
foreach ( $buildings as $building ) {
     $buildingIds[] = $building['id'];
}

$valid = true;
foreach ( $userPassedBuildingValues as $value ) {
   if ( !in_array( $value, $buildingIds ) ) {
       $valid = false;
       $this->addError();
   }
}

I'm looking for a way to refactor this so I don't have to loop through all the building elements and create a new array each time I do this comparison. Are there any array mapping/searching functions that may make this easier?
I was contemplating refactoring getBuildings to have an optional argument to return a list of IDs but this would "plague" the function and I don't think it would be as "pure" as it is now.
EDIT #1: First idea was to create a method that took a 'key' and would return a concatenated array of those keys from the array. For instance,
$buildings = $this->_getBuildings();

$buildingIds = $this->_getAllValues( 'id', $buildings );

function _getAllValues( $key, $array ) {
   $return = array();
   foreach ( $array as $rowKey => $row ) {
       if ( $rowKey == $key )
           $return[] = $row[$key]
   }
   return $return;
}

But perhaps there's a different, cleaner approach? I'd be doing the same type of thing for at least 4-5 different functions.
Note: The depth on the arrays will not be more than one, so no need to worry about deeply nested arrays.

A: You can use ouzo-goodies like:
$buildingIds = Arrays::map($buildings, Functions::extract()->id);

Here are links: Functions::extract, Arrays::map.
//EDIT
Here is two classes which can use as a helper.
class Helper
{
    public static function getBuldingIds($buildings)
    {
        return Arrays::map($buildings, Functions::extract()->id);
    }
}

class Helper
{
    public static function getBuldingIds($buildings)
    {
        return array_map(function($building){
            return $building['id'];
        }, $buildings);
    }
}


text:
Q: Set a timer with actions on google Hi I'm currently working on an app for google home / google Assistant
I use dialogflow and after my intent I want to ask the user if I should set a timer for him. How can I achieve this?

A: You do not have access to the timer/alarm on the Google Home or Google Assistant.
In some cases, you can use Notifications to do what you want, but these aren't available on the Google Home yet.


text:
Q: My code to capture the submit button on a form works but am I doing it correctly? I have an HTML form and some JavaScript code below it.  Everything works.  But what bothers me is that while everything else is in a function, the way I capture the submit button is not in a function.
So am I doing this correctly?
My form:
<form autocomplete="off" action="/cgi-bin/prl.pl">

<input id="myInput" type="text" name="myCountry" placeholder="Pick a country" autofocus>
<input id="113" type="submit" value="Ok">
</form>

The top of my scripts:


text:
Q: Function to match columns and values to rows - intersection of DataFrames Lets say I have the following DataFrame:
>>>df = pd.DataFrame([[5,2,3,11],[5,3,3,8],[9,4,11,12],[5,14,15,16]],columns=["a","b","c","d"])
>>>df
   a   b   c   d
0  5   2   3  11
1  5   3   3   8
2  9   4  11  12
3  5  14  15  16

If I wanted to match all the rows which had the column values: 'a' equal to 5, 'b' < 10 and 'c' greater than or equal to 3, I could just do the following:
df[(df['a'] == 5) & (df['b'] < 10) & (df['c'] >= 3)]

and that would give me the result I was after:
   a  b  c   d
0  5  2  3  11
1  5  3  3   8

Entering that code to match the rows was laborious so I decided to make a function called row_matcher which would take 2 arguments: a Pandas DataFrame and a list of lists of length 3 - column of choice, operator and value.
def get_operator_fn(op):
    import operator
    return {
        '<' : operator.lt,
        '<=' : operator.le,
        '==' : operator.eq,
        '!=' : operator.ne,
        '>=' : operator.ge,
        '>' : operator.gt,
        '&' : operator.and_
        }[op]

def row_matcher(df,parameters):
    import pandas as pd
    """Parameter should be [column,operation,value]
    Example: ['trial',"==",1]
    """
    operations = [df[get_operator_fn(operation)(df[column],value)] for column,operation,value in parameters]
    return reduce(lambda left,right: pd.merge(left,right,how='inner'), operations)

>>>row_matcher(df,[["a","==",5],["b","<",10],["c",">=",3]])

Unfortunately with this code it throws up an error for the return reduce(...) line:
TypeError: Could not compare <type 'str'> type with Series
I tried replacing the return reduce(...) line with:
df[reduce(operator.and_,operations)]
This still results in an error: TypeError: unsupported operand type(s) for &: 'str' and 'str'
I would appreciate any assistance.

A: I think this would be a lot simpler using the query() method.  Using this, your initial example can be written as:
df.query('a==5 & b<10 & c>=3')

Honestly, if you use the query() method, I don't think you'd gain much from your function, unless you're reading in lots of conditions from an external file.  If still want to write the row_matcher function, just use string joins to combine your list of lists as a single string, obeying the query() syntax.  Once you have a single string, pass it along to the query() method.
You may need to install the numexpr module to use the query() method.  You can get around this by supplying the keyword argument engine='python' to query() method.  This may be less efficient than using the numexpr module, so it might be worthwhile to install the module if performance becomes an issue.


text:
Q: AS3 blur filter onto a linestyle Is there a way to add a blur filter to a linestyle? Such as
var myBlurFilter:BlurFilter = new BlurFilter();

something.graphics.linestyle().filters = {myBlurFilter};

obviously this would not work, but is there a way to make it work? Perhaps a different method.

A: Filters is a property of DisplayObject. Hence you should add the filter to your something object. Which means you should separate the line with the blur in different object and add filter to it, leaving other graphic not blurred :)
Cheers!


text:
Q: Scala case classes and constructors I'm finding myself writing a lot of (sort of) boilerplate code. For example say I have the following traits
trait Foo {
  def x: Int
}

trait Bar {
  def y: Boolean
  def z: String
}

Then I want a case class that does no more or less than implement these.
case class MyClass(x: Int, y: Boolean, z: String) extends Foo with Bar

This doesn't seem annoying, but now imagine that my traits have a dozen defs each and that the names x, y, and z are much longer. Writing the case class out means I have to rewrite all of these as arguments of MyClass.
Is there a way to generate the x: Int, y: Boolean, z: String constructor part automatically based on the traits I extend?

A: I think what you are looking for is an annotation macro that can handle this work for you. You would then invoke this macro by writing something like this:
@FieldsFromTraits
case class MyClass extends Foo with Bar

Annotation macros can then rewrite your case class with information from the traits.
A library that does something similar is MetaRest. You might try to adapt that implementation. I'll see if I can't put something together tonight.


text:
Q: Bootstrap doesn't load directly I have a problem with my VueJs frontend, I have a BootstrapVue navbar component, my problem is that when the page loads (or reloads), there is a small amount of time that the navbar is displayed without loading the bootstrap, this is quite annoying.
Here is my navbar code:
<div id="navbar">
<b-navbar toggleable="lg" type="light" variant="light">
{% if user.is_authenticated and user.is_staff %}
<b-navbar-brand href="{% url 'home' %}"> Inicio </b-navbar-brand>
<b-navbar-toggle target="nav-collapse"></b-navbar-toggle>
<b-collapse id="nav-collapse" is-nav>

  <b-navbar-nav>
    <!-- Navbar dropdowns -->
    <b-nav-item-dropdown text="Maestros">
      <b-dropdown-item href="#">Candidatos</b-dropdown-item>
      <b-dropdown-item href="#">Candidaturas</b-dropdown-item>
      <b-dropdown-item href="#">Centros</b-dropdown-item>
      <b-dropdown-item href="#">Circunscripciones</b-dropdown-item>
      <b-dropdown-item href="{% url 'elecciones' %}">Elecciones</b-dropdown-item>
      <b-dropdown-item href="#">Estudios</b-dropdown-item>
      <b-dropdown-item href="{% url 'locales' %}">Locales de votación</b-dropdown-item>
      <b-dropdown-item href="#">Mesas</b-dropdown-item>
      <b-dropdown-item href="#">Urnas</b-dropdown-item>
    </b-nav-item-dropdown>

    <b-nav-item-dropdown text="Personas" right>
      <b-dropdown-item href="#">Account</b-dropdown-item>
      <b-dropdown-item href="#">Settings</b-dropdown-item>
    </b-nav-item-dropdown>

    <b-nav-item-dropdown text="Datos Personales" right>
      <b-dropdown-item href="#">Account</b-dropdown-item>
      <b-dropdown-item href="#">Settings</b-dropdown-item>
    </b-nav-item-dropdown>
    <b-nav-item-dropdown text="Consulta Censo" right>
      <b-dropdown-item href="#">Account</b-dropdown-item>
      <b-dropdown-item href="#">Settings</b-dropdown-item>
    </b-nav-item-dropdown>
    <b-nav-item-dropdown text="Seguimiento" right>
      <b-dropdown-item href="#">Account</b-dropdown-item>
      <b-dropdown-item href="#">Settings</b-dropdown-item>
    </b-nav-item-dropdown>
    <b-nav-item-dropdown text="Resultados" right>
      <b-dropdown-item href="#">Account</b-dropdown-item>
      <b-dropdown-item href="#">Settings</b-dropdown-item>
    </b-nav-item-dropdown>
  </b-navbar-nav>
  {% endif %}
  <!-- Right aligned nav items -->
  <b-navbar-nav class="ml-auto">
    {% if user.is_authenticated %}
      <b-nav-item href="{% url 'logout' %}">{{ user.username }} - Cerrar sesión</b-nav-item>
    {% endif %}
  </b-navbar-nav>
</b-collapse>

And below I define the element:
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.js">   </script>
 <script src="//unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
 <script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
 <script>
   new Vue({ el: '#navbar' });
 </script>


text:
Q: Why the FOREIGN KEY doesn't work for the LOOP? I've created two tables:
1.Table
CREATE TABLE IF NOT EXISTS  us_tAddress (
 id INT(6) UNSIGNED   AUTO_INCREMENT PRIMARY KEY,
 country VARCHAR(100),
 city VARCHAR(100),
 zip VARCHAR(100),
 street VARCHAR(100),
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
 )

The "address_id" column in the "us_tUser" table is a FOREIGN KEY in the "us_tUser" table.
2.TABLE
CREATE TABLE IF NOT EXISTS us_tUser(
 id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 address_id INT (6) UNSIGNED,
 first_name VARCHAR(100),
 last_name VARCHAR(100),
 position VARCHAR(100),
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 FOREIGN KEY (address_id)  REFERENCES us_tAddress(id)
   )

For inserting values into second table from array, I am using Loop:
foreach ($array as $row => $value) {

             $first_name    = mysqli_real_escape_string($conn,$value['first_name']);
             $last_name    = mysqli_real_escape_string($conn,$value['last_name']);
             $position     = mysqli_real_escape_string($conn,$value['position']);
             $sql = "INSERT INTO us_tUser ( first_name, last_name, position)
             VALUES ( '".$first_name."', '".$last_name."', '".$position."' )";
             mysqli_query($conn,$sql);

What I should change in the script, because the result in  address_id  column is NULL. (Let's see picture bellow)

Thank you in Advance!

A: you did not stop add null value to address_id column so you can add NOT NULL to us_tUser table and create it
CREATE TABLE IF NOT EXISTS us_tUser(
 id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 address_id INT (6) UNSIGNED NOT NULL,
 first_name VARCHAR(100),
 last_name VARCHAR(100),
 position VARCHAR(100),
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 FOREIGN KEY (address_id)  REFERENCES us_tAddress(id)
);

or ALTER it to us_tUser table
ALTER TABLE `us_tUser` MODIFY COLUMN address_id INT (6) UNSIGNED NOT NULL;

Add that to your table you can not insert data without data for address_id column. if you want to insert data without data for address_id column I recommend don't add this or add DEFAULT value to that column


text:
Q: DOMException Error: Is Google Drive still supporting Embed Link with the /preview? If you open a PDF file from Google Drive in a new window and go to the vertical 3 dots menu, you still can see the Embed item... option being made available to you. As such, I assume that Google still allows the PDF files to be embedded as shown below:

But as a result, I get the following errors being output to the Chrome browser console:
Uncaught (in promise) DOMException: Failed to execute 'getLayoutMap' on 'Keyboard': getLayoutMap()
must be called from a top-level browsing context.

I even tried with <embed> and <object> but no luck. I'm OK if it is just a warning and not an error, which is quite severe in the context of SEO. I just want to confirm if this is a bug or Google has officially discontinued the embed service, otherwise what would be the solution to tackle this issue? I just explored the Google Drive API but it doesn't seem to offer any solution for a proper HTML embed in particular.
Please advise. Thanks in advance!


text:
Q: How to remove splashscreen in buildbox I'm using buildbox 30 days challenge.
I have made a game using this platform. I wanted to ask how to remove the splash screen with the loading bar in buildbox. I replaced the image in the exported png with my own png taking the same dimension and everything. When i try to export it and compile it into eclipse. The app doesn't start. It's get stuck in the start?
Here's the splashscreen by default. The loading bar also disappear when i try to export it into apk.

A: This is the splash screen for the trial version of Buildbox.  The only way to remove this is to purchase the full version.  In fact, this is the only difference between the trial and the full version (besides the trial only working for 30 days).


text:
Q: Is it possible to time adjust push mail on iOS 5? Is it possible to time adjust push mail on my iPhone? What I want is that the phone automatically adjust the push setting for some time slots a day. E.g. that it should push mail between 9-17, but after 17 it should not push mail for an account. Is there an app for that?

A: There is no simple app for this in the default Mail app as unfortunately there is no way for an app to change this setting. You either have to accept notifications all of the time, or manually turn them on/off in the Settings app every time you want to change them as @afragen said.
There may be other email apps that will provide this functionality, but I've not come across any.

A: This isn't currently an option, but in iOS 6, Notifications will have a "Do Not Disturb" feature, so you can mute them at certain hours of the day. It won't stop your phone from receiving mail, but the alerts won't bother you.

A: Turn off Notifications from the Settings > Notifications tab. Search for Mail and turn off all notification settings.
If you also want you might need to go to Settings > General > Sounds and turn off the New Mail sound.

A: It might be possible to set your home WiFi router to disable internet access in general or for a specific device or specific service (like Mail) during certain hours. This would normally be under a Parental Controls section of the router setup.


text:
Q: Increase Filter Limit in Apache Superset I am trying to create a filter for a field that contains over 5000 unique values. However, the filter's query is automatically setting a limit of 1000 rows, meaning that the majority of the values do not get displayed in the filter dropdown.
I updated the config.py file inside the 'anaconda3/lib/python3.7/site-packages' directory by increasing the DEFAULT_SQLLAB_LIMIT and QUERY_SEARCH_LIMIT to 6000, however this did not work.
Is there any other config that I need to update?
P.S - The code snippet below shows the json representation of the filter where the issue seems to be coming from.
"query": "SELECT casenumber AS casenumber\nFROM pa_permits_2019\nGROUP BY casenumber\nORDER BY COUNT(*) DESC\nLIMIT 1000\nOFFSET 0"

A: After using the grep command to find all files containing the text '1000', I found out the the filter limit can be configured through the filter_row_limit in viz.py


text:
Q: Intercept jTable selection change events I found this forum thread which suggests overriding ListSelectionModel to prevent rows from being selected.
I would like to prevent selection changes when there are unsaved changes (external to the table) for the currently selected item UNTIL the user confirms the discard. Something like:
public class confirmSelectionChange extends DefaultListSelectionModel {
    public void setSelectionInterval(int index0, int index1) {
        if (unsavedChanges()) {
            super.setSelectionInterval(int index0, int index1);
        }
    }

    private boolean unsavedChanges() {
        if (noUnsavedChangesExist) {
            return true;
        }

        // Present modal dialog: save, discard cancel
        if (dialogAnswer == SAVE) {
            // save changes
            return true;
        } else if (dialogAnswer == DISCARD) {
            return true;
        } else {
            return false;
        }
    }
}

Is it possible to insert blocking code in the middle of ListSelectionModel changes? Is there a better way to intercept selection change events?
I'm already listening for them but the change has already happened by then.

A: My final solution (thanks in part to this code guru) was to create an anonymous inner class that extends JTable and overrides changeSelection(). Tried a separate class since I read that some people don't think anonymous inner classes are good OO design but I needed to know about the editing state plus I had to call save/discard methods. Who needs encapsulation when it's your own code anyway? ;-)
jTableMemberList = new JTable() {
    public void changeSelection(int rowIndex, int columnIndex, boolean toggle,
                                boolean extend) {
        // Member is being edited and they've clicked on a DIFFERENT row (this
        // method gets called even when the selection isn't actually changing)
        if (editModeIsActive && getSelectedRow() != rowIndex) {
            // User was editing, now they're trying to move away without saving
            Object[] options = {"Save", "Discard", "Cancel"};
            int n = JOptionPane.showOptionDialog(this,
                                            "There are unsaved changes for the "
                                            + "currently selected member.\n\n"
                                            + "Would you like to save them?",
                                            "Save changes?",
                                            JOptionPane.YES_NO_CANCEL_OPTION,
                                            JOptionPane.WARNING_MESSAGE,
                                            null,
                                            options,
                                            options[0]);

            if (n == JOptionPane.YES_OPTION) {
                saveChanges();
            } else if (n == JOptionPane.NO_OPTION) {
                discardChanges();
            } else {
                // Exit without passing call on to super
                return;
            }
        }

        // make the selection change
        super.changeSelection(rowIndex, columnIndex, toggle, extend);
    }
};

This solution seems to work so far but I haven't tested it extensively. There may be bugs or gotcha's lurking in one of the dark corners of this code...
Hope it helps someone else!


text:
Q: Sharing data via the cloud I've got some stuff that I want to be able distribute to my totally real friends, but I don't want to have to email them every time I change something.
How can I set up sharing via the cloud?

A: Tips:
When you put stuff in the cloud it's good to use your short URL in the URI (or copy it in after to shrink down the link length and scariness):
CloudPut[1, "user:b3m2a1/whee"]

CloudObject["https://www.wolframcloud.com/objects/b3m2a1/whee"]

The cloud happily makes this really easy. Say we just want to distribute some expression to someone. All we need is the following:
In[307]:= CloudExport[
 BinarySerialize["hello!"],
 "Package",
 Permissions -> "Public"
 ]

Out[307]= \
CloudObject["https://www.wolframcloud.com/objects/5e6e9b45-1018-46c5-\
bd87-17693d883732"]

And then our friend can go to that link and the thing will download for them to work with. Or, better yet, they can import it directly into Mathematica:
In[308]:= CloudImport@CloudObject[
 "https://www.wolframcloud.com/objects/5e6e9b45-1018-46c5-bd87-\
17693d883732"]

Out[308]= ByteArray[< 10 >]

For that they, too, will need a free cloud account, but if they don't want to do that all is not lost. The resource is still semi-accessible via Import:
In[312]:= Import[CloudObject[
 "https://www.wolframcloud.com/objects/5e6e9b45-1018-46c5-bd87-\
17693d883732"],
 "Text"
 ]

Out[312]= "(* Created with the Wolfram Language : www.wolfram.com *)
\
ByteArray[\"NzpTBmhlbGxvIQ==\"]"

And a quick little ToExpression will extract what we need.
Note that this won't alway work absolutely as formatting can get wonky.
Furthermore, if we use a fixed URL:
In[319]:= CloudExport[
 BinarySerialize["hello!"],
 "Package",
 "hello-array",
 Permissions -> "Public"
 ]

Out[319]= \
CloudObject["https://www.wolframcloud.com/objects/user-affd7b1c-ecb6-\
4ccc-8cc4-4d107e2bf04a/hello-array"]

our friend need only know one URL and the updating version will always be available
Packages
Where this really gets cool, though, is how you can distribute packages.
The CloudGet function acts just like Get but for the cloud, and so if you have a package file and you copy it to the cloud via CopyFile, your friend can run CloudGet on that and all of your code will become immediately accessible to them.
Paclets
But wait! There's more!
We can set up a paclet site in the cloud so that our entire application can be easily distributed. And we can combine this with CloudGet to configure an auto-installer for our package. Run this:
CloudGet@"https://wolfr.am/l514yL7C"

and (assuming I haven't broken anything since I last tested it) you'll get the current version of a package of little tools I wrote. Note that I used URLShorten on the longer URL that that hides.
You can then uninstall this via:
CloudGet@"https://wolfr.am/l51cHPOm"

Standard HTML Content
Note, too, that the cloud can take standard HTML/CSS content, too.
I have code that will turn a PacletSite.mz into an HTML page that can be deployed.

Update: full static websites
So going above and beyond what I'd done before with the cloud I recently wrote a system to push a full static website up there: https://www.wolframcloud.com/objects/b3m2a1/home/building-websites-with-mathematica.html#main-content
The www.wolframcloud.com/objects is ugly, yes, but it's so convenient to just be able to push things from within Mathematica (as I write my posts and pages in Mathematica anyway).


text:
Q: Javascript, move a specific image on button click I want to make something using javascript, i got an image which is a track, and 4 people running from the left of the track to the right. So basically all what they need to do is move to the right.
I'm trying to move a image to the right when i click a button. See i managed to move a image but when i duplicated the function, it would only do it for the last image.

I tried different stuff

*

*So i tried to change all variables for every function but it still will only move the last image.

*I tried to put If statements but i don't know how exactly how they work, so this might work but i couldn't make it work.

*I did also some research on the function init(), which i don't understand completely, but i tried changing around with it but i couldn't make it work

    code

<button id="lopergroenbutton" onclick="moveGreenRight();">groen</button>
<button id="loperroodbutton" onclick="moveRedRight();">rood</button>
<button id="lopergeelbutton" onclick="moveYellowRight();">geel</button>
<button id="loperblauwbutton" onclick="moveBlueRight();">blauw</button>

Thanks and sorry for my bad english.

A: Sir, you are overwriting the init function, use different names for each init function. E.g. init1, init2, init3, init4

A: You should have a single init function where you initialize all the image  handlers

var imgObjgroen = null;
       var imgObjrood = null;
var imgObjgeel = null;
   var imgObjblauw = null;
 function init(){
               imgObjblauw = document.getElementById('loperblauw');
               imgObjblauw.style.left = '35px';
              imgObjgeel = document.getElementById('lopergeel');
               imgObjgeel.style.left = '35px';
               imgObjrood = document.getElementById('loperrood');
               imgObjrood.style.left = '35px';
              imgObjgroen = document.getElementById('lopergroen');
               imgObjgroen.style.left = '35px';
            }
            function moveGreenRight(){
               imgObjgroen.style.left = parseInt(imgObjgroen.style.left) + 95 + 'px';
            }

            function moveRedRight(){
               imgObjrood.style.left = parseInt(imgObjrood.style.left) + 95 + 'px';
            }

            function moveYellowRight(){
               imgObjgeel.style.left = parseInt(imgObjgeel.style.left) + 95 + 'px';
            }

            function moveBlueRight(){
               imgObjblauw.style.left = parseInt(imgObjblauw.style.left) + 95 + 'px';
            }

            window.onload =init;

<button id="lopergroenbutton" onclick="moveGreenRight();">groen</button>
<button id="loperroodbutton" onclick="moveRedRight();">rood</button>
<button id="lopergeelbutton" onclick="moveYellowRight();">geel</button>
<button id="loperblauwbutton" onclick="moveBlueRight();">blauw</button>


text:
Q: Force Contextual Action Bar (CAB) for an Activity I want an acitivy to show a Contextual Action Bar, not normal ActionBar. The reason is that I show this activity in resonse for user long-clicking an item.
I know how to hide title and in general make the normal ActionBar look similar to CAB, but not quite. May be there is a simple way of doing it?
Update:
My question is similar, but not a complete duplication of how to invoke the actionbars context menu like behavior question
The difference is that I dont want at all to show a "normal" ActionBar, always the one that looks like Contextual ActionBar.
The suggestion to move to ActionMode right in the activity onCreate.
ActionMode.Callback onDestroyActionMode() that is called when ActionMode ends, we would simply finish() the activity.
It is a good one and almost does it. There are two subtle problems with this approach.
One, there is an observable flicker when ActionBar shows and immediately goes to CAB.
Second, the more substatial one is that there is no way to differentiate between edits that we want to "accept" and "decline". I would want checkmark mean that edits need to be accepted, and "back" button mean that edits need to be discarded. Unfortunately the suggested hack results in both routes ending with the call to onDestroyActionMode()
I could have added more CAB action items, for saving or exiting without saving, but this defeats the purpose of having separate editing activity.


text:
Q: Return max value with stored procedure I need to get maximal value from the table and return it to backend method, but I did this in a wrong way. At present time I have something like this
CREATE PROCEDURE [firstProcedure]
    @_maxEntityId VARCHAR(3) OUTPUT
BEGIN
    SET @_maxEntityId = 'SELECT MAX(entityId) FROM TableFrom'
    PRINT @_maxEntityId
    RETURN (@_maxEntityId)
END

Trying to print @_maxEntityId but didn't see anything.

A: CREATE PROCEDURE [firstProcedure]
    @maxEntityId INT OUTPUT
AS
BEGIN
    SELECT
        @maxEntityId = MAX(entityId)
    FROM
        TableFrom
    PRINT @maxEntityId

    RETURN (@maxEntityId)
END

A: You do not need to return result because the parameter is OUTPUT already. SP should be like below:
CREATE PROCEDURE [firstProcedure]
    @maxEntityId INT OUTPUT
AS
BEGIN
    SELECT
        @maxEntityId = MAX(entityId)
    FROM
        TableFrom
END

Here is to invoke the SP
DECLARE
        @maxEntityId INT

EXEC    [firstProcedure]
        @firstProcedure= @firstProcedureOUTPUT

SELECT  @firstProcedureas N'@firstProcedure'