text:
Q: Play raw TX/RX bits as sound from a network interface? Alright, I know this is a weird one, but I want to hear the raw data being sent and received by my Wi-Fi card as sound data. I just find it interesting to hear data being sent as sound. The only true purpose it serves for me is to tell when my Wi-Fi card is transmitting data, and to provide a source of (somewhat) deterministic noise in my very silent office.

OS: Devuan Linux 5
Kernel: 5.10.0-17
WiFi card driver open source: yes
WiFi card: ID 0bda:c820 Realtek Semiconductor Corp. 802.11ac NIC

A:
The only true purpose it serves for me is to tell when my Wi-Fi card is transmitting data

So use that. Under /sys/class/net/<interface name>/statistics/ there are various counters, use e.g. rx_bytes and tx_bytes. Write a small program that reads the counters in a fixed interval, calculates the delta, and translates the delta in some kind of sound, e.g. noise modulated by the amount of bytes currently transmitted. You modulate volume or other parameters of the noise.

A: The most straightforward way to do this would be a variation of this approach:
sudo tcpdump -w - -U | aplay -

It captures the packets from an ethernet interface, then feeds it into the default audio device. You might want to try various filters on tcpdump or different sample rates on aplay.
Sometimes it actually sounds interesting. Personally, I'd prefer silence.

A:
The only true purpose it serves for me is to tell when my Wi-Fi card is transmitting data, and to provide a source of (somewhat) deterministic noise in my very silent office.

I went a bit overboard in the comments explaining why you can't hear "raw" data.
But what you really want is what phone communication engineers call comfort noise enriched with some kinda changing data.
So, build that! This is meant to be a small introduction on how to build such things. You can just follow and copy&paste along, or you can try to understand every step in depth – whatever excites you more :)
A Small Tutorial on How To Build Signal Generation Applications
Comfort Noise and GNU Radio Companion First Steps
Let's start with the comfort noise part. It's easy to install GNU Radio (run apt install gnuradio). Then open the GNU Radio Companion.
You'll want to read the official tutorials on https://tutorials.gnuradio.org, but for now, just use the search bar on the right to find two blocks:

*

*Audio Sink

*Noise Source

Add them to the canvas, and connect them. Double-click on the Noise Source block, and change its output type to "float".
Result should look like this:

Change the samp_rate variable block the same way to have the value 48000. Hit the "Execute" button. (Depends on your desktop environment, but typically looks like ⏵; you can also find it in the "Run" menu as "Execute".)

Congratulations, white noise coming out of your speakers! You can adjust the volume, as well, by setting the "Amplitude" of the noise source (Try 0.1 instead of 1).
Shaping the Noise and a Bit of Filtering
That's cool. Let's make the noise a bit less annoying, by finding the Low-Pass Filter block, removing the direct connection between Noise Source and Audio Sink and instead placing the filter in between them. Set the filter to be "Float -> Float (Decimating)", and set its cutoff frequency to be 3000, with a transition width of 1500. Now you have converted your white noise to more human-friendly low-pass noise, colored noise. Try it!

How We're Going to Get Data Rate Into Our System
Now, we'll have to somehow add the traffic information into this whole system.
You can do that by periodically asking Linux how many bytes have passed through the network interface, and calculating the difference to the last time you asked - that way, you get a data rate, simply a number. If that number is high, we want our noise to be louder, or some tone to be higher or... Basically, we could think of this as done electronic music artist sitting in front of their large modular synthesizer and turning knobs, any knob we want, for us, in dependence on the data rate.
So, small problem: unlike the Audio Sink and the Noise Sources, GNU Radio doesn't already come with a block that does the calculation of the data rate. That's not a problem, we can build that ourselves.
But How Does it Work?
Small step back. What happened when you clicked the "Execute" button? The GNU Radio companion went, looked at the Flow Graph you've built, and generates a Python program out of that.
This program instantiates all the blocks you've added, configures them, tells the GNU Radio runtime how they are connected. Then, the program tells the runtime to actually start hauling the data through the flow graph, which means it tells the Noise Source to produce a few noise samples, and as these are then ready, tells the Filter to filter them, and as that is done, tells the Audio Sink to hand the filtered samples off to the sound card. (In fact, in the meantime, the Noise Source has already started to produce more samples, everything runs in parallel.)
So, it's all small parts of software that generate, transform, or finally handle numbers exchanged between the block "upstream" a connection and their input, and between their output and a block "downstream".
Development Task at Hand
What We Want in the End
So, our job will be to write a small piece of software that does the same. We'll just plug it in after the filter. This is how I envisioned it would look like: (this is a mockup!)

It's a block that copies input to output, multiplying it with rate of change of some integer that gets read from a file.
So, the first argument would be the name of the file to read, I use "/sys/class/net/wlp0s20u11/statistics/tx_bytes" here – replace wlp0s20u11 with the device name of your wifi card (if in doubt, ask ip link or nmcli device).
The second argument would be the number of input samples after which the file gets read again, so that we get a continuous update.
Building It
So, I coded that. You can do the same! Find the "Embedded Python Block" block and add it to your flowgraph. Double click on it to open its properties, there click on "Open in Editor", and copy and paste exactly this code (whitespace is important!):
import numpy as np
from gnuradio import gr

class blk(gr.sync_block):
    """
    Multiply by difference read from file

    This block reads an integer from a text file, after every configurable
    interval of input has been processed, calculates the per-sample rate at
    which that integer changed since the last read, and multiplies the input
    with that rate to calculate the output.

    Parameters:
     - filename                  The file to read periodically
     - read_every_n_samples      After how many samples to re-read to
                                 calculate the per-sample rate
     - max_increment_per_sample  The maximum rate to which we normalize
                                 our current rate. Set to 0 to not normalize.
    """
    def __init__(self,
                 filename="/sys/class/net/wlp0s20u11/statistics/tx_bytes",
                 read_every_n_samples=1000,
                 max_increment_per_sample=0):
        gr.sync_block.__init__(
            self,
            name='Multiply by difference from file',  # will show up in GRC
            in_sig=[np.float32],
            out_sig=[np.float32])
        self.interval = int(read_every_n_samples)
        self.next_read_in = self.interval
        self.filename = filename
        self.factor = 1
        self.max_increment_per_sample = max_increment_per_sample

    def read_value(self):
        with open(self.filename, "r", encoding="ascii") as file_handle:
            line_string = file_handle.readline()
            return int(line_string)

    def start(self):
        self.last_value = self.read_value()

    def work(self, input_items, output_items):
        in_stream = input_items[0]
        output = output_items[0]

        if self.next_read_in == 0:
            # We've reached the point at which we need
            # to update the factor with which we multiply!
            # So let's do that:
            new_value = self.read_value()
            difference = new_value - self.last_value
            rate = difference / self.interval
            if self.max_increment_per_sample > 0:
                rate = rate / self.max_increment_per_sample
                rate = min(1, max(rate, 0))
            self.factor = rate
            self.last_value = new_value
            self.next_read_in = self.interval

        # number of samples to which apply the same factor
        # This is at most as many items we currently have available at
        # the input, or as many items are left in this update period
        # (whatever is less)
        n_to_process = min(len(in_stream), self.next_read_in)

        # from current offset, the next n_to_process
        # input values get multiplied with the same factor
        # and written to the output
        output[:n_to_process] = in_stream[:n_to_process] * self.factor
        # We've consumed n_to_process input items, so we advance our
        # offset and reduce the amount of outstanding input
        self.next_read_in -= n_to_process

        # We consumed and produced n
        return n_to_process

Save and close your editor.
The properties dialog should now look like this:

As, said, you'll have to replace wlp… by the actual device name of your wifi card. We update 4 times per second (and since we do samp_rate samples per second, that means once ever samp_rate/4 samples). And I set the maximum rate per second I'm expecting averaged over that period to be 5·10⁶ bytes/s, so 5·10⁶/samp_rate.
Conclusion
And we've just converted our mockup of what should happen to something that actually makes noise in accordance to the amount of bytes going out to your card. I've not only written it, I've tried it! It works. While I'm not doing anything, there's mostly silence, but an occasional packet from some chat program that I'm still there, or my email client checking in, but as soon as I cause some outbound data, I can hear the pulsation of packets.
So, if you know a bit of Python (not too much, honestly), and feel like reading the tutorials and my source code above, you'll be able to rightfully claim you've built a real-time signal processing system for monitoring network state acoustically. That's actually not too bad a feat, and it only took asking a question on here :)
Of course, this is far from perfect. You might want to modify the python code I gave you – probably, taking the logarithm of the rate would be a good idea. So would probably also be being cleverer about interpolating the rate (instead of just holding the last rate). If you feel like writing a bit of Python, I think this might be a good starting point. There's also no reason you need to feed in noise – instead of the Noise Source and the filter, you might just as well use a "Wav File Source" (that can read most compressed audio formats like Ogg vorbis, OPUS, MP4 AAC…, not only WAV files) to play your favourite music.
Or, you could use GNU Radio and a small radio receiver (so-called "RTL-SDR Dongle") with an appropriate antenna to actually receive your local radio station, and use that as basis signal instead of the noise. The options are quite varied! GNU Radio is a signal processing framework that's been created for these kinds of situations, where you need to process a stream of digital signal, be it audio, or radio signals, or something else altogether, in real time.


text:
Q: Failed to load resource: the server responded with a status of 404 (Not Found) showing in jQuery console( icon-1.png,icon-2.png,icon-3.png,icon-4.png) I am creating a web application where I have to add jQuery version 3.2.1. I have not installed JQuery-UI. But in the console the following error message is showing 4 times:
Failed to load resource: the server responded with a status of 404 (Not Found)
Every error contains icon-1.png missing at the right side and gradually icon-2.png to icon-4.png.
I have clicked the link but it is showing under image directory 4 icons are missing but there is no image folder in my directory.
I have searched my problem but in many solution they are saying jquery-ui have missing image. But I have not installed jQuery-ui. So, none of the answer solved my problem.
Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: End of proof box is not shown When I use the proof environment, the output does not show the tombstone   informs3 class.
The class can be download here by selecting INFORMS Journal on Computing Style Files.
I tired the recommendations posted here and here. If I use a regular document class, it works, but it does not properly work in informs3 class.
Here is a MWE.
\documentclass[ijoc,nonblindrev]{informs3}
\usepackage{amsmath}
\usepackage[amsmath,amsthm,thmmarks]{ntheorem}
\begin{document}
\begin{proof}
here is the proof.
\end{proof}
\end{document}

I also tried to add the symbol manually, but still did not work
\usepackage{amsmath,amsthm}
\makeatletter
\newcommand{\altqedhere}{%
  \ifmeasuring@\else\sbox0{\popQED}\fi
  \tag*{\qedsymbol}%
}
\makeatother

A: The informs3 class defines its own proof environment without any tombstone symbol. You can add
\renewcommand{\endproof}{\strut\hfill\Halmos\endTrivlist\addvspace{0pt}}

to your preamble to add the tombstone (which is the \Halmos command) to the end of the proof environment.


