text:
Q: X11/GLX window above desktop I want create opengl application for desktop, but icons and wallpaper are break down.
Window should be under icons:

code for create window:
XSetWindowAttributes swa;
swa.background_pixmap = ParentRelative;
swa.background_pixel = 0;
swa.border_pixmap = 0;
swa.border_pixel = 0;
swa.bit_gravity = 0;
swa.win_gravity = 0;
swa.override_redirect = True;
swa.colormap = XCreateColormap(dis, root, vi->visual, AllocNone);
swa.event_mask = StructureNotifyMask | ExposureMask;

unsigned long mask = CWOverrideRedirect | CWBackingStore | CWBackPixel | CWBorderPixel | CWColormap;

window = XCreateWindow(display, desktop, 0, 0,
                              display_width, display_height, 0, vi->depth,
                             InputOutput, vi->visual, mask, &swa); // vi -XVisualInfo

XLowerWindow(display, window);

long value = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DESKTOP", false);

XChangeProperty(display, window,
                    XInternAtom(display, "_NET_WM_WINDOW_TYPE", false),
                    XA_ATOM, 32, PropModeReplace, (unsigned char *) &value, 1);

Atom xa;

 xa = ATOM(_WIN_LAYER);

  if (xa != None) {
    long prop = 0;

    XChangeProperty(display, window, xa, XA_CARDINAL, 32,
                    PropModeAppend, (unsigned char *)&prop, 1);
  }

  xa = ATOM(_NET_WM_STATE);
  if (xa != None) {
    Atom xa_prop = ATOM(_NET_WM_STATE_BELOW);

    XChangeProperty(display, window, xa, XA_ATOM, 32, PropModeAppend,
                    (unsigned char *)&xa_prop, 1);
  }

  if (transparency < 1.0) {
    uint32_t cardinal_alpha = (uint32_t) (transparency * (uint32_t)-1) ;
    XChangeProperty(display, window,
                    XInternAtom(display, "_NET_WM_WINDOW_OPACITY", 0),
                    XA_CARDINAL, 32, PropModeReplace, (uint8_t*) &cardinal_alpha, 1);
}

XLowerWindow(display, window);
ctx = glXCreateContextAttribsARB(dis, fbc, NULL, True, gl3attr); //ctx =  GLXContext

next i create XMapWindow(dis, window), glXMakeCurrent(dis, window, ctx), glViewport and clearColor(red)\swapBuffers (in cycle)
note: ATOM = #define ATOM(a) XInternAtom(dis, #a, False)

A: Unfortunately there is no solution that works in 100% of all the cases. The most immediate solution would be to draw directly to the root window: open connection to X, get xid of root window, query what visual it's configured to, created compatible GLX context, draw to that. (this works somewhat reliably for X11; doing similar on Microsoft Windows or macOS is impossible though.)
However you can't change the visual/pixelformat, and just drawing to the root window won't necessarily make it an "underlay" for icons on the desktop. You see, most "desktops" are implemented by creating their very own full screen window, on top of the root window (but beneath everything else), and will even be used to draw the wallpaper then.
Drawing directly to the root window would give you the desired effect only, if the desktop environment of choice would cooperate and draw its desktop and the icons on it as a transparent, composited window; or if it'd mask out the icons using the X shape extension (I'm not aware of any DE that does either).


text:
Q: How to show loading indicator on top of the form? I am trying to display loading indicator on top of the form (to overlay it) but having a hard time to do so...

I want to show loading indicator when trash / minus or plus is clicked.
I am using React.js  + MobX. I do have a boolean flag, but what is difficult to achieve to actually place the loading indicator on top of the form (without corrupting the styling...)
Source code of cart:
import React, { useEffect, useContext } from "react";
import { Container, Row, Col } from "react-bootstrap";
import PromotionalCode from "./PromotionalCode";
import { observer } from "mobx-react-lite";
import { RootStoreContext } from "../../app/stores/rootStore";
import CartBody from "./CartBody";
import CartSummary from "./CartSummary";
import BasicSpinner from "../../app/common/spinners/BasicSpinner";
import Section from "../../app/common/Page/Section";
import TextContainer from "../../app/common/Page/TextContainer";

const Cart = () => {
  const rootStore = useContext(RootStoreContext);
  const {
    cart,
    total,
    discount,
    subtotal,
    loadingCart,
    loadCartOnSignIn,
    loadGuestCart,
    isChangingQuantity,
  } = rootStore.cartStore;
  const { isLoggedIn } = rootStore.userStore;

  useEffect(() => {
    if (isLoggedIn) {
      loadCartOnSignIn();
    } else {
      loadGuestCart();
    }
  }, [loadCartOnSignIn, loadGuestCart]);

  if (loadingCart)
    return (

        <BasicSpinner />

    );

  return (

      <TextContainer style={{ padding: "2rem 2rem 0 2rem" }}>

Cart

The competition tickets currently added in the cart.

      </TextContainer>
      <Container className="cart pt-0">
        {loadingCart ? (
          <BasicSpinner />
        ) : (

            {cart?.cartItems && cart.cartItems.length !== 0 ? (
              <>

Items in your bag

                          Description

                          Quantity
                          Price

                      <CartBody />

                <Container className="mt-5 ">
                  <Row className="justify-content-between cart__discount-and-total">
                    <Col md={5} className="cart__discount-and-total__discount">
                      {/* <PromotionalCode /> */}
                    </Col>
                    <Col className="cart__discount-and-total__total" md={6}>
                      <CartSummary
                        total={total}
                        subtotal={subtotal}
                        discount={discount.toString()}
                      />
                    </Col>
                  </Row>
                </Container>
              </>
            ) : (

There is no items in the cart yet.

            )}

        )}
      </Container>

  );
};

export default observer(Cart);

Desired result is something like this:

Is it even possible?

A: You can use absolute positioning for overlay and spinner.
Just render them inside your form, on the bottom.
.form {
  // use relative on your form

  position: relative;
}
.overlay {
  position: absolute;

  // this will stretch overlay to fill width and height of form
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  background-color: rgba(0, 0, 0, 0.1); // some transparent grey color
}