text:
Q: Countdown Timer Error I am trying to make a countdown timer but the timer doesn't count up or count down. Please Help ! it just shows +1.
:Plus
echo-------------------------------------------------------------------------
echo Please enter starting number...
set /p time=%time%
echo Please enter ending number...
set /p etime=%etime%
echo-------------------------------------------------------------------------
echo.%time%
set time=%time%

:loop1
set /p time=%time%+1
if %time%==%etime% goto timesup1
echo.%time%
ping localhost -n 2 > nul
goto loop1

:timesup1
echo.%etime%
echo Time is Up!
goto Opt

(The Minus Option just shows the number typed then '-1')
:Minus
echo ------------------------------------------------------------------------
echo Please enter starting number...
set /p time=%time%
echo Please enter ending number...
set /p etime=%etime%
echo-------------------------------------------------------------------------
echo %time%
set time=%time%

:loop2
set /p time=%time%-1
if %time%==%etime% goto timesup2
echo %time%
ping localhost -n 2 > nul
goto loop2

:timesup2
echo %etime%
echo Time is Up!
goto Opt

A: your problem is here:
set /p time=%time%+1

you need /a, not /p to do calculations (see set /?)
Also you shouldn't set %time%, because it's a system variable used by windows. (use another name, like sTime(analogue to eTime)


text:
Q: Исходный код Google Chrome Все знают, что Google Chrome - браузер с открытым исходным кодом, т.е OpenSource. Корпорация Google даже организовывает конкурсы, в которых участники ищут баги в исходном коде. Багов с момента выхода самой первой версии браузера было исправлено очень много: и серьёзных и не особо( Null-Byte в адресной строке, например ).
Так вот, хотелось бы взглянуть на исходный код браузера и попытаться что-либо понять в нем =). Посмотреть, как бравые разработчики гугла реализовали те или иные вещи...но исходники браузера я нигде найти не могу, даже на самом сайте разработчика( google.com ) выдается 404 ошибка. Может кто уже скачивал исходники и смотрел? В таком случае хотелось бы узнать, откуда вы скачивали.

A: Идите по этому адресу и изучайте материалы. Сам исходный код в режиме онлайн можно посмотреть тут

A: Собственно вот так вот можно получить исходник chromium ( именно на основе chromium, был написан google chrome ).
Так-же, не менее интересно, копаться в исходниках webkit и v8


text:
Q: Apply hash pattern to polygon in openlayers 3 I have tried to figure out a way to apply advanced fill style to polygons in OpenLayers-3. I would like to find a way to reproduce the following style with OL3:
Apply hash pattern to polygon in openlayers
http://dev.openlayers.org/sandbox/ossipoff/openlayers/examples/graphicfill.html
The OL2 solution uses the SLD format, which does not seem to be implemented in OL3.
I have found a great article from boundless geo discussing the geometry option of ol.style.Style that allows to provide advanced styling. This option is great, but applying a hash pattern to a polygon using this technique would heavily impact performance.
http://boundlessgeo.com/2015/04/geometry-based-styling-openlayers-3/
Any suggestions?
Thanks!

A: This is not yet supported but see https://github.com/openlayers/ol3/issues/2208 for a proposal


text:
Q: Finding 'Corresponding generalized eigenvectors:' So I have a matrix $$\begin{pmatrix}1&1&1\\0&1&1\\0&0&1\end{pmatrix}$$ and I have it solves to have an eigenvalue of $1$, with an eigenvector $(1,0,0)$. I looked on wolfram alpha and it says that it has 'Corresponding generalized eigenvectors' of $(0,1,0)$ and $(0,-1,1)$
How do I go about finding these?

A: Let's start by naming your given matrix :
$$A=\begin{pmatrix}1&1&1\\0&1&1\\0&0&1\end{pmatrix}$$
To find the eigenvalues of $A$, you must solve the equation : $\det(A-λI)=0$. So, we have :
$$\det(A-λΙ)=0\Rightarrow \Bigg| \begin{matrix} 1-λ & 1 & 1 \\ 0 & 1-λ & 1\\ 0 & 0 & 1-λ\end{matrix} \Bigg| = 0 \Rightarrow \dots \Rightarrow -(λ-1)^3=0 \Leftrightarrow λ =1$$
Note that your eigenvalue $λ_{1,2,3}=λ_1=1$ is of multiplicity $3$.
Now, to find the eigenvectors, you must solve the system : $(A-λ_1I)x=0$.
So :
$$(A-λ_1I)x=0 \Rightarrow (A-I)x=0 \Rightarrow \begin{bmatrix} 0 & 1 & 1 \\ 0 & 0 & 1 \\ 0 & 0 & 0 \end{bmatrix}\begin{bmatrix}x_1 \\ x_2 \\ x_3 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \\ 0\end{bmatrix}$$
$$\Leftrightarrow$$
$$\begin{cases} x_2 +x_3=0 \\ x_3=0 \end{cases}$$
This is something to be expected, as having an eigenvalue of multiplicty of $3$ while being the only one, should yield you $3$ different eigenvectors. You can observe that $x_2=x_3=0$ but $x_1$ is undetermined. Note, that eigenvectors should NOT be entirely $0$ vectors and must be linearly independent, so you cannot just take $3$ different values for $x_1$. The fact that the equation $ 0x_1 + 0x_2 + 0x_3 =0 \Rightarrow 0x_1 =0$ can be hold $\forall x_1 \in \mathbb R$, enables you to get $1$ eigenvector for a random $x_1$.
Taking $x_1=1$, we get the eigenvector :
$$v_1= \begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix}$$
To get, now, the other $2$ eigenvectors, you need to go through the Generalized Eigenvector calculation, which for $v_2$ will go as solving the system :
$$(A-λ_1I)v_2 = v_1$$
where you will express $v_2$ with variables that you'll find through solving the system.
Can you now, solve this system and yield $v_2$ and then proceed correctly for $v_3$ ?


text:
Q: Are Banach norms Fréchet differentiable? Suppose $(V, \|\cdot\|_V)$ and $(W, \|\cdot\|_W)$ are two Banach spaces and $f: V \to W$ is some function. We call a bounded linear operator $A \in B(V, W)$ Fréchet derivative of $f$ in $x \in V$ iff
$$\lim_{h \to 0} \frac{\|f(x + h) - f(x) - Ah\|_W}{\|h\|_V} = 0$$
We call a $f$ Fréchet differentiable in $x$ iff there exists a Fréchet derivative of $f$ in $x$.
My question is:

Suppose $(V, \|\cdot\|_V)$ is a Banach space. $f: V \to \mathbb{R}, v \mapsto \|v\|_V$. Is it true, that $f$ is Fréchet differentiable $\forall x \in V \setminus \{0\}$?

This statement is indeed true in the specific case, when $V$ is a Hilbert space.
Proof:
One can manually check, that $h \mapsto \frac{h}{2\sqrt{x_0}}$ is a Fréchet derivative for $x \mapsto \sqrt{|x|}$ in $x_0 \neq 0$. One can also manually check, that $h \mapsto 2\langle v, h \rangle_V$ is a Fréchet derivative for $x \mapsto \langle x, x \rangle_V$ in all $v \in V$. And it is a well known fact, that the composition of Fréchet derivatives of two functions is a Fréchet derivative of their composition. Thus, as $\|v\|_V = \sqrt{\langle v, v \rangle_V}$, we have, that $h \mapsto \ \frac{\langle v, h \rangle_V}{\|v\|_V}$ is a Fréchet derivative of $\|v\|_V$ in all $v \in V \setminus \{0\}$.

A: No this is not always true. Take $(V, \Vert \cdot \Vert)=(\mathbb R^2, \sup (\vert x \vert, \vert y \vert))$. The norm is not Fréchet differentiable when $x = \pm y$.


text:
Q: Is it possible to set attribute value through .send? Can I do something like this?
self.send(:twitter_url) = result

It doesn't work like this for me.
self.send(:twitter_url, result) # this doesn't work either

Model.twitter_url is an attribute (string column)
I need this for refactoring.

Ok, here's one more thing:
argument = :twitter_url
self.send(argument=, result)

What should I do here?

A: You should use twitter_url= "setter" method, so this should work:
send(:twitter_url=, result)

About your edit, you can do at least two things:
First approach:
send("#{argument}=", result)

second approach, using write_attribute:
write_attribute(argument, result)

A: For a Rails (ActiveRecord) model you can set an attribute via write_attribute:
write_attribute(:twitter_url, result)

or the shorthand []=:
self[:twitter_url] = result

A: I'm not going to repeat the other guys' answers, but just want to point out a difference between myobj.send("methodname=", value) and myobj[:methodname] = value.
The second one bypasses the usual setter method, which can do extra "stuff", ie have extra functionality besides just setting the value.  For example, with postcodes you might, for search or optimisation reasons, have another field which removes spaces and upcases the postcode, like this
#in User, who has name, address1, address2, postcode, tidied_postcode
def postcode=(pcode)
  self[:postcode] = pcode #the usual content of a setter like this
  self[:tidied_postcode] = pcode.gsub(" ","").upcase #some extra functionality
end

With this situation, if you were to do either of the following, tidied_postcode would get updated too.
@user.postcode = "abc 123"
@user.send("postcode=", "abc 123")

Whereas with these, tidied_postcode would not get updated.
@user[:postcode] = "abc 123"
@user.write_attribute(:postcode, "abc 123")

I just mention this in case it's informative.


text:
Q: When is it time to update OpenWRT on a router? Am using OpenWRT/LEDE on a great deal of various routers (the work they do is amazing!) and the open firmware works faster and better than the factory fw.
However, they don't release anymore "stable" version, (the last is 18.06.2), since the "joint venture" with LEDE.
The reason given was basically that with so many routers supported, people should carefully install the latest available snapshot. "Carefully" because the soft evolves, add features and fix bugs, and the team doesn't test all routers after each change (obviously) ; so a new version might not fit within the memory/flash constraints of such and such router after a change (there could be some regression as well).
The routers work ok, and I chose not to (take the risk to) update anymore, but maybe I'm missing new interesting features, or some performance gain (or bug fixes)?
Is there a better recommended "policy" to follow, regarding OpenWRT/LEDE updates? Any advice on when to update?

A: I don't think there is a official policy for OpenWRT devices.  My rule of a thumb, is to do it quaterly/half a year (depending on your time schedule and if you also have time to test it) or if there is an outbreak of some nasty stuff like some worm or some kind of attack that is used in the wild.
It takes time to monitor it, so I would recommend some RSS reader/agregator or visiting some of your favourite security site you read regularly.

A: Generally, there are some reasons why you update a software:

*

*Bug fixes

*Performance enhancements

*New features

*Security fixes/improvements/..

Personally I think the first three points can be decided on personal need or personal interest. If you are pleased with the current version regarding to speed and features, I think there is no need to upgrade/update. You may want to take a look at the latest added features or changes and decide if you are willing to take the risk.
But a clear reason to update is when it comes to security. Additionally, this is a 'critical' device, since it is directly accessible from the internet.
You should monitor the CVEs for your version and check them regularly. Take a look at security websites which report when it comes to new vulnerabilities.