.spinner {
  position: absolute;

  // this will place spinner in center of form
  top: 50%;
  left: 50%;

  transform: translate(-50%, -50%);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does Noah Classifieds encrypt their passwords? Here are some examples:
db: 35273f5c7b3fb45a
actual: 5093625

db: 272beab9517a8835
actual: 7091343

According to http://hash-it.net/ it's not MD5 or SHA1.

A: I finally got a reply from the developers:
"The native 'password' function of MySql is used to encode the passwords. You can find it in the 'getPassword' function of 'gorum/dbproperty.php'"

A: I believe it is being salted, as none of the hashes on http://www.hashemall.com/ worked.
You can read more about salting here.


text:
Q: Within .NET Core DI, how do singleton lifetime services behave with concurrent requests? Within the context of .NET Core DI, if a service is registered as a Singleton (the lifetime, not to be confused with the pattern), will it be able to handle multiple concurrent requests?
Documentation says "every subsequent request uses the same instance." Let's say our data access implementation is registered as such. Does that imply it won't scale and handle concurrent requests, and each will essentially queue up to use the service?

A:
Does that imply it won't scale and handle concurrent requests, and each will essentially queue up to use the service?

Not at all. When you declare a service as Singleton (or other scopes) you JUST define its lifetime (create and dispose behavior) for DI. Not more, not less. It doesn't have any relation or impact on accessing manner of threads and requests to service. So you have to pay attention to concurrency issues of your service and define locks everywhere on code that isn't threadsafe.

Let's say our data access implementation is registered as such

Specifically if you're using ORMs like Entity Framework you should know that its DbContext is not threadsafe and declaring it as Singleton causes many concurrency issues and should be avoided.

A: According to Microsoft:
Singleton lifetime services (AddSingleton) are created the first time they're requested (or when Startup.ConfigureServices is run and an instance is specified with the service registration). Every subsequent request uses the same instance. If the app requires singleton behavior, allowing the service container to manage the service's lifetime is recommended. Don't implement the singleton design pattern and provide user code to manage the object's lifetime in the class.
According to the statement above, the requests as you mentioned in your question will be queued up.
But if you think from a performance point of view, your alternative would be to

*

*Instantiate the object

*Run your method

*Garbage collect the object

You do not only pay a performance toll in the beginning by instantiating the objects but you also require more effort from the GC when collecting them.
If you have some very heavy CPU operation in your singleton service that is used multiple times per request it might actually make some sense to reconsider your approach and go towards a scoped lifetime.
But overall creating a singleton service is still the best solution, when it is possible, from a performance point of view.


text:
Q: probabilities with copula i am trying to calculate the probability of tow random continuous variable being in an interval with the help of copula i am starting with

i want to calculate it with R but i dont know how to do this double integral

A: You can use the definition of copula:
$$P(U \le b, V \le d) = C(b,d)$$
to calculate this.
$$P(a \le U \le b, c \le V\le d) = P(a \le U \le b, V \le d) - P( a \le U \le b, V \le c).$$
The first term is
$$P(a \le U \le b, V \le d) = P(U \le b, V \le d) - P(U \le a, V \le d)$$ and the second term is
$$P( a \le U \le b, V \le c) = P(U \le b, V \le c) - P(U \le a, V \le c)$$
so overall you have
$$P(a \le U \le b, c \le V\le d) = (C(b,d) - C(a,d)) - (C(b,c) - C(a,c))$$
This probability is also called the $C$--volume of the rectangle $[a,b] \times [c,d]$, and of course it is what you get when you do the double integral in the usual way (using the Fundamental Theorem of Calculus twice). See Defintion 2.1 in Nelsen's Introduction to Copulas here.


text:
Q: Prism Mvvm Mef Interactivity Open window new instance I'm in process of learning different Prism features and now I'm stuck on opening new window.
My application Shell has Master region and Detail region.
Shell's master region has DataGrid with items which when clicked show it's properties in Detail region.
What I need is a way to create new instance of window with double click on item in Master region.
And every new window can stay active until I close it, so I can open and other windows by clicking on any other item in Master region.
In the pre-MVVM-Prism times, I would probably do something like:
    ICollection<Window> MyWindows = new List<Window>();
    var wnd = MyWindows.SingleOrDefault(x => x.Name == id.ToString());
    if (wnd == null)
    {
        wnd = new MyWindow(this, id);
        MyWindows.Add(wnd);
    }
    wnd.Show();

But this is a no-go from Shell's ViewModel and Prism...
Had used something like InteractionRequestTrigger from my Shell xaml:
 <prism:InteractionRequestTrigger SourceObject="{Binding CyberPopUpViewRequest, Mode=OneWay}">
    <prism:PopupWindowAction>
        <prism:PopupWindowAction.WindowContent>
            <views:CyberPopUpView />
        </prism:PopupWindowAction.WindowContent>
    </prism:PopupWindowAction>
</prism:InteractionRequestTrigger>

But this allows me to create only single window.

A:
But this is a no-go from Shell's ViewModel and Prism...

True, if you'd put the code directly in the view model. But it's completely fine if you put (read: hide) it in a service (that's injected as dependency and can be replaced with a mock when testing):
internal class WindowManager : IWindowManager
{
    public void CreateWindow( string id )
    {
        Window wnd;
        if (!_myWindows.TryGetValue( id, out wnd ))
        {
            wnd = new MyWindow( Application.Current.MainWindow, id );
            _myWindows[ id ] = wnd;
        }
        wnd.Show();
    }

    private Dictionary<string, Window> _myWindows = new Dictionary<string, Window>();
}


text:
Q: Remove lines from stderr There is custom message that comes each time I ssh or scp which I would like to hide. I still want the rest of the stderr to go to stderr output.
For example: a.sh contain one line: ssh example.com "touch /tmp/a.log ; echo ok"
myuser@host $ ./a.sh
No valid ciphers for protocol version 2 given, using defaults.
#######
# this is prod
#
#######
ok
myuser@host $

So I want to hide the first 5 lines, or if putting it into scripting grep -v -E "#|No valid ciphers for protocol". Any other error should still be output to screen/stderr.

A: ( exec 7>&1; your_command 2>&1 >&7 | grep -v msg_to_suppress >&2 )

See also https://stackoverflow.com/questions/3618078/pipe-only-stderr-through-a-filter.

A: The banner message looks like it's set on the remote server. You should be able to supress it with -q:
ssh -q example.com ...

The cipher message can be suppressed by using a cipher that matches one of the set offered by the server. Start with ssh -Q cipher and then experiment with settings such as ssh -o Cipher=aes256-gcm@openssh.com ...


text:
Q: Adaptec Raid Failed i have a Supermicro Server with this RAID Controller. The server works fine, but for cleaning purposes unplug the disks for some time.  After that, the controller shows an error and the server won't boot.
Error:

fatal error : controller monitor failed. controller not started

Any suggestions?

A: This is likely one of the following:

*

*The card is not seated correctly. Remove it from the PCIe slot and plug it back in.

*The SAS cables are not connected to the card properly. Try reseating them.

*The card is bad. Try swapping it with a spare.

As a side note, you should never remove disks or backplanes from a working server for cleaning. If you're accumulating that much dust in your systems, you should correct your environment so that it's less dusty. Put rules in place like "no cardboard in the server room" and have a proper HVAC system that has clean filters in place.


text:
Q: Python Chest Opening Odds I've been trying to figure out how to recreate odds in python for a chest opening game thingy, but the random.choice isn't really considering different odds. The goal I'm trying to achieve is set certain odds for different "rarities", like for example having 50% probability for getting an "Uncommon".
Code example:
import random

skins = {
    'Common':'Knife',
    'Uncommon':'Pistol',
    'Rare':'Submachine Gun',
    'Epic':'Automatic Rifle',
    'Legendary':'Semi-Automatic Sniper Rifle'
}

print("Welcome to N/A")
print("Input 'open' to open a chest.")
n = input("> ")
if n == "open":
    print(random.choice(skins))

A: A simple solution is to pick a random number between 0 and 100 and check which percentile it gets within.
import random

skins = {
    'Common':'Knife',
    'Uncommon':'Pistol',
    'Rare':'Submachine Gun',
    'Epic':'Automatic Rifle',
    'Legendary':'Semi-Automatic Sniper Rifle'
}

chance = random.randint(0, 100)
if chance < 50:
    print(skins["Common"])
elif chance < 80:
    print(skins["Uncommon"])
elif chance < 95:
    print(skins["Rare"])
elif chance < 99:
    print(skins["Epic"])
else:
    print(skins["Legendary"])

The first if has 50% chance of executing, the second 30%, the third 15%, the fourth 4% and the else has 1 % chance of executing (assuming linear perfect distribution of randint).

A: My advice is to use Random choice() method since it allows you to make a list where you can specify probability for each element.
https://www.w3schools.com/python/ref_random_choices.asp
from random import choices
skins = {
    'Common':'Knife',
    'Uncommon':'Pistol',
    'Rare':'Submachine Gun',
    'Epic':'Automatic Rifle',
    'Legendary':'Semi-Automatic Sniper Rifle'
}
weights = [0.4, 0.25, 0.2, 0.1, 0.05]
print("Welcome to N/A")
print("Input 'open' to open a chest.")
n = input("> ")
if n == "open":
    print(choices(list(skins.items()), weights))


text:
Q: Поиск в массиве с возможностью изменения результата (без ссылок) Требуется написать функцию, через которую можно будет в массиве найти элемент (если несколько таких элементов - то первый), и при необходимости изменить найденный элемент.
Массив такого вида:
$myArray = array(
    array(
        "name" => "Tra-ta-ta",
        "id" => 213
    ),
    array(
        "name" => "Test name",
        "id" => 25
    ),
    ...
);

Я сделал это через ссылки:
function &arraySearchByField(
        array &$array, string $fieldName, string $haystack): ?array
    {
        foreach($array as $key => &$arItem)
            if($arItem[$fieldName] == $haystack)
                return $arItem;
        return null;
    }

Подскажите пожалуйста, какие есть еще варианты решения этой задачи, без ссылок ?


text:
Q: Recommendations for beginner - intermediate quantum mechanics books I have an interest in quantum mechanics rather than classical mechanics , so should I read Feynman Lectures with those red cover and is it correct or would you suggest some other book for start . And I like to study by making my own notes and my own thoughts , so pls I know you're not a psychiatrist , but pls suggest.
PS : I am a beginner in quantum world


text:
Q: Device torch turns off when starting AVCaptureSession I'm using AVCaptureSession to capture video.
I want to light on the torch during the whole session, but once the session is started, the light turns automatically off.
There is a lot of posts here showing how to turn on the torch. It works, unless the capture session is started.
here's the way I start the session
guard let camera = AVCaptureDevice.default(for: .video) else { return }
self.captureSession.beginConfiguration()

let deviceInput = try AVCaptureDeviceInput(device: camera)
self.captureSession.addInput(deviceInput)

let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "com.axelife.axcapturer.samplebufferdelegate"))
self.captureSession.addOutput(videoOutput)

try camera.setLight(on: true)
self.captureSession.commitConfiguration()

DispatchQueue(label: "capturesession").async {
    self.captureSession.startRunning()
}

And my code to turn on the light
extension AVCaptureDevice {
    func setLight(on: Bool) throws {
        try self.lockForConfiguration()
        if on {
            try self.setTorchModeOn(level: 1)
        }
        else {
            self.torchMode = .off
        }
        self.unlockForConfiguration()
    }
}

With that code, the light turns on during < 0.5 seconds, and turn back off automatically.

A: Ok, I figured out.
The torch simply must be lighted on after the session start.
So instead of:
try camera.setLight(on: true)
self.captureSession.commitConfiguration()

DispatchQueue(label: "capturesession").async {
    self.captureSession.startRunning()
}

just do
self.captureSession.commitConfiguration()

DispatchQueue(label: "capturesession").async {
    self.captureSession.startRunning()
    try camera.setLight(on: true)
}