text:
Q: Rotate table based on drop down input Data
I have a table B3:F7 with a changing range, more or less rows and columns.
Objective
I want to Rotate the original table using the input from the drop down I2:M2 to get the result like  90, 180, 270 Rotation.
To clarify

*

*I don't want to choose between them; I want the original table to be Rotated according to the input of the dropdown. I have only the original table and the data is mixed and the range is growing.

*The formatting is for demonstration only.
Progress
I tried transpose twice =TRANSPOSE(TRANSPOSE(B3:F7)) to get 180 result, but the output is reverted back to the original form B3:F7.
Sources
Make a copy

A: try:
=ARRAYFORMULA(IF(I2=O3, B3:F7,
 IF(I2=O4, TRANSPOSE(SORT(B3:F7, ROW(B3:F7), 0)),
 IF(I2=O5, TRANSPOSE(SORT(TRANSPOSE(SORT(B3:F7, ROW(B3:F7), 0)), ROW(B3:F7), 0)),
 IF(I2=O6, SORT(TRANSPOSE(B3:F7), ROW(B3:F7), 0), )))))


text:
Q: Django voting system: Determine rank in appropriate way I am trying to create a simple voting system but the problem is while displaying the rank of participants. For example if there are 20 participants and 10 have same votes then all of them are ranked same. All the participants have date_joined. So i want to re rank the participants having same number of votes based on date_joined. Any suggestions?
Below is the model for participants:
class participants(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
fullname = models.CharField(max_length =50)
email = models.EmailField(max_length =50, default='')
display_image = models.ImageField(upload_to=path_and_rename, max_length=500, help_text="Select display image")
date_joined = models.DateTimeField(null=True, blank=True)
dob = models.DateTimeField(null=True, blank=True)
gender =models.CharField(max_length =10)
competition_name = models.CharField(max_length =50,null=True, blank=True)
featured = models.BooleanField(default=False)
total_votes = models.IntegerField(default=0)
unique_key =  models.CharField(max_length =50, blank = True)

Below is the view:
def view_participant(request, participant_id):
//i want to display the rank of the participant from participant_id. Also the id of next and previous ranked user id.
// I have tried the following code:
    participant_data = participants.objects.get(id=participant_id)
    rank = participants.objects.filter(total_votes__gt=participant_data.total_votes).count()
    ranked_data =participants.objects.order_by('-total_votes')
    next_rank=0
    prev_rank=0
   if rank == 0:
        #checks if the participant is there is only one participants
        if rank ==0 and ranked_data.count() == 1:
            next_rank=0
            prev_rank=0

        #checks if the participant is first and there is more than one participants
        elif rank ==0 and ranked_data.count() > 1:
            next_rank = (ranked_data[rank+1]).id
        #checks if the participant is last
        elif rank == (ranked_data.count() -1):
            prev_rank = (ranked_data[rank-1]).id

    #checks if the participants rank is in between first and last rank
    elif rank > 0 and rank < (ranked_data.count() -1):
        prev_rank = (ranked_data[rank-1]).id
        next_rank = (ranked_data[rank+1]).id

A: Does this do what you're wanting?
views.py
ranklist = Participants.objects.all().order_by('total_votes', 'date')

You could also make a separate model for your votes:
models.py
class vote(models.Model):
    user = models.ForeignKey(participants, on_delete=models.CASCADE)
    date = models.DateField(auto_now_add=True)

and then annotate a vote count to each user, sort by that, and secondarily sort by date joined.
views.py
ranklist = Participants.objects.all().annotate(votes=Count('vote')).order_by('-votes', 'date_joined')

As far as displaying their rank, you can use {{forloop.counter}} to display their position in the list.


text:
Q: Markov chain steady state existence Is it possible for a Markov chain to have no steady state solution ? What is an example of such system ?

A: A finite Markov chain always has at least one steady-state distribution. If the transition matrix is $A$, each column of $A-I$ sums to $0$, so $A-I$ doesn't have full rank, and there is at least one nontrivial solution to $Ax=x$.
On the other hand a Markov chain with an infinite state space doesn't have to have a steady-state distribution. For example, consider the chain with state space $\{1,2,3,4,\ldots\}$, where state $k$ transitions to state $k+1$ with probability $1$.

A: In the excellent discussion of Markov chains in Feller's "Introduction to Probability Theory and Applications," the term "steady state" appears nowhere.  If your definition coincides whith "persistent state", then that means that the probability $f_{ii}$, given an initial state of $i$, of returning to $i$ eventually, is 1.  More precisely,
$$
\sum_{n=1}^{\infty}f^{(n)}(i) = 1
$$
where $f^{(n)}(i)$ is the probaility or a first return to state $i$ at time $n$.
The contrasting term to "persistent state" is transient state.  My own example of a Markov chain with no persistent state at all is as follows:
Consider a chain whose transition map is
$$
M : [0,1) \mapsto [0,1) : M(x) = \{ x\sqrt{2}\} $$
where the notation $\{w\}$ means the fractional part of $w$, that is, $w-\lfloor w \rfloor$.
The states of $M$ are the reals on the half-open interval $[0,1)$.  No state will every repeat exactly, so there is no persistent ("steady") state.


text:
Q: Aligning views at runtime in RelativeLayout How do I add a view in relative layout at runtime, so that it aligns itself at the Top of the parent. Say I am adding an EditText on clicking the button. Now this EditText should come in such a way that EditText comes above the Button.
here is an example of what I am doing.
    button = new Button(this);  //here I am just checking if the button can come above the EditText
    button.setText("I am a button");
    params.addRule(RelativeLayout.BELOW, editText.getId());
    params.addRule(RelativeLayout.ALIGN_PARENT_ABOVE);
    relativeLayout.addView(button);

I am not able to make the alignment at all.
Any clue is highly appreciated.
Thanks in Advance.

A: You need to use the overload of RelativeLayout.addView that takes your LayoutParams as a second parameter
    button = new Button(this);  //here I am just checking if the button can come above the EditText
    button.setText("I am a button");
    params.addRule(RelativeLayout.BELOW, editText.getId());
    params.addRule(RelativeLayout.ALIGN_PARENT_ABOVE);
    relativeLayout.addView(button, params);

addView method

A: Dont go such complex
Instead
Step 1 : Add a Linear Layout with Vertical orientation where so ever you are adding your button
Step 2 : First Add EditText and Set its Visibility to GONE
Step 3 : Add Your Button
Step 4 : On button click simply make your button VISIBLE
This will work for sure and is easy to implement to
Hope it helps :)


text:
Q: CSS order rules question Why the following code results in red color rather than black ?
HTML:

CSS:
div {
    width: 100px;
    height: 100px;
}

[att=A].classA {
    background-color: red;
}

.error {
    background-color: black;
}

If I remove [att=A], it becomes black, as expected. Why is that ?

A: It's because of CSS Specificity. The 'red' rule is more specific (elements which have this attribute AND this class) than the 'black' rule (elements which have this class). When you remove the [att=A], they have the same specificity, but because the black rule is later in the file, it wins.

A: The most specific selector wins, and [att=A].classA is more specific than .error.  Without it, the last one declared in the CSS wins, for example:
.error {
    background-color: black;
}
.classA {
    background-color: red;
}

Would also result in red.

A: Because in CSS, specificity counts towards the "Cascade" too.
[att=A].classA targets an attribute and a class name.
.error only targets a class name
Because the first is more specific, it gets applied over top of the second.
If you want to forcefully override a previously applied style, you can use the !important declaration:
[att=A].classA {
    background-color: red !important;
}

However, I should note, IE ignores the !important declarationhas buggy support for it, so use it with care.


text:
Q: JBOSS configuration error I'm trying to add the following security-domain in the JBOSS AS7 standalone.xml
<security-domain name="form-authentication" cache-type="default">
                <authentication>
                    <login-module code="Database" flag="sufficient">
                        <module-option name="dsJndiName" value="java:jboss/datasources/MySqlDS"/>
                        <module-option name="principalsQuery">select password from Users_Authentication where username=?</module-option>
                        <module-option name="rolesQuery">select rolename, 'Roles' from Users_Roles where username=?</module-option>
                    </login-module>
                </authentication>
</security-domain>

But I'm having the following error: Missing required attribute(s): value (pointing to the second module-option). I've already tried to put value="", but a new error appears pointing to the closing tag </module-option>.

A: Try the following principalQuery and rolesQuery module-option descriptors. Actually you need to put the "select .... " in the values part.
<module-option name="principalsQuery" value="select password from Users_Authentication where username=?"/>
<module-option name="rolesQuery" value="select rolename, 'Roles' from Users_Roles where username=?"/>


text:
Q: Include tags in WP_Query I found several posts about it. Others said that you cannot do it without a plugin and others that it is possible. However, I am not sure what is true :P
This is my query and unfortunately, I cannot make it return objects with a certain tag.
<?php
global $query_string;

$query_args = explode("&", $query_string);
$search_query = array();

foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $search_query[$query_split[0]] = urldecode($query_split[1]);
}

$search = new WP_Query($search_query);
?>

Any idea how I can modify the query to include also the tags without a plugin?

A: This solution may work for you also Include custom taxonomy term in search


text:
Q: Building an IPA file with Xcode I have a app and have successfully built it with Xcode. The problem is I want to test this application on my iPad. I know there is Apple developer program and stuff. But before going there I wanted to try this app first. There is a website called testflightapp.com where we can deploy applications to iPad on the fly.
That requires a IPA file. How do I go about it ?

A: You can create an IPA file in Xcode with "Build -> Build and Archive". Now open "Window -> Organizer" and you find the IPA in the section "Archived Applications". Save the IPA to a folder now.
IMPORTANT: You have to be an Apple developer to create an IPA file. The IPA file have to be signed with certificates, etc. ...

A: Put your ad-hoc profile before archiving the project. Once you are ready.
Go to Product ---->Archive  upon successful archiving you will see Organizer Window Navigate through to
Archives then click on Distrubition next window you need to choose Save for Enterprise or Ad-Hoc Deployent then you will choose your AdHoc profile and save.

A: The directions for that are at http://support.testflightapp.com/kb/tutorials/how-to-create-an-ipa.  You might need to be in the developer program to create a valid IPA file, though.

A: To load an app on a physical device you MUST be an Apple developer, it is not optional.
Once you have your account, you will need to enter your device IDs and generate a certificate against those device IDs at developer.apple.com
The certificate is used to sign the IPA and allow it to run on the pre-defined devices.


text:
Q: How to retrieve the parent frame name by its element I got the reference of element inside the frame by dom click event, How do i know its frame name.
function eventTrigger(evt){
     alert(evt.target.name);    //Need to know frame name of evt.target
}

frame.addEventListener("click", eventTrigger);

A: I'd suggest you to check this:

function eventTrigger(evt){
     // alert(evt.target.name);
     console.dir(evt.target);
}

frame.addEventListener("click", eventTrigger);

You can see on the console panel all the properties of the element. If it has a name you can target the name with evt.target.name but you have to set it on the html. A class or an id could be useful in this situation too.
evt.target.classListor evt.target.id


text:
Q: Eclipse quit Unexpectedly on MacOS I have just installed Eclipse IDE for Enterprise Java and Web Developers on Mac OS Catalina Version 10.15.7, yesterday. I dragged the Eclipse.app from the Downloads folder to the Application folder. It was working just fine. I created a couple of servlets. But today when I clicked on the app to open it, I got a problem report (Error), and so it didn't open.
The error details are..

Time Awake Since Boot: 3300 seconds
System Integrity Protection: enabled
Crashed Thread:        0
Exception Type:        EXC_CRASH (Code Signature Invalid) Exception
Codes:       0x0000000000000000, 0x0000000000000000 Exception Note:
EXC_CORPSE_NOTIFY
Termination Reason:    Namespace CODESIGNING, Code 0x1
kernel messages:
VM Regions Near 0 (cr2):
__TEXT                 000000000c447000-000000000c44b000 [   16K] r-x/r-x SM=COW

Thread 0 Crashed: 0   ???
0x0000000015674000 _dyld_start + 0
Thread 0 crashed with X86 Thread State (64-bit):   rax:
0x0000000000000000  rbx: 0x0000000000000000  rcx: 0x0000000000000000
rdx: 0x0000000000000000   rdi: 0x0000000000000000  rsi:
0x0000000000000000  rbp: 0x0000000000000000  rsp: 0x00007ffee37bcc60
r8: 0x0000000000000000   r9: 0x0000000000000000  r10:
0x0000000000000000  r11: 0x0000000000000000   r12: 0x0000000000000000
r13: 0x0000000000000000  r14: 0x0000000000000000  r15:
0x0000000000000000   rip: 0x0000000015674000  rfl: 0x0000000000000200
cr2: 0x0000000000000000    Logical CPU:     0 Error Code:
0x00000000 Trap Number:     0

In fact, I already googled the issue but the solutions that worked for others didn't work for me. For example, I tried the following solutions:

*

*move the Eclipse.app from the Application folder

*eclipse -clean

*I double clicked the executable eclipse, which in  /Applications/Eclipse.app/Contents/MacOS
I thought of re-installing Eclipse, but before that I want to know if there is a solution for this issue.

A: Modern Eclipse (2021-09 and perhaps even before) has a major incompatibility with Gatekeeper which checks for CODESIGNING of the Eclipse.app bundle. Self-modification of bundles is not permitted by Apple as it undermines the security model of macOS -- as malware protection (Xprotect). See: https://eclecticlight.co/tag/gatekeeper/
I suspect the Info.plist changes after initial launch or when modifying some user preferences or IDE settings.
Workaround such as trying to codesign manually is cumbersome and didn't work for me on Catalina:
codesign -v -vvv --deep /Applications/Eclipse.app
/Applications/Eclipse.app: invalid Info.plist (plist or signature have been modified)
In architecture: x86_64

sudo codesign --force --sign -  /Applications/Eclipse.app
Password:
/Applications/Eclipse.app: replacing existing signature
/Applications/Eclipse.app: bundle format unrecognized, invalid, or unsuitable
In subcomponent: /Applications/Eclipse.app/Contents/MacOS/${user.home}

What did work for me was defining an exception for Gatekeeper's Xprotect by recursive removal specific extended attribute for quarantine. Use the following directly after installing Eclipse and before running it:
xattr -r -d com.apple.quarantine /Applications/Eclipse.app

See: https://eclecticlight.co/2019/06/17/what-to-do-when-you-cant-launch-an-app/

A: Code Signature Invalid means that the app has somehow been corrupted which causes the signature to not match anymore. Re-installing is the proper course of action to fix this.
As for what caused it, it's something that happened between the last successful launch and the first time it didn't start. Maybe it's a bug in Eclipse itself, maybe it's an action you took. It's hard to figure out after the fact. If it keeps happening, the Eclipse bugtracker is the proper place to report it.


text:
Q: Convert 1d numpy array to 2d I have an array A of shape (30,) where each row has a list with 2000 elements. I want to convert this into a 2d array of shape (30, 2000). This is what I tried
A = np.reshape(A, (30, -1))

But, running this gives me an array of shape (30, 1) rather than (30, 2000). What should I do to get the correct shape?

A:
where each row has a list with 2000 elements

As Ahmed Mohamed AEK points out in the comments this won't work as the numpy object is of shape (30,). One easy fix is to stack them into a 30 by 2000 np.array.
For example:
A = np.vstack(A)

or equvalently:
A = np.stack(A, axis=0)


text:
Q: Floating multiple divs in one row I'm trying to show 4 widgets next to each other in a WordPress footer. I added into functions.php and footer.php files, so that the widget-content gets loaded.
But I'm unsure on how to display the widgets next to each other and starting at the same position as the header content, like in regular 4-column footer WordPress themes.
After a lot of tries, I managed to show them all in one row. left- & right-margins dont work anymore.

The css part looks like this:
.widgetfooter {
            margin-left: auto;
            margin-right: auto;
            display: flex;
            float: left;
            width: 15%;
            max-width: 1200px;
}

I includes the widget into the footer.php file like this:
<?php if ( is_active_sidebar( 'footer-sidebar1' ) ) : ?>

        <?php dynamic_sidebar( 'footer-sidebar1' ); ?>

<?php endif; ?>

In the functions.php:
register_sidebar( array(
    'name' => __( 'Footer Widget Area1', 'scentchild' ),
    'id' => 'footer-sidebar1',
    'description' => __( 'Appears on the footer, which has its own widgets', 'footer-sidebar1' ),
    'before_widget' => '
',
    'after_widget' => '
',
    'before_title' => '
',
    'after_title' => '
',
) );

Can somebody help me out with the css, please?

A: Structure:
grandparent
  parent
    child
    child
    child
    child

Float (in the middle):
grandparent {
  text-align:center;
}
parent {
  margin: 0 auto;
  max-width: /* desired content width, in px, according to theme
              * mind responsiveness here...
              */
}
child {
  margin: 0;
  display: inline-block;
  width: 25%;
  float: left;
}

Flex
(preferred, as you have more alignment options, especially if your children are smaller than parent available space and you want them to evenly distribute. It also allows vertical alignment - read more on flex if interested):
grandparent, parent {
  display:flex;
  justify-content: center; /* horizontal alignment,
                            * if flex-direction is row (default)
                            */
}
child {
  flex: 0 0 25%;
}
/* optional: */
parent {
  max-width: ... /* desired max-width here */
  align-items: center; /* vertical alignment */
}

Both of the above work if none of the rules are overridden by other rules. So you'd need to replace grandparent, parent and child with appropriate selectors.
You'll also need to specify rules for how to display the widgets at lower screen widths, inside @media queries, tuned in with your theme's responsiveness breakpoints.


text:
Q: toggle making weird effect jquery Can somebody explain me why this dropdown menu is acting weird, instead of display the menu above the image it make some weird effect
this is a live example(I don't know how to display images on fiddle)
Fiddle (http://jsfiddle.net/8YqKc/2/)
   #dropMenu {
    display: none;
    position: relative;
    right: 5px;
    background: #000;
    color: black;
    margin:30% -5% 0% -142%;
    padding: 0px 0px 0px 10px;
}

#dropMenu a {
    display: block;
    color: #fff;
    text-decoration: none;
    padding:10px 6px;
    font-weight:400;
    border-bottom: solid 1px #fff;
}

#dropMenu a:hover {
    background: #57585A;
}

#dropMenu ul {
    list-style:none;
    padding:0;
}

$(document).ready(function() {
 $("li").click(function() {
                 $("#dropMenu").hide("slow");
            });

  $("a").click(function(){
    $(this).toggleClass("active");
    $(this).next("div").stop('true','true').slideToggle("slow");
  });

});

Campus Alerts

A: its because default margin of UL
Add this in your CSS:
#dropMenu ul { margin:0 }


text:
Q: Execute Command work in cmd and not work in java code i have problem with this code
i use the CLC (cloud fondry)to deplyer the application in the cloud
my code is
public class cmd1 {

public static void main(String[] args) throws IOException, InterruptedException {
    String[] command =
        {
            "cmd",
        };
        Process p = Runtime.getRuntime().exec(command);
        new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
        new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
        PrintWriter stdin = new PrintWriter(p.getOutputStream());
        stdin.println("dir c:\\ /A /Q");  //ca march bien

        stdin.println("cf login");        //ca march

        stdin.println("hakimguettaoui@gmail.com");   //ici si j'ai fait un login il me demander Email et mot de pass mais il me
                                                     // donnée un pb
        stdin.println("");

        // write any other commands you want here
        stdin.close();
        int returnCode = p.waitFor();
        System.out.println("Return code = " + returnCode);

}

}
class SyncPipe implements Runnable {

public SyncPipe(InputStream istrm, OutputStream ostrm) {
 istrm_ = istrm;
 ostrm_ = ostrm;}
 public void run() {
 try
 {
     final byte[] buffer = new byte[1024];
     for (int length = 0; (length = istrm_.read(buffer)) != -1; )
     {
         ostrm_.write(buffer, 0, length);
     }
 }catch (Exception e)
 {
     e.printStackTrace();
 } } private final OutputStream ostrm_; private final InputStream istrm_;

}
all of command is work but
if i use cf login is work but the authentification
is not work lock the err
enter image description here

A: You're doing it correctly, separate Threads for STDOUT and STDERR.  After using Runtime for years, I switched to ProcessBuilder...Maybe switch to ProcessBuilder.  See the following posts on this :
Java Runtime OR Processbuilder OR Other
Java - ProcessBuilder command arguments with spaces and double-quotes fails


text:
Q: Find Transformation Matrix with constraint I have two sets of 3d points, and I have to find the best transformation matrix between the two sets. This I can do, and I do it via an SVD algorithm.
However, I'd like to add a constraint to this transformation. For example, I'd like one specific point of the first set to correspond exactly to a specific point of the second set.
How can I achieve this?
Thanks in advance.

A: That means that one of the row of the matrix will be $(0,0,\cdots,1,\cdots,0)$.
Permutate the points so as to bring the $1$ on the upper corner, and proceed as usual with the $n-1$ matrix. Finally do a back-permutation.


text:
Q: All checkboxes getting checked even if one is checked I'm making a basic todo app in angularjs.
Here's the code that's used to create a new todo with a checkbox

Enter Todo
 <input type="text" ng-model = 'new'>
    <button ng-click = 'add();' ng-disabled="status();">Add</button>

        <input type="checkbox" ng-model = "todo.done" /> {{i.name}}