A: For me, the torch turns off when I change the videoOrientation of the capture preview layer. I turn it on again after that happens. (DispatchQueue.main.async is important, for some reason, it doesn't work if I leave it out)
previewConnection.videoOrientation = orientation

do {
    try captureDevice.lockForConfiguration()
} catch {
    print(error)
}

DispatchQueue.main.async { [weak self] in
    self?.captureDevice.torchMode = .on

    self?.captureDevice.unlockForConfiguration()
}


text:
Q: Why can a deterministic first-mover always be exploited in 2-player zero-sum games? I am reading a book about Bandit Algorithms in which the authors make the following observation. I am wondering if anyone could point me to an explanation of why the first-mover can always be exploited unless following a randomized strategy:

Readers familiar with game theory will not be surprised by the need for randomisation. The interaction between learner and adversarial bandit can be framed as a two-player zero-sum game between the learner and environment. The moves for the environment are the possible reward sequences, and for the player they are the policies. The pay-off for the environment/learner is the regret and its negation respectively. Since the player goes first, the only way to avoid being exploited is to choose a randomised policy.

A: Think about these two games.
\begin{align*}
\quad &A_1 & A_2\\
B_1 \;\;\;\;& (4,-4)&(5,-5)\\
B_2 \;\; \; \;& (c,-c)&(d,-d)\\
\end{align*}
\begin{align*}
\quad &A_1 & A_2\\
B_1 \;\;\;\;& (4,-4)&(-5,5)\\
B_2 \;\; \; \;& (c,-c)&(d,-d)\\
\end{align*}
If player $A$ knows that player $B$'s pure strategy, say $B_1$, player $B$ is exploited. The second mover will always choose the pure strategy beneficial to himself, which puts the first mover in a worse situation.

A: The problem is that the idea of a zero-sum game is being conflated with a dynamic or sequential move game.
In a zero-sum game with a finite number of strategies, the players move simultaneously. But if my payoff is the negative of your payoff and vice versa, you can think of me as moving to minimize your payoff given that you are maximizing. Conversely, since $-\max = \min-$, you can think of me as maximizing my payoff subject to you acting to minimize my payoff. Since the game is zero sum, we must be randomizing (or if there are many equilibria, like the game in which all our payoffs are zero, there is one that involves randomization). Think of it like rock-paper-scissors: if I strictly prefer some strategy, that means you must be losing out, and you can make me worse off and you better off by adjusting your strategy. That must mean we are all indifferent over our pure strategies, given our expectations of how our opponents will behave. That means I pick my mixed strategy to make you indifferent over your pure strategies, and vice versa. This is usually called the minimax theorem: https://mathworld.wolfram.com/MinimaxTheorem.html .
All of that has no "timing".  It is a simultaneous move game, and neither player moves first or second. It is only because the operators in the minimax theorem appear in "order" that you might get that impression. In games that genuinely have timing, the correct solution concept is Subgame Perfect Nash Equilibrium. In an SPNE, randomization only happens when players are indifferent over some of their payoffs at terminal histories in the game, and this is a fragile and somewhat rare situation (if you perturb the payoffs a very small amount, such indifferences are broken, and there will typically be a pure strategy SPNE). In your example, in the $\min \max$, the second mover does not get to observe the outcome of the first mover's randomization before picking their strategy, only the randomization itself (or else the second mover could always pick an optimal response to the first mover, which they typically do not; they simply know the distribution of states the first mover picked). To keep the first mover uncertain and maximize their payoff, the second-mover therefore plays randomly, just as in rock-paper-scissors.


text:
Q: Twig doesn't render dollar ($) sign Product title is "Navy Maverick Aviator Jacket $10"
But when I try to render it with twig {{ product.title }} I get "Navy Maverick Aviator Jacket"

A: I think that you should create a twig extension to show the dollar symbol as explained in this post Displaying currency symbol in twig

A: Try to use {{ product.title | raw }} It will render the raw value without escaping


text:
Q: $A$ is normal if and only if $trace(A^\ast A)=\sum_{i=1}^n|\lambda_i|^2.$ where the $\lambda_i$ are the eigenvalues of $A$. Let $A$ complex matrix of $n\times n$. Show that $A$ is normal if and only if $$trace(A^\ast A)=\sum_{i=1}^n|\lambda_i|^2.$$ where the $\lambda_i$ are the eigenvalues of $A$.
I try using the trace properties and the definition of normal matrix...I use that $A$ is similar to unitary matrix...but i not can prove the exercise.
I wait that can you help me. Thanks!


text:
Q: "Exclude text from blending" CSS-blending I am making a website for one of our clients. Our designers used blending: multiply because it can be done in CSS these days. I have implemented it in the site but I can't get the requested result and just wanted to ask you people if it even possible.
Here's the case: I have a big header with images in the background. On top of that header floats a round div which has mix-blend-mode: multiply. This works as desired, but in this div there is text which is also blended. Can I keep this text "unblended"?
desired effect:

What it is now:

Thanks in advance!

A: Use a pseduo-element and apply the blend-mode to that instead of the parent div.

div.header {
  width: 100%;
  height: 300px;
  background-image: url(http://www.eikongraphia.com/wordpress/wp-content/BIG_Zira_Island_Copyright_BIG_1_Small.jpg);
}
div.info-bol {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  text-align: center;
  position: relative;
}
div.info-bol::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 50%;
  background-color: red;
  mix-blend-mode: multiply;
}
div.info-bol span {
  position: relative;
  top: 22%;
  font-size: 30px;
  font-weight: bold;
  color: white;
}

    samenwerken
is meer dan
samen
werken

A: You must take the span out, because mix-blend-mode affects all children.
You can try something like creating a clone, without background, and pushing it into position.

div.header{
  width: 100%;
  height: 300px;
  background-image: url(http://www.eikongraphia.com/wordpress/wp-content/BIG_Zira_Island_Copyright_BIG_1_Small.jpg);
}

div.info-bol{
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: red;
  mix-blend-mode: multiply;
  text-align: center;
  color: #fff;
}

div.info-bol-clone{
  position: relative;
  width: 200px;
  height: 200px;
  text-align: center;
  color: #fff;
  bottom: 200px;
}

div.info-bol-clone span{
  position: relative;
  top: 22%;
  font-size: 30px;
  font-weight: bold
}

    samenwerken
is meer dan
samen
werken


text:
Q: Migrating from abstract model to proxy models Right now, I have an abstract model with several models that inherits its fields. But I have discovered the power of Proxy models, and I want to implement them to my app. This is a picture from now:
class BaseModel(models.Model):
    field_1 = models.CharField(max_length=10)
    field_2 = models.CharField(max_length=10)
    field_3 = models.CharField(max_length=10)

    class Meta:
        abstract = True

class Model1(BaseModel):
    pass

    def __unicode__(self):
        return self.field_1

class Model2(BaseModel):
    pass

    def __unicode__(self):
        return self.field_1

And this is what I want:
class BaseModel(models.Model):
    field_1 = models.CharField(max_length=10)
    field_2 = models.CharField(max_length=10)
    field_3 = models.CharField(max_length=10)

class Model1(BaseModel):
    pass

    class Meta:
        proxy = True

    def __unicode__(self):
        return self.field_1

class Model2(BaseModel):
    pass

    class Meta:
        proxy = True

    def __unicode__(self):
        return self.field_1

The problem is when I remove the "abstract = True" sentence. When I try to migrate, this is the warning:

You are trying to add a non-nullable field 'basemodel_ptr' to Model1 without a default; we can't do that (the database needs something to populate existing rows).

Ok, got it. I read "ptr" is a pointer to the parent model, which is BaseModel, but I don't have any BaseModel, and I cannot get it until I migrate. How can I fix this??

A: The migrations for this are not trivial.
Currently, your database has two tables:

*

*yourapp_model1

*yourapp_model2
Both have the same columns but they use different sequences meaning that their primary keys clash: Both of the tables will start counting their IDs (aka PKs) from 1 onwards. There is a very good chance that there is an instance of Model1 with pk=1 as well as an instance of Model2 with pk=1 and they are not the same.
This is the point of having an abstract model and concrete implementations: share Django code (business logic) while separating the data in the DB. For example, because it is semantically different (different types).
The point of proxy models is the exact opposite: while the data is located in one table in the DB, the proxy models allow you to implement different behaviour but based on the same DB data.
If you are now migrating from abstract models to proxy models it means that what you once considered different types will now become the same types (from a database point of view). As mentioned at the beginning, you will have to move the data from several tables into one and regenerate the IDs for at least part of it. Meaning also, that part of the resources that are currently using these URLs will change/cease to exist/point to a different resource.
Unless you can start from scratch (no live data that you have to support) you should really appreciate the magnitude of this change.
Should you not have the need to support live data:

*

*drop the database

*recreate the database

*remove all migration files

*recreate all migration files from scratch

*call migrate

Data migration of live data:
Note that there are other ways to do this. Search for "Django data migration".

*

*create the new Model structure with new names (no collisions)

*makemigrations which will now pick up the new model structure and create new and empty tables in database leaving the old tables and their data untouched

*create a management command that reads in the old model instances and copies them into the new tables

*once this command has been run on production you can deprecate the old models and remove them while making sure that everything that was depending on them is now using the new tables


text:
Q: list of any collection type, also with a generic data type I'm trying to modify the class below so its functions accept any from of collection the data type of those collection is also generic, allowing for maximally flexible:
public class Container<E> {
   List<E> cont;
   public Container() {
        cont = new java.util.LinkedList<T>();
   }
   void add(E item) {
        cont.add(item);
   }
   public E remove() {
        return cont.remove(0);
   }
   void addMulti(List<E> items) {
        for (E elem : items) {
              cont.add(elem);
        }
   }
   void removeMulti(int x, List<E> items) {
        for (E elem : cont.subList(0, n)) {
              items.add(elem);
        }
        for (int i=0; i<x; ++i) cont.remove(0);
   }
}

I'm trying to make List accept multiple types using wildcard, like:
 List<?> //Right??

In addition, the addAll, and removeAll function should accept any kind of lists as an argument, instead of List only, could t be like:
Collection<?> //Correct???

Thank you!

A: For addMulti, you do not want to accept a Collection<?>, because you cannot rightly say it contains elements compatible with E. For maximum generality, you might accept a Collection<? extends E>, which says that the collection contains E or some subclass of E.
void addMulti(Collection<? extends E> items) {...}

For removeMulti, yes, you could accept a Collection<?>, because if the type of some element in the collection is not compatible with E, it will simply not be removed.
void removeMulti(int x, Collection<?> items) {...}

Though, if you take a wildcard collection in removeMulti, you will not be able to add to items. (I don't really understand what your code is supposed to do there.)
This is the way Collection#addAll and Collection#removeAll are defined.


text:
Q: Remove property by value from object I have a simple object like this:
var obj = {
    "option1": "item1",
    "option2": "item2",
    "option3": "item3"
};

For adding a new property to the object I'm using the following code:
obj[this.value] = this.innerHTML;

// this.innerHTML is used just because I'm adding the value I get from a DOM element

Is there a function that can help me remove a property from the object, that receives as a parameter the value of the key-value pair?
For example removeItem('item3');.

A: That would probably be delete :
delete obj['option1'];

FIDDLE
To do it by value, you'd do something like :
function deleteByVal(val) {
    for (var key in obj) {
        if (obj[key] == val) delete obj[key];
    }
}

deleteByVal('item1');

FIDDLE

A: This question has been answered correctly but there is just one thing I want to add:
You should write a pure function for this solution. That is a function that does not require your object to be defined in the global scope.
so:
const deleteObjectItemByValue = (Obj, val) => {
    for (var key in Obj) {
        if (Obj[key] == val) {
            delete Obj[key];
            return Obj;
        }
    }
};

usage: deleteObjectItemByValue(yourObj, val);
This is a pure function that does not have side effects i.e mutate anything in its outer environment and does not depend on any global variable for its operation.

A: Like this-
delete obj["option1"]; Or delete obj.option1;


text:
Q: How to scan an image folder and add them to an image array I am working on a project and one of the requirements is to scan a folder containing different Images. I need to find a way to scan the folder and add each image to an array of Images. Here is what I want to do
public class ImageScan {
   private ArrayList<Image> images = new ArrayList<>();

   public void loadImages() {

   ArrayList<Image> image_Array = new ArrayList<>();

   File file = new File("data/images");
   BufferedImage image = ImageIO.read(file);

      while(image.hasNextImage()) {//hasnextImage() is  not a valid method,
      //just to express my idea.

         Image image = //save read Image to an image instance
         //here all I want to do is add each image I obtain into an
         //arrayList of images

         image_Array.add(image);
      }//end of while

   this.setImages(image_Array);// i set image_Array using getter method
   }//end of loadData method

}//end of class

A: Okay here is what I created:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

public class ImageScan {

    private List<Image> images = new ArrayList<Image>();

    public void loadImages() {

        List<Image> imageArray = new ArrayList<Image>();

        File file = new File("data/images");

        File[] imageFiles = file.listFiles(); // This gets all of the files inside
'file', if 'file' is a folder
        for (File f : imageFiles) {
            try {
                BufferedImage image = ImageIO.read(f);
                imageArray.add(image);
            } catch (Exception e) {
                // This makes sure only the images in the folder are used, not any
file.
            }
        }

        this.setImages(imageArray);
    }

    public void setImages(List<Image> imageArray) {
        images = imageArray;
    }

    public List<Image> getImages() {
        return images;
    }

}


text:
Q: Cannot access collection by properties Laravel 5.8 So I have three different arrays with the same length in the request and below is how I combine them into one collection:
$inputs = collect();
$keys = collect(['id', 'username', 'email']);
foreach ($request['ids'] as $index => $id) {
   $username = $request['usernames'][$index];
   $email = $request['emails'][$index];
   $inputs->push($keys->combine([$id, $username, $email]));
}

The result looks correct to me:

However, I cannot access the collection when I iterate over it:
foreach ($inputs as $input) {
    dd($input->id); // Property [id] does not exist on this collection instance.
}

This is the result of dd($input):

Any pointers on this problem? (Another short way to combine the arrays into one collection will also be appreciated!)
Thank you.

A: It is a collection and you should get it like this: dd($input['id']).

A: You can combine arrays bt array_merge
array_merge($a1,$a2)

or collect
$c=collect([$arr1,$arr2])

then pluck if you want
$c->pluck('username')


text:
Q: Learning C++, What's next? Also what's a recommended compiler? I've been spending my "inbetween" time at the office looking into C++. I'm primarily a flash & web developer, also working on a bunch of flash games, but I thought it was time to have a look at some non-web-based languages and see if I could get some real games going.
I've got the hang of how typing works, arrays, outputting using cout, structs, classes and so on and so on.
I seem to have found myself stuck in terms of what I can do next. Outputting to a DOS window obviously isn't that exciting - how do I get started on doing something graphical? A square moving around on the screen, even. Simple is better in this case.
As for the compiler - I've been using devcpp by Bloodshed; is this adequate or am I missing a more common compiler somehow?

A: Graphics can be done using DirectX in Windows, or OpenGL on every platform. It's a whole different discussion upon which to choose.
In addition to trying to work with graphics, you could try your hand at developing GUIs. I'd give Qt a shot. Be warned though, Qt is being sold by Nokia, but it's overall a very well known and heavily used framework. Or try direct Win32 (not necessarily something I'd suggest unless you're interested). Or try WinForms (requires .NET experience, and steals from the true C++; C++/CLR is NOT the same C++ you are learning--it adds to it). If you do go the .NET route, avoid "Managed C++" examples, as they that was the first iteration of C++/CLR, and they simply redid it and vastly improved it.
Two most common compilers: gcc (Linux, Mac and Windows) and Visual Studio's for development on Windows', I always use Visual Studio (there is a free version called Visual Studio Express that is a solid product) for Windows development simply because I love the IDE.

A: For a compiler, my school uses g++, an excellent, free C++ compiler that is compatible with many IDEs for unix-based C++ development. If you're running a windows machine, you'll have to download cygwin (which emulates a linux shell) - you'll have to select which executables you want to download with the cygwin shell, figuring out what items you need may take a little time (basically, download useful looking things for the type of development that you want to do; g++/gcc are very important).
http://cygwin.com/install.html
When you have this, you can easily configure netbeans or eclipse (I've had better experience with netbeans) to compile and run your C++ code through cygwin.
Also, my favorite resource for learning C++ has been cplusplus.com - it has detailed tutorials of all of C/C++'s standard functions.
Hope this helps a little!

A: Have a look at graphics and windowing libraries. For windowing, as you seem to be on Windows, there's builtin stuff. For more general applicability I suggest having a look at Qt or Gtk.
For graphics, the fancy stuff is usually done in either DirectX (basically Windows only) or OpenGL (more portable).
Compilers: GCC is commonly used in the Unix/Linux world and also available on Windows through Cygwin. In the Windows world you'll also find Microsoft's MSVCC as it comes with their development tools. Btw., there are free dev tools from Microsoft as well, see their Visual Studio Express Editions.

A: Some tips:

*

*Work through one or more good books. I recommend "Accelerated C++" and "Effective C++". These books will teach you real C++ programming.

*If you're on Windows then I think you're better off using Visual Studio. The learning curve for C++ is steep enough already. If you simultaneously need to learn how to work with gcc and makefiles then you are likely to become overwhelmed.

*Windows specific: for simple graphics I find WinAPI and GDI+ useful. They are relatively easy to learn and they are immediately available.


text:
Q: Why does Google Maps kills my flutter app in the background? We develop a tourism app using flutter, we use Google Maps (map_launcher plugin) to guide the user all over the city. When we Go to Maps, (our app is in background), as soon as we start navigation, our app is killed. No erros, No logs.
I tried to use BackgroundLocation service to keep the app Alive, it works on debug mode ! but not on release.
PS: It's not a memory problem, this does not happen with other memory consuming apps.
Thank you for your Help.


text:
Q: Indoor location using WiFi Signals and Machine Learning I am trying to determine in which zone of a building a person is located based solely on the strength of the WiFi signals her cellphone gets. Currently, we are making measures with an Android App, for each measure we are assigning a "zone" such as "corridor", "room1" or "room2".
I intend to build a matrix in which each row represents a measure of various signals and the zone they were measured. There will be a column for each hotspot present in the building (With 0's for all the hotspots which haven't appeared in a measure).
The idea is to have the algorithm classify in which zone you probably are based on the power of the signals you get. Any ideas about what machine learning algorithm can achieve a good classification accuracy with that data? I'm currently thinking about Logistic Regression and Neural Networks.

A: (Pieter already mentioned my thesis on "Human SLAM", a more terse version is available as a paper here: http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=7471364)
To give a direct answer to your question: there are multiple approaches. One of the most simple ones is "fingerprinting". You start by collecting signal strength data in each room and store these in a database (this makes the fingerprint). After this initialisation phase, each time a user wants to know it's location you make a new signal strength fingerprint and compare this with your fingerprint database. Such an algorithm should be easy to implement, but I can't really say anything about the performance.
Personally, I focussed more on SLAM which is a localisation algorithm from the robotics field. Using this technique you can make more precise maps and skip the initialisation phase. This is, however, more difficult to implement and, because it is fully autonomous and starts from zero knowledge, is not yet the most accurate approach.


text:
Q: How to create photo grid using flexbox with same order I have an image grid with 2 rows(Horizontally).at initial state, the first row has 4 images and the second row has 2 images user will be able to add extra images to the second raw. in first-row images are displaying correctly but when it comes to 2nd row those two images are displaying in the beginning and the end of the row .middle space get empty.i have attached images with this.
This is what I have now

This is My SCSS
  .container-gallery{
        width: percentageCalculator(870);
        .image-grid{
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;

        }
        .gallary-images{
            height: percentageCalculator(130);
            width: percentageCalculator(165);
            border-radius: percentageCalculator(6);
            margin-bottom: percentageCalculator(10);
            opacity: 0.7;
        }

    }

This is what I  expected

A:
space-between: items are evenly distributed in the line; first item is
  on the start line, last item on the end line

Change justify-content: space-between; to  justify-content: flex-start;


text:
Q: Git Ignore not working Here is my scenario. I was on branch A, where I made some changes to certain file on my local working copy.
/launcher/file.esb
I basically want the following:

*

*Ignore the changes made to this file completely. I accomplished this using
assume-unchanged

*Untrack this file from version control, which I tried to accomplish using .gitignore.

*Preserve the changes to this file on my local working folder as I checkout different branches.
A->Develop->B->C etc...
It is #3 that I am not able to accomplish. As soon as I checkout a new branch and do a pull, the old changes are overwritten on the file.
Why is this happening? Shouldnt inclusion of this file path into .gitignore effectively take out this file completely out of reach of the version control tentacles?
How can I achieve #3?
This question is unlike the one mentioned in the "possible duplicate" link.
Heres why:
Here's basically what I want in lay words. "Put this one particular file of mine in essentially a 'shell', that neither gets overwritten during ANY git operations nor gets taken into account if changed". Its basically excluding any form of version control synchronization between that file and staging/remote. This local file and the version on staging/remote must exist with mutual and total disconnection.

A: This is happening because the file is already part of the repository. So when you switch branches you get the version of this file from the branch you are checking out. The gitignore file only prevents git from seeing files that are not a part of the repository. This is done, so git doesn't include certain files in commands like git add . or git commit -a. And assume-unchanged option tricks git into not seeing the changes, but that means that Git feels free to overwrite the file on checkouts, since it knows the file to be no different from the committed version.
If what you want is to remove this file from git control and manage the changes to it yourself, you can use git rm --cached /launcher/file.esb and commit the change. This will remove this file from the index and the file will no longer be tracked by git. The --cached option prevents git from actually removing the file from your working directory. You might have to do this separately for each branch though, since removing file from one branch doesn't remove it from other branches. To do this you might want to undo assume-unchanged and then use git stash command to temporarily stash your local changes.

A:
Untrack this file from version control, which I tried to accomplish using .gitignore.

You tried and you failed. .gitignore is read only when you update the index, i.e. you prepare the next commit. If a file was already committed, adding it to .gitignore doesn't help telling Git to stop tracking the file.
You have to also remove the from the index (using git rm --cached) and commit the change. Only then Git stops tracking the file. Adding its name to .gitignore only tells it to stop listing it in the Untracked files section on the output of git status.
However, if you checkout a commit that was created before you removed the file from the repo, the commit contains the file and Git will try to check it out too.


text:
Q: nodejs keycloak-connect-graphql not working while in docker I have hit an issue that I have struggled to figure out for the last little while regarding docker. Here is a shortened version of the story
In my development environment (everything is running on localhost), code works great, whenever I add my authorization token in my headers keycloak-connect detects it and works as usual. The problem occurs when I use it in docker and add custom network interfaces.
When the docker container boots up, I have it connect to keycloak via http://keycloak:8080/auth and generate the realm. That works fine, not an issue, thus I know that the keycloak network is up and running as expected. I am able to remote into the container, communicate with keycloak, get a token and etc...
In my graphql application, I use keycloak-connect-graphql to set the context of the graphql application which in turn uses keycloak-connect to set up all the headers. The problem is, that keycloak-connect-graphql tells me that there is no header.If I simply print out the request, I can clearly tell that there is a token being passed in, it's just that for some reason, keycloak-connect-graphql/keycloak-connect does not want to set it because I am using a different network besides localhost.
I was actually able to side-step this problem in production by setting the keycloak url to be a the public url (https://keycloak.DOMAINNAME.com) which makes absolutely no sense to me because http://keycloak:8080/auth does not work. I have digged through keycloak-connect and the keycloak-connect-graphql code and I could not find anything relating to a CORS issue or something else suspicious. If anyone has any ideas please let me know. This bug has been driving me crazy.
Code snippet:
keycloak configuration (app.config)
  keycloak: {
    realm: process.env.KEYCLOAK_REALM,
    'auth-server-url': 'http://keycloak:8080/auth',
    'ssl-required': 'none',
    resource: process.env.KEYCLOAK_RESOURCE,
    'public-client': true,
    'use-resource-role-mappings': true,
    'confidential-port': 0,
  },

configurekeycloak.js
function configureKeycloak(app, graphqlPath) {
  const keycloakConfig = require('../config/app.config').keycloak;

  const memoryStore = new session.MemoryStore();

  app.use(
    session({
      secret:
        process.env.SESSION_SECRET_STRING || 'this should be a long secret',
      resave: false,
      saveUninitialized: true,
      store: memoryStore,
    }),
  );

  const keycloak = new Keycloak(
    {
      store: memoryStore,
    },
    keycloakConfig,
  );

  // Install general keycloak middleware
  app.use(
    keycloak.middleware({
      admin: graphqlPath,
    }),
  );

  // Protect the main route for all graphql services
  // Disable unauthenticated access
  app.use(graphqlPath, keycloak.middleware());

  return { keycloak };
}

index.js
// perform the standard keycloak-connect middleware setup on our app
const { keycloak } = configureKeycloak(app, graphqlPath);

// Ensure entire GraphQL Api can only be accessed by authenticated users
app.use(playgroundPath, keycloak.protect());

const server = new ApolloServer({
  gateway,
  // uploads: false,

  // Apollo Graph Manager (previously known as Apollo Engine)
  // When enabled and an `ENGINE_API_KEY` is set in the environment,
  // provides metrics, schema management and trace reporting.
  engine: false,

  // Subscriptions are unsupported but planned for a future Gateway version.
  subscriptions: false,

  // Disable default playground
  playground: true,

  context: ({ req }) => {
    return {
      kauth: new KeycloakContext({ req }),
    };
  },

  // Tracing must be enabled for this plugin to add the headers
  tracing: true,
  // Register the plugin
  plugins: [ServerTimingPlugin],
});

Edit:
setting network_mode to host fixes the issue, but I much prefer using dockers integrated networks rather than using network_mode host, especially for production
Edit 2:
I was able to reproduce the error in my local development environment (without shelling into docker and then debugging from there). I was able to do this buy using the IP address provided by docker. This yields the same results. I have narrowed the issue down to keycloak-connect, which for some reason, does no want to connect to keycloak or something. Still not sure


text:
Q: Creating a Asteroid type game, problem is when player waits to press play button many asteroids spawn instead of controlled amount About 500 lines of code, so to make it easier to read I believe the bug comes from _update_asteroids(self) function. Simply put, when the user is in the paused game state and must press play, if the player decides to wait lets say a minute. A minutes worth of asteroids will spawn at the exact same time. I believe this is because the pygame.time.get_ticks() function continues to gain ticks while game is paused. Is there any way to reset the ticks or make it so that 100s of asteroids do not spawn when the user decides to wait before pressing play button?
import pygame
import sys
from pygame.sprite import Sprite
import random
from time import sleep
import pygame.font

class Game(Sprite):
    """ a class the creates a window with a blue screen """
    def __init__(self):
        pygame.init()
        super().__init__()

        #--------------------------------------------------------------------------------------------
        #screen size, color, caption
        self.screen = pygame.display.set_mode((1200,800))   #create attribute to hold display settings
        self.bg_color = (0,0,255)                           #create attribute to hold RGB color (blue)
        pygame.display.set_caption("Blue Screen")
        #--------------------------------------------------------------------------------------------

        #--------------------------------------------------------------------------------------------
        #tank drawing
        self.screen_rect = self.screen.get_rect()               #get the screen rect dim
        self.image = pygame.image.load('images/tank.gif')       #load the image from directory
        self.rect = self.image.get_rect()                       #get the image rect dim
        self.rect.center = self.screen_rect.center              #store the screens center x/y coord

        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

        #tank movement
        self.tank_moving_left = False
        self.tank_moving_right = False
        self.tank_moving_up = False
        self.tank_moving_down = False
        self.tank_speed = 0.5                                                       #tank pixels
        self.direction_right = self.image                                       #holds right image
        self.direction_left = pygame.transform.flip(self.image, True, False)    #holds left image
        #--------------------------------------------------------------------------------------------

        #--------------------------------------------------------------------------------------------
        #UI
        self.health = 100
        self.visable = True
        self.sb = Scoreboard(self)
        #--------------------------------------------------------------------------------------------

        #--------------------------------------------------------------------------------------------
        #bullet
        self.bullets = pygame.sprite.Group()
        self.current_direction = self.direction_right
        #--------------------------------------------------------------------------------------------

        #--------------------------------------------------------------------------------------------
        #asteroids
        self.asteroids = pygame.sprite.Group()
        self.next_object_time = 0
        self.time_interval = 250
        #self._create_asteroids()
        #--------------------------------------------------------------------------------------------

        #--------------------------------------------------------------------------------------------
        #button
        self.game_active = False
        self.play_button = Button(self, "Play")
        #--------------------------------------------------------------------------------------------

    def _create_asteroids(self):
        """ create the asteroid shower """
        #create a asteroid
        number_of_aliens = 1
        for asteroid_num in range(number_of_aliens):
            self._create_asteroid()

    def _create_asteroid(self):
        asteroid = Asteroid(self)
        if asteroid.x <= 0:
            asteroid.direction = 1
        elif asteroid.x >= 1160:
            asteroid.direction = -1
        self.asteroids.add(asteroid)

    def move(self):
        """ move tnak tank_speed based on direction of movement (key pressed)
            also detect collision """
        if self.tank_moving_right and self.rect.right < self.screen_rect.right:
            self.x += self.tank_speed
            self.rect.x = self.x
        if self.tank_moving_left and self.rect.left > self.screen_rect.left:
            self.x -= self.tank_speed
            self.rect.x = self.x
        if self.tank_moving_down and self.rect.bottom < self.screen_rect.bottom:
            self.y += self.tank_speed
            self.rect.y = self.y
        if self.tank_moving_up and self.rect.top > self.screen_rect.top:
            self.y -= self.tank_speed
            self.rect.y = self.y

    def draw_healthbar(self):
        pygame.draw.rect(self.screen, (255,0,0), (self.rect.x, self.rect.y - 20, 100, 10))
        pygame.draw.rect(self.screen, (0,255,0), (self.rect.x, self.rect.y - 20, 100 - (100 - self.health), 10))

    def blitme(self):
        """ draw the image of the tank """
        self.screen.blit(self.image, self.rect)

    def tank_asteroid_collision(self):
        #get rid of asteroids that collide with tank
        for asteroid in self.asteroids.copy():
            if pygame.Rect.colliderect(self.rect, asteroid.rect):
                if self.health > 25:
                    self.health -= 25
                    self.asteroids.remove(asteroid)
                    print(self.health)
                else:
                    self._tank_death()
                    self.sb.reset_score()
                    self.game_active = False
                    pygame.mouse.set_visible(True)

    def _update_screen(self):
        """ update screen """
        self.screen.fill(self.bg_color)
        self.blitme()
        for bullet in self.bullets.sprites():
            self.bullets.draw(self.screen)

        collisions = pygame.sprite.groupcollide(self.bullets, self.asteroids, True, True)
        if collisions:
            for asteroids in collisions.values():
                self.sb.score += 100 * len(asteroids)
            self.sb.prep_score()
            self.sb.check_high_score()
        #draw healthbar if game active
        if self.game_active:
            self.draw_healthbar()
            self.asteroids.draw(self.screen)

        #draw the play button and other buttons if game is paused
        if not self.game_active:
            self.play_button.draw_button()

        self.sb.show_score()

        pygame.display.flip()

    def _tank_death(self):
        sleep(0.5)
        self.bullets.empty()
        self.asteroids.empty()
        self.center_ship()
        self.health = 100

    def _check_KEYDOWN(self, event):
        """ when key is press either quit, or move direction of arrow pressed and flip image """
        if event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_RIGHT:
            self.tank_moving_right = True
            self.image = self.direction_right
            self.current_direction = self.direction_right
        elif event.key == pygame.K_LEFT:
            self.tank_moving_left = True
            self.image = self.direction_left
            self.current_direction = self.direction_left
        elif event.key == pygame.K_UP:
            self.tank_moving_up = True
        elif event.key == pygame.K_DOWN:
            self.tank_moving_down = True
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_KEYUP(self, event):
        """ when key is let go stop moving """
        if event.key == pygame.K_RIGHT:
            self.tank_moving_right = False
        elif event.key == pygame.K_LEFT:
            self.tank_moving_left = False
        elif event.key == pygame.K_UP:
            self.tank_moving_up = False
        elif event.key == pygame.K_DOWN:
            self.tank_moving_down = False

    def _fire_bullet(self):
        """ create a bullet and add it to the bullets group """
        if self.current_direction == self.direction_left:
            #create new bullet and set bullet path
            new_bullet = Bullet(self)
            new_bullet.bullet_shootRight = False
            new_bullet.bullet_shootLeft = True

            #change direction of bullet starting point
            new_bullet.x -= 100

            #add bullet to sprite list
            self.bullets.add(new_bullet)

        elif self.current_direction == self.direction_right:
            #create new bullet and set bullet path
            new_bullet = Bullet(self)
            new_bullet.bullet_shootRight = True
            new_bullet.bullet_shootLeft = False

            #add bullet to sprite list
            self.bullets.add(new_bullet)

    def center_ship(self):
        """ centers the ship in middle of screen """
        self.rect.center = self.screen_rect.center
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

    def _update_tank(self):
        """ move tank or quit game based on keypress """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_KEYDOWN(event)
            elif event.type == pygame.KEYUP:
                self._check_KEYUP(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and self.play_button.rect.collidepoint(mouse_pos):
            self.game_active = True
            pygame.mouse.set_visible(False)

    def _update_asteroids(self):
        """ afer 'x' milliseconds create a new asteroid """
        current_time = pygame.time.get_ticks()
        if current_time > self.next_object_time:
            self.next_object_time += self.time_interval
            self._create_asteroids()

    def run_game(self):
        """ loops the game/ updates screen/ checks for key clicks"""
        while True:
            self._update_tank()
            if self.game_active:
                self.move()
                self.bullets.update()
                self.tank_asteroid_collision()
                #after certain number of time create a asteroid
                self._update_asteroids()
                self.asteroids.update()

                #get rid of asteroids that have disapeared
                for asteroid in self.asteroids.copy():
                    if asteroid.x >= 1200 or asteroid.x <= 0:
                        self.asteroids.remove(asteroid)

                #get rid of bullets that have disapeared
                for bullet in self.bullets.copy():
                    if bullet.rect.left >= 1200 or bullet.rect.right <= 0:
                        self.bullets.remove(bullet)
            self._update_screen()

class Bullet(Sprite):
    """ A class to manage bullets fired from the ship """
    def __init__(self, game):
        """ create a bullet object at the ships current position """
        super().__init__()
        self.screen = game.screen
        self.bullet_speed = 2.0
        self.bullet_width = 20
        self.bullet_height = 5
        self.bullet_color = (0, 200, 200)
        self.bullet_shootRight = False
        self.bullet_shootLeft = False

        self.image = pygame.Surface((self.bullet_width, self.bullet_height))
        self.image.fill(self.bullet_color)
        self.rect = self.image.get_rect()
        self.rect.midright = game.rect.midright
        self.rect.y -= 5 #the tanks barrel is 5 pixels above center
        self.rect.x += 15

        #store the bullets position as a decimal value
        self.y = float(self.rect.y)
        self.x = float(self.rect.x)

    def update(self):
        """ move the bullet up the screen """
        #update the decimal position of the bullet.
        if self.bullet_shootRight:
            self.x += self.bullet_speed
            self.rect.x = self.x
        elif self.bullet_shootLeft:
            self.x -= self.bullet_speed
            self.rect.x = self.x

class Asteroid(Sprite):
    """ a class that represents a single asteroid """
    def __init__(self, game):
        """ initialize the asteroid and set its starting position """
        super().__init__()
        self.screen = game.screen
        self.speed = 0.1
        self.direction = 1

        #load the asteroid image onto the screen
        self.image = pygame.image.load('images/asteroid.gif')
        self.rect = self.image.get_rect()

        #start each new asteroid in a random part just outside the map on either the left or right
        self.rect.x = random.randint(*random.choice([(0, 0), (1160, 1160)]))
        self.rect.y = random.randint(0, 760)

        #store the asteroid's exact horizontal positon
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

    def update(self):
        """ move the asteroid to the right or left """
        self.x += self.speed * self.direction
        self.rect.x = self.x

        self.y += (self.speed / 3) * self.direction
        self.rect.y = self.y

class Button:

    def __init__(self, game, msg):
        """ Initialize button """
        self.screen = game.screen
        self.screen_rect = self.screen.get_rect()

        #set the dimensions and properties of the button
        self.width, self.height = 200, 50
        self.button_color = (0, 255, 0)
        self.text_color = (255, 255, 255)
        self.font = pygame.font.SysFont(None, 48)

        #Build the button's rect object and center it.
        self.rect = pygame.Rect(0, 0, self.width, self.height)
        self.rect.center = self.screen_rect.center

        self._prep_msg(msg)

    def _prep_msg(self, msg):
        """ Turn msg into a rendered image and center text on the button """
        self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)
        self.msg_image_rect = self.msg_image.get_rect()
        self.msg_image_rect.center = self.rect.center

    def draw_button(self):
        """ draw blank button then draw message """
        self.screen.fill(self.button_color, self.rect)
        self.screen.blit(self.msg_image, self.msg_image_rect)

class Scoreboard:
    """ A class to report scoring information """

    def __init__(self, game):
        """ initialize scorekeeping attributes """
        self.screen = game.screen
        self.screen_rect = self.screen.get_rect()
        self.score = 0
        self.highscore = 0

        # Font settings for scoring information
        self.text_color = (30, 30, 30)
        self.font = pygame.font.SysFont(None, 48)

        self.prep_score()
        self.prep_highscore()

    def reset_score(self):
        self.score = 0
        self.prep_score()

    def prep_highscore(self):
        """ Turn the high score into a rendered image. """
        high_score = round(self.highscore, -1)
        high_score_str = "{:,}".format(high_score)
        self.high_score_image = self.font.render(high_score_str, True, self.text_color, (255, 255, 255))

        #center the high score at the top of the screen
        self.high_score_rect = self.high_score_image.get_rect()
        self.high_score_rect.centerx = self.screen_rect.centerx
        self.high_score_rect.top = self.score_rect.top

    def check_high_score(self):
        """ check to see if there's a new high score """
        if self.score > self.highscore:
            self.highscore = self.score
            self.prep_highscore()

    def prep_score(self):
        """ Turn the score into a renered image """
        rounded_score = round(self.score, -1)

        score_str = "{:,}".format(rounded_score)
        self.score_image = self.font.render(score_str, True, self.text_color, (255, 255, 255))

        #Display the score at the top of the screen
        self.score_rect = self.score_image.get_rect()
        self.score_rect.right = self.screen_rect.right
        self.score_rect.top = 0

    def show_score(self):
        """ draw the score to the screen """
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.high_score_image, self.high_score_rect)

if __name__ == '__main__':
    a = Game()
    a.run_game()

A: The spawning of the asteroids depends on the next_object_time. next_object_time is initialized with 0. You need to set self.next_object_time when the play button is pressed:
class Game(Sprite):
    # [...]

    def _check_play_button(self, mouse_pos):
        if self.play_button.rect.collidepoint(mouse_pos):
            self.game_active = True
            pygame.mouse.set_visible(False)

            self.next_object_time = pygame.time.get_ticks() + self.time_interval

To make the algorithm more robust you can set next_object_time depending on the current time when an asteroid spawns (this is optional):
class Game(Sprite):
    # [...]

    def _update_asteroids(self):
        """ afer 'x' milliseconds create a new asteroid """
        current_time = pygame.time.get_ticks()
        if current_time > self.next_object_time:

            # self.next_object_time += self.time_interval
            self.next_object_time = current_time + self.time_interval

            self._create_asteroids()


text:
Q: timestamps microsecond precision is reset to 000 when kafka deserializes data to create sql insert (?) Using avro schema for data; have a field for timestamp named 'time'
and its like this:

     {"name": "time", "type":
   {"type": "long", "logicalType": "timestamp-micros"}},

The timestamp-micros could alternatively be timestamp-millis but
I want microseconds included that's why I chose this.
What is passed on here is :

{'time': datetime.datetime(2022, 1, 10, 6, 52, 53, 511281, tzinfo=)}

The problem is when this is deserialized I get something like

2022, 1, 10, 6, 52, 53, 511000
inserted into the database. This is shaving off the micros.
What is this related to?

What this is matched with


text:
Q: MYSQL moving order I have a mysql table.
I want to "cut and paste" a value from one column to another using php.  like this:
mysql_query("UPDATE table1 SET a1=a2,a2='' WHERE colid=3 LIMIT 1");

Is it possible to do this with just a single statement as above?
Does the ordering of the elements used in "SET" part matter?
If this is not good, what is the most efficient way to do this?

A: From the docs:

The second assignment in the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.
UPDATE t1 SET col1 = col1 + 1, col2 = col1;

Single-table UPDATE assignments are generally evaluated from left to right. For multiple-table updates, there is no guarantee that assignments are carried out in any particular order.

A: Tried it, works.  But like others have mentioned it is an efficiency step at the cost of maintainability.
Personally, I will be using the efficient code, since it's for a non-critical functionality.  If you want to use it, understand the risks.


text:
Q: Saving checkbox/option list status? my self-made admin panel works just fine, but it doesn't save values of form inputs.
When I type something into textbox and click "save" it is still there after refreshing, thanks to PHP:
<input type="text" name="header" value="<?php echo get_option('header'); ?>" />

So the PHP echoes its own value to a input and everything is just fine. But what to do when I have list of 10 radio buttons or just a checkbox?
For now I have a checkbox like this:
<input type="checkbox" name="showS" value="true">

And after clicking on it and saving - it's still "unclicked".
Any helping had?

A: This may be a HTML centric question, but as it happens WordPress does have some helper functions for dealing with checkboxes, select dropdowns, disabled inputs, etc..
http://sillybean.net/2010/09/wordpress-hidden-gems-checked-selected-and-disabled/
Rarst also pointed this out in his comment.
I always use these now, they look more elegant then the self-written alternative methods.

A: This is really just an html question, not specific to WordPress. Look into checked="checked" (for check boxes) or selected="selected" (for selects, radio buttons, etc.) In your case,
<input type="checkbox" name="showS" value="true"
    <?php if (get_option('showS')==true) echo 'checked="checked" '; ?>>

Since this is WordPress, though, I should also be reminding you to use the Settings API where possible. Don't try to sanitize and validate all of the inputs yourself unless you really know what you're doing. Here's a link to a tutorial on the Settings API:
http://ottopress.com/2009/wordpress-settings-api-tutorial/


text:
Q: EXT JS Combo drop down not displayed On IE11; EXTJS Popup Window show/display event freezes the application on IE11 I am facing following issues for my EXTJS application on IE 11:

*

*Combo box drop down not displayed on click of arrow trigger.

*Application gets freezes when Extjs window show event gets called (application get freezes during display/show event of Extjs popup window).
Application works properly on Chrome/Mozilla.
Application works properly on IE-11 which is located at location A.
Application not responding at all on IE-11 which is located at location B.
..Girish


text:
Q: Is there a local Google App Engine data viewer? I want to use google's online GAE data viewer offline...
Is there some bunch of python code to display all my local data and even schema?

A: Yes, go to http://localhost:8000/_ah/admin (supposing you're running your local instance with dev_appserver.py).
NOTE: when the app is being deployed locally, it logs to which port the admin page is being binded


text:
Q: 'cabal copy' failed during `stack build` in cifs directory I'm following these instructions. I successfully did stack new and stack setup but stack build fails.
I found a git issue that this may be due to extra files listed in the cabal file, but removing them didn't fix the issue (and I'm just using the new-template without any changes). I am on Ubuntu 14.04 and installed stack using the script. Is there anything else I can look into?
It appears that this might be due to me trying to build inside of a cifs directory. Is there anything I can do to handle this?
# stack build
ehri-haskell-0.1.0.0: configure (lib + exe)
Configuring ehri-haskell-0.1.0.0...
ehri-haskell-0.1.0.0: build (lib + exe)
Preprocessing library ehri-haskell-0.1.0.0...
Preprocessing executable 'ehri-haskell-exe' for ehri-haskell-0.1.0.0...
ehri-haskell-0.1.0.0: copy/register
Installing library in
/mnt/docs/RubymineProjects/ehri-haskell/.stack-work/install/x86_64-linux/lts-8.6/8.0.2/lib/x86_64-linux-ghc-8.0.2/ehri-haskell-0.1.0.0-Kh3VLZPfbij7EgcL22QBMN
Installing executable(s) in
/mnt/docs/RubymineProjects/ehri-haskell/.stack-work/install/x86_64-linux/lts-8.6/8.0.2/bin
/mnt/docs/RubymineProjects/ehri-haskell/.stack-work/install/x86_64-linux/lts-8.6/8.0.2/bin/.copyFile5965166491189641421.tmp:
copyFile: does not exist (Host is down)
'cabal copy' failed.  Error message:

--  While building package ehri-haskell-0.1.0.0 using:
      /root/.stack/setup-exe-cache/x86_64-linux/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.24.2.0 copy
    Process exited with code: ExitFailure 1

One possible cause of this issue is:
* No module named "Main". The 'main-is' source file should usually have a header indicating that it's a 'Main' module.

# stack --version
Version 1.4.0, Git revision e714f1dd3fade19496d91bd6a017e435a96a6bcd (4640 commits) x86_64 hpack-0.17.0

A: Looks like the issue is caused by the depth of the folder where the project lives (Windows 10, x64). From the moment the depth exceeds some threshold, described error appears. So try moving the project folder up in directories tree.


text:
Q: Redundant constructor overloads in std::function? According to cppreference, std::function has the following three constructor overloads:
template< class Alloc >
function( std::allocator_arg_t, const Alloc& alloc,
          const function& other );
template< class Alloc >
function( std::allocator_arg_t, const Alloc& alloc,
          function&& other );
template< class F, class Alloc >
function( std::allocator_arg_t, const Alloc& alloc, F f );

Wouldn't it be sufficient to just leave the last one? Would the first two provide any better performance (they are more specialized, anyway)? If so, how could it be done?

A: TLDR: It's an optimization
The first two versions take std::functions as arguments whereas the third version takes an arbitrary callable. Taking an arbitrary callable requires type erasure, so you end up with a function call overhead when calling an std::function and possibly a dynamic memory allocation for creation.
Removing the first two overloads would make std::function treat another std::function as a generic callable and type-erase that function, so you would end up with an std::function calling an std::function calling an std::function and possibly pay dynamic memory allocation each time.
Instead you treat std::function differently and instead of storing the std::function you just store the callable that the other std::function stores, thereby reducing the levels of indirection and dynamic memory allocations.


text:
Q: What does "principle" mean here? What's the meaning of principle in this definition of soul from Dictionary.com as in body and soul?

the principle of life, feeling, thought, and action in humans, regarded as a distinct entity separate from the body, and commonly held to be separable in existence from the body; the spiritual part of humans as distinct from the physical part.

Does principle in this context mean definition #7 of Google definition or does it mean something else that's not in this dictionary?

A: Actually, I could see #'s 6, 7 and 8 applying to the definition of "principle" as it relates to a component of a soul.  It's more the context of the example that drives my answer, not just the definitions in abstract.


text:
Q: General advice for malloc size I was wondering what would be some general guidelines on how to do malloc. Here would be an example of two different approaches using the following function:
split_strings_on_separator(char ** string_array_buffer, char *string, char *separator);
// for example: split_strings_on_separator(buffer, "big,word", ",");
// ==> ["big", "word", NULL];

One way I could do this is to malloc a "big enough" chunk of memory hoping that it probably won't make a big difference as long as I have enough, so I could do something like:
buffer = malloc(1000);

The other way would be more precise and would require me to calculate the exact size of the buffer. For example something like:
// separator and size
char * separator = ",";
size_t len_split_on = strlen(split_on);

// string and size
char * string = "big,word";
size_t len_string = strlen(string);

// exact_buffer_size = [sizeof pointer] x [num separator occurrences + 1 (array element exists after the last (or none) separator) + 1 (NULL at end)
malloc(exact_buffer_size);

Is one way wrong and the other correct, or when should one approach be used over the other? Using the first approach is obviously much easier and seems to be preferable on trivially-sized memory chunks (though maybe that's a lazy/naive way of thinking about it).


text:
Q: How to define a data structure in Json, with the name of the object at the top of the structure? I'm working on json and I really need to get this structure:
{

"Identidade":

       [

           {  "numero": 1704,  "numeroFinal": 1804,  "id": 28 },
           {  "numero": 1806,  "numeroFinal": 1905,  "id": 28 },
           {  "numero": 1705,  "numeroFinal": 1706,  "id": 29 },
           {  "numero": 1707,  "numeroFinal": 1807,  "id": 30 }

       ]

}

But until now I can only get this one, and I still have to be able to write the ** Identidade** at the top
   [

       {  "numero": 1704,  "numeroFinal": 1804,  "id": 28 },
       {  "numero": 1806,  "numeroFinal": 1905,  "id": 28 },
       {  "numero": 1705,  "numeroFinal": 1706,  "id": 29 },
       {  "numero": 1707,  "numeroFinal": 1807,  "id": 30 }

   ]

The code that follows is my current implementation.
public void writeJsonStream(String file, List<Identidade> iden) throws IOException {

    JsonWriter writer = new JsonWriter(new OutputStreamWriter(m_Context.openFileOutput(file, Context.MODE_PRIVATE)));
    writer.setIndent(" ");
    writeArray(writer, util);
    writer.close();
}

public void writeArray(JsonWriter writer, List<Identidade> iden) throws IOException {
    writer.beginArray();
    for (Identidade i : iden) {
        writeIdentidade(writer, i);
    }
    writer.endArray();
}

public void writeIdentidade(JsonWriter writer, Identidade iden) throws IOException

    writer.beginObject();
    writer.name("numero").value(iden.getM_numero());
    writer.name("numeroFinal").value(iden.numeroFinal());
    writer.name("id").value(iden.getID());
    writer.endObject();
}

Can someone give me a hint on how to add ** Identidade**?

A:  {
  "status": "100",
  "cart_qty": 0,
  "user": [
    {
      "pro_id": "63",
      "pro_title": "Nikon S9400 Advanced Point & Shoot Camera  (Red)",
      "pro_price": "16000.00",
      "pro_disprice": "12000.00",
      "pro_discount_percentage": 25,
      "pro_Img": [
        "http://backslashinfotech.in/laravel_Ecommerce/assets/product/nikon-coolpix-s9400-advance-point-and-shoot-original-imadgx8twu6buaag.jpeg",
        "http://backslashinfotech.in/laravel_Ecommerce/assets/product/nikon-coolpix-s9400-advance-point-and-shoot-original-imadgx8ty6rvx2dn.jpeg"
      ],
      "created_date": "07/13/2017",
      "pro_image_count": "1",
      "pro_qty": "23",
      "hit_count": "0",
      "sold_status": "1",
      "whishlist": 0
    },
  ]
}

this is json and below is logic of android side
try {
            JSONObject jsonObject= new JSONObject("respones");
            String status=jsonObject.getString("status");
            String scart_qty=jsonObject.getString("cart_qty");

            JSONArray user= jsonObject.getJSONArray("user");
            for (int i=0;i<user.length();i++){
                JSONObject json_data = user.getJSONObject(i);
                Log.e("pro_title",json_data.getString("pro_title"));
                Log.e("pro_price",json_data.getString("pro_price"));
                Log.e("pro_disprice",json_data.getString("pro_disprice"));
                Log.e("pro_discount_percentage",json_data.getString("pro_discount_percentage"));

                JSONArray itemArray=json_data.getJSONArray("pro_Img");
                for (int j = 0; j < itemArray.length(); j++) {
                    String value=itemArray.getString(j);
                    Log.e("PHOTOS_URL", j+"="+value);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

A: You have to create the JSON objects, assign them to a JSON array, then assign the array to a JSON object.
JSONObject obj1 = new JSONObject();
obj1.put("numero", 1704);
obj1.put("numeroFinal", 1804);
obj1.put("id", 28);

JSONObject obj2 = new JSONObject();
obj2.put("numero", 1806);
obj2.put("numeroFinal", 1905);
obj2.put("id", 28);

JSONObject obj3 = new JSONObject();
obj3.put("numero", 1705);
obj3.put("numeroFinal", 1706);
obj3.put("id", 29);

JSONObject obj4 = new JSONObject();
obj4.put("numero", 1707);
obj4.put("numeroFinal", 1807);
obj4.put("id", 30);

JSONArray jsonArray = new JSONArray();
jsonArray.put(obj1);
jsonArray.put(obj2);
jsonArray.put(obj3);
jsonArray.put(obj4);

JSONObject parent = new JSONObject();
parent.put("Identidade", jsonArray);

System.out.println(parent.toString());

output:
{
  "Identidade": [
    {
      "numeroFinal": 1804,
      "numero": 1704,
      "id": 28
    },
    {
      "numeroFinal": 1905,
      "numero": 1806,
      "id": 28
    },
    {
      "numeroFinal": 1706,
      "numero": 1705,
      "id": 29
    },
    {
      "numeroFinal": 1807,
      "numero": 1707,
      "id": 30
    }
  ]
}

You'll need a dependency to use JSONObject and JSONArray, if you're using a maven project add this in your pom.xml:
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
    </dependencies>

A: You can try this which uses ObjectMapper of Jackson API.
1) Create a DTO class :
package com.multithreading.concurrency;

public class Identidade {

 private int numero;
 private int numeroFinal;
 private int id;

public Identidade(int numero, int numeroFinal, int id) {
    this.numero = numero;
    this.numeroFinal = numeroFinal;
    this.id = id;
}

// getters and setters
}

2) Then write a parent bean, which will contain the above DTO reference :
public class ParentIdentidade {

    @JsonProperty("Identidade")
    private List<Identidade> identidade;
    // getters and setters
}

3) Now, write the test class to produce the desired output :
public class TestIdentidade {

public static void main(String[] args) {

    List<Identidade> idenList = new ArrayList<Identidade>();
    idenList.add(new Identidade(1704, 1804, 28));
    idenList.add(new Identidade(1806, 1905, 28));
    idenList.add(new Identidade(1705, 1706, 29));
    idenList.add(new Identidade(1707, 1807, 30));

    ParentIdentidade parentIden = new ParentIdentidade();
    parentIden.setIdentidade(idenList);

    ObjectMapper mapper = new ObjectMapper();
    try {
        String json = mapper.writeValueAsString(parentIden);
        System.out.println(json);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
}

It is producing the desired output :
{
"identidade": [{
        "numero": 1704,
        "numeroFinal": 1804,
        "id": 28
    }, {
        "numero": 1806,
        "numeroFinal": 1905,
        "id": 28
    }, {
        "numero": 1705,
        "numeroFinal": 1706,
        "id": 29
    }, {
        "numero": 1707,
        "numeroFinal": 1807,
        "id": 30
    }
  ]
}

A: Try this
writer.setIndent(" ");
writer.beginObject();
writer.name("Identidade")
writeArray(writer, util);
writer.endObject();
writer.close();


text:
Q: Wave file modification using java I am currently trying to write a program in which i have to process a .wav file, i need to process the data in the wave file.
My main aim is to extract the data from currently existing file, create a new file with appropriate wave headers, and then write the information/data in the new file.
I am expecting the program to be written in java.

A: I have come across this in Google:
http://www.jstick.de/javaprojects/sampleeditor
This is a WAV editor and should provide you with the ideas for your implementation since it is open source.


text:
Q: How to show in HTML a circle filled by one color within a cell table? I need to show a circle filled by one color within a table cell.  Somehow, I found an example that works but does not work reliably. Please, see the code below.
On IE the circle becomes a vertically elongated oval.  The same can happen on Mozilla with bigger cell height.
<!DOCTYPE HTML>

        <title>circle</title>

A: Use border-radius:100% instead of border-radius: 25px; in your css.
and remove the unused  tag from the markup.
You are using border-radius here so make sure your browser supports CSS3 Specifications.
JS Fiddle Demo

A: You also could create a SVG (Scalable Vector Object) to do this.
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
   <circle cx="41" cy="41" r="40" stroke="#333" stroke-width="1" fill="#800000"/>
</svg>

A: This worked for me:
CSS
.filled-circle {
  padding: 2px 11px;
  border-radius: 100%;
  background-color: #f38e23;
}

HTML

A: Use same width, height and border-radius. Example:
        width:25px;
        height:25px;
        border-radius:25px;


text:
Q: Ember- live preview image I'm doing a product form with a live preview just for fun
HBS

        Product name:
        {{input type="text" placeholder="First name" value=newProductname class="form-control"}}

        Price:
        {{input type="text" placeholder="$$" value=price class="form-control"}}

        Image location:
        {{input type="text" placeholder="Url" value=Url class="form-control"}}

And this live preview would come up simply using their values in  {{ }}

{{newProductname}}

{{price}}$

{{description}}

So how would you do this nested binding or simply recommend another solution?
cheers
Kristjan

A: For some reason Ember doesn't like uppercase properties, I'll look into it.  For now use a lowercase property name.

    Image location:
    {{input type="text" placeholder="Url" value=url class="form-control"}}

http://emberjs.jsbin.com/idUWEGU/2/edit
Update:
Looks related to a global namespace, apparently an uppercase property infers global namespace Bypass/disable uppercase -> global inference in Handlebars templates?
http://emberjs.jsbin.com/idUWEGU/1/edit
Other update:
You can always define the scope by qualifying your binding more.

    Image location:
    {{input type="text" placeholder="Url" value=controller.Url class="form-control"}}

http://emberjs.jsbin.com/idUWEGU/3/edit


text:
Q: Djano remot user login via java script In my django application hosted on heroku (https://ers-heatscreen-app.herokuapp.com) , i would like to authenticate users from an existing customer login on a productive homepage which is solved with java script.
So when they login at https://shop.ers-heatscreen.com/login i would like to take the existing user an create a new user/login with existing user in my application.
I have invested a ton of time in reading stackoverflow and django documentation, but cant puzzle things together....
Somehow is the best solution, to set a remote_user in django and solve the problem with django
MIDDLEWARE = [
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
]
....
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.RemoteUserBackend',
]

Maybe you have some hints/code snippeds/links for me to point me to the right direction.
Would really appreciate any help. If you need some more information, i can post further information anytime.

A: This Post was really helpful.
I created a Backend, where i get the user information via querystring und create/login the user.
With the middleware i managed to login automatically.
https://www.sipios.com/blog-tech/automatic-login-in-a-django-application-using-external-authentication


text:
Q: PHP wget link through javascript call I am using PHP and PHP Simple HTML Dom to get a link and download a csv file. However, the link is through a javascript call. Is there a way to get this through a PHP call or even wget through linux cmd? I am trying to get the spreadsheet through the Download Data link in the bottom right of the table.
Currently, I scrape the link by:
    <?php
include 'simple_html_dom.php';

//first we want to rip the data from pregame.com
$html =  file_get_html('http://pregame.com/sportsbook_spy/default.aspx');

$ret = $html->find('a');
$link=$ret[98]->attr['href'];

?>


text:
Q: postgresql data formatting while querying i am new to sql in postgreqsl my table looks like

city
fname
lname

nyc
max
smith

nyc
will
xxx

nyc
sam
123

wdc
stacy
xxx

wdc
kim
xxx

cap
john
xxx

cap
will
xxx

output should be like

city
fname
lname

nyc
max
smith

will
xxx

sam
123

wdc
stacy
xxx

kim
xxx

cap
john
xxx

will
xxx

any help is appreciated...
Regards

A: This type of formatting is usually handled on application side. However, it can be done in SQL, using order by and window functions:
select
    case when row_number() over(partition by city order by fname, lname) = 1
        then city
    end as city,
    fname,
    lname
from mytable
order by city, fname, lname


text:
Q: How to edit ManyToManyField in model's save() method? I have a method which has a required field for the author and a non-required field for co-authors. Sometimes the person which creates the post unintentionally, or because of the lack of knowledge, selects his/her own profile as a co-author.
I would like to remove the actual author from the co-authors, and I think the best way to do it is overriding model's save() method. Here's what I have so far, but it doesn't seem to work.
models.py
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _

User = get_user_model()

class Post(models.Model):
    PUBLICATION_STATUS_CHOICES = [
        ("PUBLIC", _("public")),
        ("PRIVATE", _("private")),
        ("DRAFT", _("draft")),
    ]

    title = models.CharField(max_length=100, verbose_name=_("post title"))
    summary = models.CharField(max_length=250, verbose_name=_("post summary"))
    content = models.TextField(verbose_name=_("post content"))
    is_markdown = models.BooleanField(default=True, verbose_name=_("Markdown"), help_text=_("Is this a post written in Markdown format?"))
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts", verbose_name=_("author of the post"))
    coauthors = models.ManyToManyField(User, blank=True, related_name="colab_posts", verbose_name=_("colaborators / co-authors"))
    date_created = models.DateTimeField(default=now, verbose_name=_("date of creation"))
    date_updated = models.DateTimeField(default=now, verbose_name=_("last update"))
    status = models.CharField(max_length=10, choices=PUBLICATION_STATUS_CHOICES, default=PUBLICATION_STATUS_CHOICES[0][0], verbose_name=_("post status"))
    slug = models.SlugField(unique=True, verbose_name=_("slug"))

    class Meta:
        ordering = ["-date_created"]
        verbose_name = _("post")
        verbose_name_plural = _("posts")

    def __str__(self):
        return f"{self.title} ← {self.author} ({self.date_created.strftime('%Y-%m-%d %H:%M:%S')})"

    def get_absolute_url(self):
        return reverse("blog:post_details", args=[self.slug])

    def save(self, *args, **kwargs):
        if self.author in self.coauthors.all():
            self.coauthors.remove(self.author)
        super(Post, self).save(*args, **kwargs)

A: IMO pre_save signal will be the best way to do that. Save your model as usual and then in pre_save signal remove author from coauthors.
example code:
from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=Post)
def validate_post_authors(sender, instance, created, **kwargs):
    post_author = instance.author
    instance.coauthors.remove(post_author)


text:
Q: Getting memory usage by python I am having trouble retrieving memory usage of my system using psutil.
When I run my code it retrieves the cpu usage correctly, but when it tries to get the memory it throws an AccessDenied error.
code:
if(pi['name']=='java.exe'):
    pro=psutil.Process(0)
    cpu=pro.cpu_percent(1)
    memory=pro.memory_full_info().uss/(1024*1024)
    return memory,cpu

Error message:
psutil.AccessDenied (pid=0)

How can i get memory usage?

A: psutil.Process() takes one argument - a process identifier (PID). If it is called without an argument or with None, then the pid of the current process is used.
On Window, pid 0 is the The System Idle Process, which requires SYSTEM privileges.
pro=psutil.Process(0) # here's your problem

If you want to get the memory/cpu usage of java.exe, you'll have to get the pid, then use psutil. In the example below, I have used firefox.exe:
import psutil
from ctypes import *
from ctypes.wintypes import *

class PROCESSENTRY32W(Structure):
    _fields_ = [("dwSize", DWORD),
                ("cntUsage", DWORD),
                ("th32ProcessID", DWORD),
                ("th32DefaultHeapID", POINTER(ULONG)),
                ("th32ModuleID", DWORD),
                ("cntThreads", DWORD),
                ("th32ParentProcessID", DWORD),
                ("pcPriClassBase", LONG),
                ("dwFlags", DWORD),
                ("szExeFile", c_wchar * MAX_PATH)]

def get_processes():
    TH32CS_SNAPPROCESS = 0x00000002
    INVALID_HANDLE_VALUE = -1

    CreateToolhelp32Snapshot = windll.kernel32.CreateToolhelp32Snapshot
    CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]
    CreateToolhelp32Snapshot.restype = HANDLE

    Process32FirstW = windll.kernel32.Process32FirstW
    Process32FirstW.argtypes = [HANDLE, POINTER(PROCESSENTRY32W)]
    Process32FirstW.restype = BOOL

    Process32NextW = windll.kernel32.Process32NextW
    Process32NextW.argtypes = [HANDLE, POINTER(PROCESSENTRY32W)]
    Process32NextW.restype = BOOL

    CloseHandle = windll.kernel32.CloseHandle
    CloseHandle.argtypes = [HANDLE]
    CloseHandle.restype = BOOL

    snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
    if snapshot == INVALID_HANDLE_VALUE:
        return []

    try:
        process_entry = PROCESSENTRY32W()
        process_entry.dwSize = sizeof(PROCESSENTRY32W)
        if not Process32FirstW(snapshot, byref(process_entry)):
            return []

        processes = []
        while Process32NextW(snapshot, byref(process_entry)):
            processes.append((process_entry.th32ProcessID, process_entry.szExeFile))
    finally:
        CloseHandle(snapshot)
        #print("Closed handle")

    return processes

for pid, name in get_processes():
    if name == "firefox.exe":
        pro = psutil.Process(pid)
        cpu = pro.cpu_percent(1.0)
        memory = pro.memory_full_info().uss/(1024*1024)
        print(memory, cpu)

Output:
471.2890625 1.6
127.15234375 25.0
18.50390625 0.0
668.09375 0.0
706.6875 0.0
512.671875 0.0
648.953125 4.7
1037.0859375 4.7
1160.1015625 98.4
337.46484375 0.0
1418.72265625 1.6
0.90625 0.0
0.90625 0.0