The problem is that all the checkboxes get checked even when I check just one
Here's my controller module
todoApp.controller('controller',['$scope',function($scope){
 $scope.new = '';
 $scope.todo = [];

 $scope.add = function(){
    $scope.todo.push({name : $scope.new, done: false});
    console.log($scope.todo);
    $scope.new = '';
 };

 $scope.status = function(){
    return !(/\S+/.test($scope.new));
 };

A: Because the list of the checkbox are sharing the same model. You can create a custom directive or you can use checklist-model directive.
Demo URL:
https://vitalets.github.io/checklist-model/

A: ng-model = "i.done"

should solve the problem. In your version ng-model = "todo.done" todo is an array and angular just creates a property on the fly, when it's used for the first time. This way all of your checkboxes are connected to this property, that's why checking one checkbox affects all of them.


text:
Q: Transform Hot Encoding I have this data;
ID   Month
001  June
001  July
001  August
002  July

I want the result to be like this:
ID   June  July  August
001   1     1      1
002   0     1      0

I have tried one-hot encoding, my query is like this:
one_hot = pd.get_dummies(frame['month'])
frame = frame.drop('Month',axis = 1)
frame = frame.join(one_hot)

However, the result is like this
ID   June  July  August
001   1     0      0
001   0     1      0
001   0     0      1
002   0     1      0

May I know which part of my query is wrong?

A: get_dummies returns strictly 1-hot encoded values, you can use pd.crosstab:
>>> out = pd.crosstab(df.ID, df.Month)
>>> out

Month  August  July  June
ID
1           1     1     1
2           0     1     0

To preserve the order of appearance of Months, you can reindex:
>>> out.reindex(df.Month.unique(), axis=1)

Month  June  July  August
ID
1         1     1       1
2         0     1       0

In case an ID can have more than 1 month associated with it and you want to see it as 1:
out = out.ne(0).astype(int)

can be used afterwards.

A: If need hot encoding convert ID to index and aggregate max for always 0,1 ouput:
one_hot = (pd.get_dummies(frame.set_index('ID')['Month'])
             .max(level=0)
             .reindex(df.Month.unique(), axis=1))
print (one_hot)
    June  July  August
ID
1      1     1       1
2      0     1       0


text:
Q: Multiple split on strings I have a string of the form:
s = "1,2;3,4"
I have to obtain:
res = [(1,2),(3,4)]
I could not came up better than:
pairs = [pair.split(",") for pair in s.split(";")]
res = [(int(a), int(b)) for a,b in pairs]

In fact this doesn't work:
>>> res = [(int(a),int(b)) for pair in s.split(";") for a,b in pair.split(",")]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
ValueError: not enough values to unpack (expected 2, got 1)

My questions are:

*

*Is there a one-liner solution? What's the most pythonic way to achieve this?

*Why my latter code doesn't work?

A: Try this instead:
>>> [tuple(int(x) for x in i.split(',')) for i in s.split(';')]
[(1, 2), (3, 4)]

Or with unpacking:
>>> [(*(int(x) for x in i.split(',')),) for i in s.split(';')]
[(1, 2), (3, 4)]
>>>

Or:
>>> [tuple(map(int, i.split(','))) for i in s.split(';')]
[(1, 2), (3, 4)]

You could try a list comprehension with tuple(map(...)) or a nested list comprehension.
The reason your code doesn't work is because you're trying to iterate through a list with two items while you're unpacking it by two iterators. Iteration isn't required for that. To fix your code try:
res = [(int(pair.split(',')[0]), int(pair.split(',')[1])) for pair in s.split(";")]
print(res)

Output:
[(1, 2), (3, 4)]

Or:
[(int(a), int(b)) for a, b in [pair.split(",") for pair in s.split(";")]]

A: You can fix your own approach:
[(int(a), int(b)) for a, b in (pair.split(",") for pair in s.split(";"))]

Or you can be more concise, using some mapping and unpacking:
[(*map(int, p.split(",")),) for p in s.split(";")]
# [(1, 2), (3, 4)]

A: Your attempt was almost correct, just need to wrap the pair split in an iterable:
change
[(int(a),int(b)) for pair in s.split(";") for a,b in pair.split(",")]

to:
[(int(a),int(b)) for pair in s.split(";") for a,b in [pair.split(",")]]

Short alternative:
[*map(eval, s.split(';'))]

(Use ast.literal_eval if the data can't be trusted.)


text:
Q: Is it possible to add different table header in a Colspan I am trying to add text above every column in Colspan but nothing works as expected.
https://i.stack.imgur.com/MxQPj.png as shown here in the image I want in columns of colspan to be
1 2 3 4 5 O, but I don't know how to make that.
Here is example of my code

            @DbResHtml.T("Натпреварувач", "Resources")

            @DbResHtml.T("Бр.", "Resources")

        @DbResHtml.T("ВИ", "Resources")

            @DbResHtml.T("П.", "Resources")

            @DbResHtml.T("Грешки", "Resources")

            @DbResHtml.T("12345O", "Resources")

Tbody code is not included for clarity.

A: I'm not sure if I'm following your question correctly, but if you want text above each column a colspan will prevent that from working correctly. You would need to split them into their own  elements.

        @DbResHtml.T("Натпреварувач", "Resources")

        @DbResHtml.T("Бр.", "Resources")

    @DbResHtml.T("ВИ", "Resources")

        @DbResHtml.T("П.", "Resources")

    @DbResHtml.T("Г", "Resources")

        @DbResHtml.T("1", "Resources")

    @DbResHtml.T("р", "Resources")

        @DbResHtml.T("2", "Resources")
    @DbResHtml.T("е", "Resources")

        @DbResHtml.T("3", "Resources")
    @DbResHtml.T("ш", "Resources")

        @DbResHtml.T("4", "Resources")
    @DbResHtml.T("к", "Resources")

        @DbResHtml.T("5", "Resources")
    @DbResHtml.T("и", "Resources")

        @DbResHtml.T("O", "Resources")

As it appears you are pulling from a Db so you could split the strings into arrays and perform a loop to generate each  for each character in the array.
Hope this helps.


text:
Q: Slow upload to azure blob storage with python The Api receive the file, than tries to create an unique blob name.
Than I upload in chunks of 4MB to the blob. Each chunk takes something about 8 seconds, is this normal? My upload speed is 110Mbps. I tried uploading a 50MB file and it took almost 2 minutes. I don't know if the azure_blob_storage version is related to this, I'm using azure-storage-blob==12.14.1
import uuid
import os
from azure.storage.blob import BlobClient, BlobBlock, BlobServiceClient
import time
import uuid

@catalog_api.route("/catalog", methods=['POST'])
def catalog():
    file = request.files['file']

    url_bucket, file_name, file_type = upload_to_blob(file)

def upload_to_blob(self, file):
    file_name = file.filename
    file_type = file.content_type

    blob_client = self.generate_blob_client(file_name)
    blob_url = self.upload_chunks(blob_client, file)
    return blob_url, file_name, file_type

def generate_blob_client(self, file_name: str):
    blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)
    container_client = blob_service_client.get_container_client(self.container_name)

    for _ in range(self.max_blob_name_tries):
        blob_name = self.generate_blob_name(file_name)

        blob_client = container_client.get_blob_client(blob_name)
        if not blob_client.exists():
            return blob_client
    raise Exception("Couldnt create the blob")

def upload_chunks(self, blob_client: BlobClient, file):
    block_list=[]
    chunk_size = self.chunk_size
    while True:
        read_data = file.read(chunk_size)

        if not read_data:
            print("uploaded")
            break

        print("uploading")
        blk_id = str(uuid.uuid4())
        blob_client.stage_block(block_id=blk_id,data=read_data)
        block_list.append(BlobBlock(block_id=blk_id))

    blob_client.commit_block_list(block_list)

    return blob_client.url
    ```

A: I tried in my environment and got below results:
I tried with 50 mb file to upload blob storage account with chunk size of 4*1024*1024 from local environment to storage account it takes 45 secs.
Code:
import uuid
from azure.storage.blob import BlobBlock, BlobServiceClient
import  time

connection_string="<storage account connection string >"
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client('test')
blob_client = container_client.get_blob_client("file.pdf")
start=time.time()
#upload data
block_list=[]
chunk_size=4*1024*1024
with  open("C:\\file.pdf",'rb') as  f:
  while  True:
        read_data = f.read(chunk_size)
        if  not  read_data:
            break  # done
        blk_id = str(uuid.uuid4())
        blob_client.stage_block(block_id=blk_id,data=read_data)
        block_list.append(BlobBlock(block_id=blk_id))

blob_client.commit_block_list(block_list)
end=time.time()
print("Time taken to upload blob:", end - start, "secs")

In the above code, I added the timing method of both start and end at end of code I used the end-start process to know the timing of uploaded file in blob storage.
Console:

Make sure your internet speed is good and also, I tried with some other internet speed it takes maximum 78secs.
Portal:


text:
Q: Mac OS X Terminal - Display list of File Types from Subfolders I have an external hard drive that has the content of a Recovered Drive.  All the folders have 'recup_dir.XX' names and there are over a thousand.
I have copied over all content I can think of, of specific file types using:
find . -type f -name \*.jpg -exec cp \{\} /Volumes/somedrive/somefolder/ \;

I went through all file types I can think of - but I want to see what file types are on the drive and in the sub folders.
What command can I use that will go through all folders and sub folders and display 'total's for each file type?
du -hcs

Gives a total of the Drive- but I am after a Total per File Type.
Can anyone help point me in the right direction.  I have thousands of folders and I want to make sure I haven't forgotten any file types - so want to get a list of them.
Thanks for your help in advance.

A: You can do this with awk (as well as other scripting languages).  Here is a script in awk:
#!/bin/sh
find . -type f -ls | awk '
{
    type = $11;
    if ( type ~ /\./ ) {
        sub(/^.*\./, "", type);
    } else {
        type = ".";
    }
    sizes[type] += $7;
}
END {
    for ( type in sizes ) {
        printf "%10d %s\n", sizes[type], type;
    }
}' | sort -r -n

It uses an array sizes with the file-suffix as an index.  awk does not have built-in sorting, but you can do that by piping the result through sort.
For example, here is output from MacOS running in a copy of the Debian scripts for the xterm package:

341580 html
 72830 /changelog
  8458 /copyright
  5846 /control
  5754 diff
  2401 /rules
  1817 Debian
  1328 asc
  1284 postinst
   964 1
   723 prerm
   631 /NEWS
   442 faq
   419 /local/lxterm
   279 ctlseqs
   162 conf
   127 install
   125 /tests/control
   102 /watch
   101 docs
    58 /patches/series
    23 /clean
    12 /source/format
     3 /compat

What you see when running the script depends on what file-suffixes exist.  In this example, there are a couple of large ".html" files.


text:
Q: C - Code after switch in for loop ignored I have this bit of code in C:
for(int y = 1; y <= array_size; y++){          //outer loop starts here
    for(int x = 1; x <= array_size; x++){      //inner loop starts here

            switch(array[x][y]){
            case 1: dosomething;
            case 2: dosomething;
            case 3: dosomething;
            }

            makestuff;                        //this line is ignored
    }                                         //inner loop ends here
    outerloop;                                //outer loop - everything works fine
}                                             //outer loop ends here

and as you can see if I use switch, the code after it is just ignored despite it still being in the inner loop.
But if I rewrite the code like this:
for(int y = 1; y <= array_size; y++){          //outer loop starts here
    for(int x = 1; x <= array_size; x++){      //inner loop starts here

        if(array[x][y]==1)
            dosomething;
        else if(array[x][y]==2)
            dosomething;
        else if(array[x][y]==3)
            dosomething;

            makestuff;                        //works
    }                                         //inner loop ends here
    outerloop;                                //outer loop - everything works fine
}                                             //outer loop ends here

it works as I expected. It would not a problem if I used the second method but I would just like to know why the first method does not work.
Thank you for your answers.

A: I'm not sure about what are you doing and how did you tested, but this simple code works fine.
#include <stdio.h>
#define array_size 2
int main() {
    int array[array_size][array_size];
    for (int i = 0; i < array_size; i++) {
        for (int j = 0; j < array_size; j++) {
            array[i][j] = i;
        }
    }

    for (int y = 1; y <= array_size; y++) {
        for(int x = 1; x <= array_size; x++) {

            switch(array[x][y]) {
                case 1: printf("One\n"); break;
                case 2: printf("Two\n"); break;
                case 3: printf("Three\n"); break;
                default: printf("Nothing\n"); break;
            }

            printf("I'm not ignored\n");
        }
    }
    printf("END\n");
    return 0;
}

Output:
One
I'm not ignored
Nothing
I'm not ignored
Nothing
I'm not ignored
Nothing
I'm not ignored
END


text:
Q: Inconsistency in formula for shortest distance between two points on a sphere. I've found many formulas for the shortest distance between two points on a sphere, but all of them using coordinate geometry. I wanted a formula in terms of radius and angle subtended at the centre, since I feel those terms are much more intuitive. Heres my attempt to do so:
Consider points A and B on a sphere of radius $R$, subtending angle $\theta$ at the centre. A plane passing through these two points cuts the sphere in a circle of radius $r$. A and B subtend angle $\beta$ at the centre of this circle. Let $l$ be the length of the arc AB of the circle
Now, $\ d(A,B) = 2R \sin \frac \theta2 = 2r \sin \frac \beta2$
$\therefore l = r \beta = R\beta \frac {\sin \frac \theta2}{\sin \frac \beta2}$
For minima, $\frac {dl}{d\beta} = 0$
$\therefore  \frac {d}{d\beta} (\frac {\beta}{\sin \frac \beta2})= 0$
$\therefore \sin \frac \beta2 - (\frac \beta2) \cos \frac \beta2 = 0$
$\therefore \tan \frac \beta2 = \frac \beta2$
$\therefore \sin \frac \beta2 = \frac {\beta}{\sqrt {\beta ^2 + 4}}$
$\therefore l= \sqrt {\beta ^2 + 4} * R \sin \frac \theta2$
Now, to get the value of $\beta$, I know that for $\theta = \pi$, shortest distance is going to be $\pi R$
Substituting values of $l$ and $\theta$ in the final equation, I get $\beta \approx 2.42$
However, this value of $\beta$ is not consistent with my previous equation, $\tan \frac \beta2 = \frac \beta2$
Where did I go wrong?

A: I figured out what was wrong, and thought I'd just post the answer instead of deleting the question. Who knows, maybe it will help somebody else.
For the cut circle to actually be on the sphere, the limits ($\theta \leq\beta \leq \pi$)  need to be in place. However there were no such limits while calculating minima, and thus it gave the answer as $\beta=0$
In fact, after graphing $l$ against $\beta$ on a graphing calculator, I saw that the only minima is at $\beta=0$, and $l$ increases with increasing $\beta$ (for within the limits we are concerned with). Hence for $\theta \leq\beta \leq \pi$, the minima is at $\beta = \theta$ !

Therefore minimum $l=R\theta$


text:
Q: Python JIRA rest api - Filter changelog I can read JIRA issue's change log in python like below
changelog_response = requests.get(self.JIRA_URL + 'rest/api/2/search?jql=key=' + key_value + '&expand=changelog&fields=""',                                                                            auth=(self.JIRA_USERNAME, self.JIRA_PASSWORD))
json_issue_changelog = changelog_response.json()

I am running the above code in FOR loop to read change log details for all JIRA issues.
Objective: I am reading change log to fetch all sprint transition details of the issue. Let's say, if issue was not completed in the assigned sprint, then it got moved to next sprint. so, issue had two sprints assigned. Similarly I have to find out for all issues through the loop
I am interested only on sprint details, but, change log would give me all details. Is there a way to filter JIRA change log rest api to read only sprint details? I tried to find, but, it seems like filter is not supported for change log.
Because of I run change log for all issues, script takes hours of time to complete.
Total # of issues in project is 50000. Each issue has an average of 15-20 change log, but issue moved only between two or three sprint. so, 20 change log iteration (max) * 50k issues = 1 million . This iteration may get increased when more issues logged.
questions:

*

*How to filter JIRA change log rest api by Field = Sprint?

*If filter is not possible for change log, any other way to read sprint transition details directly? This has to be done only through JIRA rest api, not through any library

A: The only thing I've ever managed to do is to process the changelog from the newest to the oldest change and ignore changes older than a certain date. Otherwise you would need to create a new REST endpoint that selects the changeitems in the DB with a where clause to only retrieve the ones you want. Not an easy thing


text:
Q: Get multiple values out of checkboxes I searched a lot on the internet but I still can't find the right answer to my question. I am trying to "print" all the selected values out of multiple checkboxes on my html-page. However, this works only for integers and not for other values. Right now, I use to following code:

<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />

<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />

in combination with the following jquery code:
function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
    return +e.value;
});
$('span').text('the checked values are: ' + arr.join(','));
}

calculate();
$('div').delegate('input:checkbox', 'click', calculate);

The problem right now, is that I want to see all the values from the checkboxes, however, I do not want them to be integers, but they should have values like:

<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />

So that there will be an output like:
the selected values are: Teamsport,Ballsport,etc..
I think the problem should be in the Jquery code, but I am not very familiar with javascript and jquery, so I hope that someone can help me.

A: There is simply a typo in your code: this:
 return +e.value;

must be
 return e.value;

The prefix + is only defined for numbers, so javascript tries to convert the "Teamsport" into a number - which is NaN (not a number)

A: hier is an example may help you

$(':checkbox').change(function(){
    var liste2 = $(':checkbox:checked').map(function() {
    return this.value;
}).get();
   $('span').text('the checked values are: ' + liste2);
});

   <input type="checkbox" name="options[]" value="1" />
   <input type="checkbox" name="options[]" value="2" />

   <input type="checkbox" name="options[]" value="3" />
   <input type="checkbox" name="options[]" value="4" />
   <input type="checkbox" name="options[]" value="5" />

A: Just return the e.value in your map function.

function calculate() {
  var arr = $.map($('input[type="checkbox"]:checked'), function(e, i) {
    return e.value;
  });
  $('span').text('the checked values are: ' + arr.join(','));
  // console.log('the checked values are: ' + arr.join(','))
}

calculate();
$('div').on('click', 'input:checkbox', calculate);

  <input type="checkbox" name="options[]" value="Teamsport" />
  <input type="checkbox" name="options[]" value="Individual sport" />

A: The problem lies here: return +e.value;
+e.value will return NaN for non-number values, in this case, String will be converted to NaN

function calculate() {
  var arr = $.map($('input:checkbox:checked'), function(e, i) {
    return e.value; // +e.value will return NaN for String and non number values
  });
  $('span').text('the checked values are: ' + arr.join(','));
}

calculate();
$('div').delegate('input:checkbox', 'click', calculate);

  <input type="checkbox" name="options[]" value="abc" />
  <input type="checkbox" name="options[]" value="pqr" />

  <input type="checkbox" name="options[]" value="xyz" />
  <input type="checkbox" name="options[]" value="lmn" />
  <input type="checkbox" name="options[]" value="ccc" />

A:

function calculate() {
var arr =[];
$('input:checkbox:checked').each(function() {
    arr.push($(this).val());
});
$('span').text('the checked values are: ' + arr.join(','));
}

calculate();
$('div').delegate('input:checkbox', 'click', calculate);

<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />

<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />

<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />


text:
Q: Mysterious problem: Deleting massive amount of files doesn't free up disk space I have a disk that is 100% used, 400 GB of 400 GB, however I have moved more than 44 GB of files from it, but no extra space got available, the usage is still 400GB of 400GB.
Filesystem                        Size  Used Avail Use% Mounted on
/dev/mapper/system-root            49G  5.1G   41G  12% /
udev                               32G  192K   32G   1% /dev
tmpfs                              32G  148K   32G   1% /dev/shm
/dev/sda3                         158M   37M  114M  25% /boot
/dev/mapper/vg00-lv_hana_backups  500G  471G   30G  95% /backup
/dev/mapper/vg00-lv_B1H           200G   78G  123G  39% /hana/SAPBusinessOne
/dev/mapper/vg00-lv_hana_data     400G   19G  382G   5% /hana/data
/dev/mapper/vg00-lv_hana_log      400G  400G  280K 100% /hana/log
/dev/mapper/vg00-lv_hana_shared   200G   35G  166G  18% /hana/shared
/dev/mapper/vg00-lv_usr_sap       200G   45G  156G  23% /usr/sap
//10.1.1.201/HANABackups          1.9T  698G  1.2T  38%
/windbackup/HANABackup
comapny-sap:/hana/log # du -h
1.3G    ./mnt00001/hdb00001
794M    ./mnt00001/hdb00003
286G    ./mnt00001/hdb00004
288G    ./mnt00001
288G    .

As it can be seen from lsof, there are no files still being held open by processes>
lsof -n | grep '(deleted)'
nautilus    6184       root   31r      REG              253,0       752    1753275 /root/.local/share/gvfs-metadata/home (deleted)
nautilus    6184       root   32r      REG              253,0     32768    1753307 /root/.local/share/gvfs-metadata/home-bc638f00.log (deleted)
shutdown  111517       root    0u      CHR              136,0       0t0          3 /dev/pts/0 (deleted)
shutdown  111517       root    1u      CHR              136,0       0t0          3 /dev/pts/0 (deleted)
shutdown  111517       root    2u      CHR              136,0       0t0          3 /dev/pts/0 (deleted)

I have also tried copying 44 GB of files of that partition and than I could not copy any of the files from that 44 GB back, not even one 1 GB file?


text:
Q: Cannot add localnotification plugin to android phonegap app I tried this localnotificationplugin for adding local notification plugin and worked each step as in read me although I had some compilation errors but I resolved that by changing alarm = new AlarmHelper(this.ctx);in localnotification.java with new AlarmHelper(cordova.getContext()); here is my localnotification.js
    /*-
 * Phonegap LocalNotification Plugin for Android
 *
 * Created by Daniel van 't Oever 2012 MIT Licensed
 *
 * Usage:
 *
 * plugins.localNotification.add({ date: new Date(), message: 'This is an Android alarm using the statusbar', id: 123 });
 * plugins.localNotification.cancel(123);
 * plugins.localNotification.cancelAll();
 *
 * This interface is similar to the existing iOS LocalNotification plugin created by Greg Allen
 */
if (typeof PhoneGap !== "undefined") {

    /**
     * Empty constructor
     */
    var LocalNotification = function() {
    };

    /**
     * Register a notification message for a specific date / time
     *
     * @param successCB
     * @param failureCB
     * @param options
     *            Array with arguments. Valid arguments are date, message,
     *            repeatDaily and id
     */
    LocalNotification.prototype.add = function(options) {
        var defaults = {
            date : new Date(),
            message : '',
            ticker : '',
            repeatDaily : false,
            id : ""
        };

        if (options.date) {
            options.date = (options.date.getMonth()) + "/"
                    + (options.date.getDate()) + "/"
                    + (options.date.getFullYear()) + "/"
                    + (options.date.getHours()) + "/"
                    + (options.date.getMinutes());
        }

        for ( var key in defaults) {
            if (typeof options[key] !== "undefined")
                defaults[key] = options[key];
        }

        PhoneGap.exec(null, null, 'LocalNotification', 'add', new Array(
                defaults));
    };

    /**
     * Cancel an existing notification using its original ID.
     *
     * @param id
     *            The ID that was used when creating the notification using the
     *            'add' method.
     */
    LocalNotification.prototype.cancel = function(notificationId) {
        PhoneGap.exec(null, null, 'LocalNotification', 'cancel', new Array({
            id : notificationId
        }));
    };

    /**
     * Cancel all notifications that were created by your application.
     */
    LocalNotification.prototype.cancelAll = function() {
        PhoneGap
                .exec(null, null, 'LocalNotification', 'cancelAll', new Array());
    };

    /**
     * Register this plugin with phonegap
     */
    PhoneGap.addConstructor(function() {
        alert("constructor called here");
        if (!window.plugins) {
            window.plugins = {};
        }
        window.plugins.localNotification = new LocalNotification();
        alert("localnotification called");
    });
}

It calls to phonegap constructor and  alert("localnotification called"); is shown but after that add is not executed thus, I Cannot get localnotification to run

A: Where are you testing it (device or emulator)? You know that the localnotification don't popup a window, don't you?
Is there any error in the Log?


text:
Q: Vector space over local field Let $L/K$ be an extension of number field and $\frak p$ a place of $K$ and $\frak P$ aplace of $L$ above.
My question: $L$ can be considered as a vector space over $K_\frak p?$
thanks !

A: No, $L$ cannot be considered as a vector space over $K_\mathfrak{p}$, at least not in a way compatible with the $K$-vector space structure on $L$ and $K_\mathfrak{p}$; $L$ is finite-dimensional over $K$ but $K_\mathfrak{p}$ is infinite-dimensional over $K$. Do you mean to ask about $L_\mathfrak{P}$ instead of $L$? In that case the answer is ``yes." The universal property of the completion $K_\mathfrak{p}$ implies that there is a unique continuous ring map $K_\mathfrak{p}\hookrightarrow L_\mathfrak{P}$ compatible with $K\subseteq L$. Via this map, $L_\mathfrak{P}$ becomes a finite extension of $K_\mathfrak{p}$, and in particular a $K_\mathfrak{p}$-vector space.

A: $L$ is an extension of $K$ (extension of number fields).
$L_\mathfrak{P}$ is an extension of $K_\mathfrak{p}$ (extension of local fields).
$\overline{L_\mathfrak{P}} := \mathcal{O}_L / \mathfrak{P}$ is an extension of $\overline{K_\mathfrak{p}} := \mathcal{O}_K / \mathfrak{p}$ (extension of finite fields).
Finally, $L_\mathfrak{P}$ is an extension of $L$ and $K_\mathfrak{p}$ is an extension of $K$ (completions).  This gives you just one "non-obvious" extension: $L_\mathfrak{P}$ is an extension of $K$.
It's instructive to consider the case $L=K=\mathbb{Q}$.  Then you have the fields $\mathbb{Q}$, $\mathbb{Q}_p$, and $\mathbb{F}_p$, and your question, as written, asks if $\mathbb{Q}$ is a vector space over $\mathbb{Q}_p$.  There is certainly no way to make sense of this, as the former is countable and the latter is uncountable.


text:
Q: "Watching PewDiePie videos" or "Watching PewDiePie's videos"? I saw both forms where the nickname of an user is used as an adjective, but which one(s) are idiomatic and why?

A: Both are idiomatic and essentially mean the same thing, although the name "PewDiePie" is being used differently in each.
"PewDiePie's videos" means the videos belonging to PewDiePie. The videos are his work, he created them, so it is correct to refer to them this way.
However, a noun can also be an attribute of something. When it is used this way it is called an attributive noun and acts very much like an adjective. You are differentiating the videos from other videos by attributing the artist's name to them.
For example:

Did you hear Coldplay's new single?
Did you hear the new Coldplay single?

Both of these are also idiomatic.
Also consider:

This is a can of Coke.
  This is a Coke can.
This is a video of PewDiePie.
  This is a PewDiePie video.

When something is a brand name it can also be used as part of the product name. "PewDiePie" is a brand name of sorts, not because it isn't the star's real name, but because it is a name under which he has become famous.

A: There is a subtle difference in meaning.
"PewDiePie's videos" has more of an implication of "all of them". When you use the
"X's Y" construction, the meaning is definite: it is usually equivalent to "the Y of X" (in this case, "the videos of PewDiePie", although that wouldn't be an idiomatic way of putting it). Because "watching" is a progressive form, "I am watching PewDiePie's videos" doesn't necessarily imply that you have gotten through all of them, but it might imply that you plan to eventually watch all of them.
In contrast, "PewDiePie videos" is indefinite, and would imply "some of PewDiePie's videos". I find this to be the more idiomatic choice.


text:
Q: clearing a small integer array: memset vs. for loop There are two ways to zero out an integer/float array:
memset(array, 0, sizeof(int)*arraysize);

or:
for (int i=0; i <arraysize; ++i)
    array[i]=0;

obviously, memset is faster for large arraysize. However, at what point is the overhead of memset actually larger than the overhead of the for loop? For example, for an array of size 5 - which would be best? The first, the 2nd, or maybe even the un-rolled version:
array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;
array[4] = 0;

A: There's no way of answering the question without measuring. It will depend entirely on the compiler, cpu and runtime library implementations.
memset() can be bit of a "code smell", because it can be prone to buffer overflows, parameter reversals and has the unfortunate ability of only clearing 'byte-wise'. However it's a safe bet that it will be 'fastest' in all but extreme cases.
I tend to use a macro to wrap this to avoid some of the issues:
#define CLEAR(s) memset(&(s), 0, sizeof(s))

This sidesteps the size calculations and removes the problem of swapping the length and vlaue parameters.
In short, use memset() "under the hood". Write what you intend, and let the compiler worry about optimizations. Most are incredibly good at it.

A: In all likelihood, memset() will be inlined by your compiler (most compilers treat it as an 'intrinsic', which basically means it's inlined, except maybe at the lowest optimizations or unless explicitly disabled).
For example, here are some release notes from GCC 4.3:

Code generation of block move
  (memcpy) and block set (memset)
  was rewritten. GCC can now pick the
  best algorithm (loop, unrolled loop,
  instruction with rep prefix or a
  library call) based on the size of the
  block being copied and the CPU being
  optimized for. A new option
  -minline-stringops-dynamically has
  been added. With this option string
  operations of unknown size are
  expanded such that small blocks are
  copied by in-line code, while for
  large blocks a library call is used.
  This results in faster code than
  -minline-all-stringops when the
  library implementation is capable of
  using cache hierarchy hints. The
  heuristic choosing the particular
  algorithm can be overwritten via
  -mstringop-strategy. Newly also
  memset of values different from 0 is
  inlined.

It might be possible for the compiler to do something similar with the alternative examples you gave, but I'd bet it's less likely to.
And it's grep-able and more immediately obvious at a glance what the intent is to boot (not that the loop is particularly difficult to grok either).

A: As Michael already noted, gcc and I guess most other compilers optimize this already very well. For example gcc turns this
char arr[5];
memset(arr, 0, sizeof arr);

into
movl  $0x0, <arr+0x0>
movb  $0x0, <arr+0x4>

It doesn't get any better than that...

A: Considering this code per se evrything is already been told. But if you consider it in its program, of which I don't know nothing, something else can be done. For example, if this code is to be executed every some time to clear an array, you could run a thread that constantly allocates a new array of zero elements assigned to a global variable, which your code, when needs the array to be cleared, simply points to.
This is a third option. Of course if you plan to run your code on a processor with at least two cores and this makes sense. Also the code must be run more than once to see the benefits. For only a one-time run, you could declare an array filled with zeros and then point to it when needed.
Hope this may help someone


text:
Q: What does >> and 0xfffffff8 mean? I was told that (i >> 3) is faster than (i/8) but I can't find any information on what >> is.  Can anyone point me to a link that explains it?
The same person told me "int k = i/8, followed by k*8 is better accomplished by (i&0xfffffff8);" but again Google didn't help m...
Thanks for any links!

A: Bitwise shift right.
i >> 3 moves the i integer 3 places to the right [binary-way] - aka, divide by 2^3.

A: int x = i / 8 * 8:
1) i / 8, can be replaced with i >> 3 - bitwise shift to the right on to 3 digits (8 = 2^3)
2) i & xfffffff8 comparison with mask
For example you have:
i = 11111111
k (i/8) would be: 00011111
x (k * 8) would be: 11111000

Therefore the operation just resets last 3 bits:
And comparable time cost multiplication and division operation can be rewritten simple with
i & xfffffff8 - comparison with (... 11111000 mask)

A: As explained here the >> operator is simply a bitwise shift of the bits of i. So shifting i 1 bit to the right results in an integer-division by 2 and shifting by 3 bits results in a division by 2^3=8.
But nowadays this optimization for division by a power of two should not really be done anymore, as compilers should be smart enough to do this themselves.
Similarly a bitwise AND with 0xFFFFFFF8 (1...1000, last 3 bits 0) is equal to rounding down i to the nearest multiple of 8 (like (i/8)*8 does), as it will zero the last 3 bits of i.

A: Regarding the first half:
>> is a bit-wise shift to the right.
So shifting a numeric value 3 bits to the right is the same as dividing by 8 and inting the result.
Here's a good reference for operators and their precedence: http://web.cs.mun.ca/~michael/c/op.html
The second part of your question involves the & operator, which is a bit-wise AND. The example is ANDing i and a number that leaves all bits set except for the 3 least significant ones. That is essentially the same thing happening when you have a number, divide it by 8, store the result as an integer, then multiply that result by 8.
The reason this is so is that dividing by 8 and storing as an integer is the same as bit-shifting to the right 3 places, and multiplying by 8 and storing the result in an int is the same as bit-shifting to the left 3 places.
So, if you're multiplying or dividing by a power of 2, such as 8, and you're going to accept the truncating of bits that happens when you store that result in an int, bit-shifting is faster, operationally. This is because the processor can skip the multiply/divide algorithm and just go straight to shifting bits, which involves few steps.

A: They are Bitwise Operations

A: The >> operator is the bit shift operator.  It takes the bit represented by the value and shifts them over a set number of slots to the right.

A: Bitwise shifting.
Suppose I have an 8 -bit integer, in binary

01000000

If I left shift (>> operator) 1 the result is

00100000

If I then right shift (<< operator) 1, I clearly get back to wear I started

01000000

It turns out that because the first binary integer is equivelant to

0*2^7 + 1*2^6 + 0*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 0*2^1 + 0*2^0

or simply 2^6 or 64
When we right shift 1 we get the following

0*2^7 + 0*2^6 + 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 0*2^1 + 0*2^0

or simply 2^5 or 32
Which means
i >> 1

is the same as
i / 2

If we shift once more (i >> 2), we effectively divide by 2 once again and get
i / 2 / 2

Which is really
i / 4

Not quite a mathematical proof, but you can see the following holds true
i >> n == i / (2^n)

A: >> is right shift operation.
If you have a number 8, which is represented in binary as 00001000, shifting bits to the right by 3 positions will give you 00000001, which is decimal 1. This is equivalent to dividing by 2 three times.
Division and multiplication by the same number means that you set some bits at the right to zero. The same can be done if you apply a mask. Say, 0xF8 is 11111000 bitwise and if you AND it to a number, it will set its last three bits to zero, and other bits will be left as they are. E.g., 10 & 0xF8 would be 00001010 & 11111000, which equals 00001000, or 8 in decimal.
Of course if you use 32-bit variables, you should have a mask fitting this size, so it will have all the bits set to 1, except for the three bits at the right, giving you your number - 0xFFffFFf8.

A: Your shifting the bits in binary so for example:
1000 == 8
0100 == 4 (>> 1)
0010 == 2 (>> 2)
0001 == 1 (>> 3)
Being as you're using a base two system, you can take advantage with certain divisors (integers only!) and just bit-shift. On top of that, I believe most compilers know this and will do this for you.
As for the second part:
(i&0xfffffff8);
Say i = 16
0x00000010 & 0xfffffff8 == 16
(16 / 8) * 8 == 16
Again taking advantage of logical operators on binary. Investigate how logical operators work on binary a bit more for really clear understanding of what is going on at the bit level (and how to read hex).

A: That's called bit shifting, it's an operation on bits, for example, if you have a number on a binary base, let's say 8, it will be 1000, so
x = 1000;
y = x >> 1; //y = 100 = 4
z = x >> 3; //z = 1

A: >> shifts the number to the right. Consider a binary number 0001000 which represents 8 in the decimal notation. Shifting it 3 bits to the right would give 0000001 which is the number 1 in decimal notation. Thus you see that every 1 bit shift to the right is in fact a division by 2. Note here that the operator truncates the float part of the result.
Therefore i >> n implies i/2^n.
This might be fast depending on the implementation of the compiler. But it generally takes place right in the registers and therefore is very fast as compared to traditional divide and multiply.
The answer to the second part is contained in the first one itself. Since division also truncates all the float part of the result, the division by 8 will in theory shift your number 3 bits to the right, thereby losing all the information about the rightmost 3 bits. Now when you again multiply it by 8 (which in theory means shifting left by 3 bits), you are padding the righmost 3 bits by zero after shifting the result left by 3 bits. Therefore, the complete operation can be considered as one "&" operation with 0xfffffff8 which means that the number has all bits 1 except the rightmost 4 bits which are 1000.


text:
Q: create multiple folders in python automatically I want to create a path like C:\sample\sample1\hello.py.  It should automatically create the complete path from sample to hello.py, and all the directories in between.  Is this possible in Python?

A: The following functions may help:

*

*os.makedirs

*os.path.dirname

*os.path.basename

A: import os
root_path = 'C:\path'

folders = ['folder 01', 'folder 02', 'folder 03']

for folder in folders:

    os.mkdir(os.path.join(root_path, folder))


text:
Q: Ruby on Rails: Sum table column row values based on other column data I have a table with columns 'id', 'resource_id', 'read_time', 'value' where 'value' is a float
What I am trying to accomplish is to return a list of records such that the 'value' of each record is the sum of all the records at a specific 'read_time' but having differing 'resource_id' values.
I am wondering if there is a clever way (ie not looping through all the entries) to accomplish this. Currently I am implementing something along these lines:
@aggregate_meters = []
@res_one_meters = Meter.find(:all, :conditions => ["resource_id = ?", 1])

@res_one_meters.each do |meter|
  read_time = meter.read_time
  value = meter.value
  if res_two_meter = Meter.find(:first, :conditions => ["resource_id = ? AND read_time = ?", 2, read_time ])
    value = value + res_two_meter.value
  end
  aggregate_meter = Meter.new(:read_time => read_time, :value => value, :resource_id => 3)
  @aggregate_meters.push(aggregate_meter)
end

Thank you.

A: ActiveRecord::Calculate is your friend here. Letting you do exactly what you want with one database call. It returns a hash using the unique values in the column used in the group as keys.
Here's the code you wrote, rewritten to use sum.
values = Meter.sum(:value, :group => :read_time)

values.each do |read_time, value|
  aggregate_meter = Meter.new(:read_time => read_time, :value => value, :resource_id => 3)
  @aggregates_meter.push(aggregate_meter)
end


text:
Q: python : How to add different markers to different Y values I'm trying to visualize data where each X value has multiple Y values and I would like to distinguish each Y value visaully. This is the example code
xLables = ['A1','A2','A3','A4','A5']

YValues = [[1,2,3,4],[1,2,3,4,5,6,7],[1,2,3],[5,6,7],[1,2,3]]
X = [xLables[i] for i, data in enumerate(YValues) for j in range(len(data))]
Y = [val for data in YValues for val in data]

plt.scatter(X, Y)
plt.grid()
plt.show()

When I plot this , I get the following attached

Each X label has corresponding Y values ... For Ex: A1 has 1,2,3,4 , A2 has 1,2,3,4,5,6,7 and so on
I have two questions on this one
(1) Can I have different markers for different Y-values .. all 1's are stars , all 2's are diamonds , all 10's are circles ?
something like this may be

(2) Is there a better way to plot such 2D data and distingush them where each X has multiple Y values
Any suggestions/help is highly appreciated
Thanks
I tried to add markers and different colors , but they apply to all Y values for each X .. but not specific to each Y values..

A:
My solution is particularly ad hoc, but it replicates your target drawing using your data, so that I feel confident posting her here.
import matplotlib.pyplot as plt

labels = ['A1','A2','A3','A4','A5']
Y2D = [[1,2,3,4],[1,2,3,4,5,6,7],[1,2,3],[5,6,7],[1,2,3]]

# prepare a dictionary with the characteristics
# we want to change according to the Y value
d = {1:dict(marker="*", s=150, color="red"),
     2:dict(marker="o", s=100, color="yellow"),
     3:dict(marker="o", s= 60, color="blue"),
     4:dict(marker="o", s=100, color="green"),
     5:dict(marker="o", s=100, color="red"),
     6:dict(marker="*", s=150, color="blue"),
     7:dict(marker="o", s=100, color="lightgray")}
# an outer loop on the abscissae and the lists of Y values
for x, ys in zip(labels, Y2D):
    an inner loop on the Y values, plotted separately
    for y in ys:
        # here the point is to unpack the values contained
        # in the "inner" dictionary, addressing the outer by Y
        # zorder=5 places the dots above the grid
        plt.scatter(x, y, ec='k', zorder=5, **d[y])
plt.grid(1)
plt.show()

A: Add your marker types to list & iterate over them accordingly.
from matplotlib import pyplot as plt
import matplotlib

xLables = ['A1','A2','A3','A4','A5']

YValues = [[1,2,3,4],[1,2,3,4,5,6,7],[1,2,3],[5,6,7],[1,2,3]]
X = [xLables[i] for i, data in enumerate(YValues) for j in range(len(data))]
Y = [val for data in YValues for val in data]

plt.scatter(X, Y, marker=matplotlib.markers.CARETDOWNBASE)
plt.grid()

markers=['8','+', '.', 'o', '*','^', 's', 'p', 'h','8','+', '.', 'o', '*','^', 's', 'p', 'h' ]
for i in range(18):
    plt.plot(X[i], Y[i],  marker=markers[i])
    plt.xlabel('X Label')
    plt.ylabel('Y Label')
plt.show()

Output:

Note: change the order you want accordingly you want. That will be replicated over graphs

A: I think the easiest way is to use one plt.scatter() per score.
import matplotlib.pyplot as plt
xLables = [ 'A1','A2','A3','A4','A5']
YValues = [ [1,2,3,4],[1,2,3,4,5,6,7],[1,2,3],[5,6,7],[1,2,3]]
markers = [ '.', 'o', '^', 'v', '>', '<', '*'] # to be customized
Y = [None for i in range( len( xLables))]

for y in range( len( markers)):
  for x in range( len( xLables)):
    Y[x] = y+1 if y+1 in YValues[x] else None # values start at 1
  if any( Y):  # something to display?
    plt.scatter( xLables, Y, marker=markers[y])
plt.grid()
plt.show()

A: You can add markers.
A list of them can be found here: https://matplotlib.org/stable/api/markers_api.html
I think you can use it like this:
plt.scatter([1, 2, 3], marker=11) which means that you'll have to put the values you want to be the same in the same list. I don't think there is a way of giving a list of markers or something like that.
As far as i understand your code would look something like:
plt.scatter(X, Y[0], marker=1)
plt.scatter(X, Y[1], marker=1)
plt.scatter(X, Y[2], marker=1)
plt.scatter(X, Y[3], marker=1)

You could make this a for loop if it is something having to work for different sizes but i suppose you'll figure it out from here.
Good luck i hope this helps.


text:
Q: How to redirect url for CreateView in views.py
*

*class A_modelCreateView(CreateView)in views.py

*path('create/'),view.A_modelCreateView().as_view(),name='create' in urls.py

*build an HTML as form for A_model form but not in its default directory(my_app/A_model.form)

Is there filled parameter somewhere for redirect the url you want?

A: Yes, a CreateView has as one of its baseclasses a the FormMixin. This FormMixin class has a success_url attribute [Django-doc].
You can add a real url, or work with reverse_lazy [Django-doc] to calculate the URL based on the name of a view. For example:
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView

class A_modelCreateView(CreateView):
    success_url = reverse_lazy('overview_page')
    # ...
where overview_page is here the name of a hypothetical view.
If you do not specify a success_url in a CreateView or UpdateView, it will take the get_absolute_url of the model object that is created/updated, if the model has such method. For more information, see the Django documentation.