text:
Q: Ellipsis overflow not working as intended with flexbox item I have this setup:
.flex-container {
    margin: auto;
    display: flex;
    flex-direction: row;
    width: 75vw;
    justify-content: center;
    align-items: flex-start;
}

and then three sections (left navbar, middle content, right infobar) with flex 1, 8, 1 respectively.
Inside the infobar on the right, I want to overflow ellipsis on the username, this is the css for that section:
.main-infobar {
    flex: 1;
    position: sticky;
    top: 0;
}
.main-infobar__items {
    display: flex;
    flex-direction: column;
}
.main-infobar__items__item {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Reading on SO, I found I needed to either put min-width: 0 or overflow: hidden on the flex item, its parent, or perhaps its parent's parent as it's a flex item in a flex item in a flexbox. No combination of this solution worked and so I'm at a loss.
What is currently happening is that if something within an .main-infobar__items__item is too long, it stretches the whole column. I want it to remain at its initial size and ... the overflow. Any help is appreciated.

.flex-container {
  margin: auto;
  display: flex;
  flex-direction: row;
  width: 75vw;
  justify-content: center;
  align-items: flex-start;
}

.main-infobar {
  flex: 1;
  position: sticky;
  top: 0;
}

.main-infobar__items {
  display: flex;
  flex-direction: column;
}

.main-infobar__items__item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

        item1

        item2

        etc

        logged in as

        14 messages

        8 notifications

        8 notifications extra long thing test


text:
Q: Using Xcode for generic C/C++ development I'd like to use all the power of Xcode for generic C/C++ projects but I can't figure out what are the basic steps to configure a new Xcode project and attach it to an existing source tree of a legacy, plain, C/C++ project.
Creating a new empty project, attaching it to a source tree and configuring a build target (using GNU Make) was a really silly task.
I can't figure out how to enable source code indexing in order to enable source refactoring tools, searching and fast-jumping and all the amenities that makes the Xcode programmer's life great.
Moreover I'd like to use the internal debugging facilities…
Does anyone point me to a tutorial, a hint or whatever could be useful?
Thanx

A: I've found a (dirty) path to enable refactoring tools:
I've added a new standard «console target» to the project and added all the source files under the Build Phases > Compiled Sources.
Refactoring tools now works. Having two targets doesn't seem to be a relevant issue (elegance apart)

A: Personally, I wouldn't attempt to use legacy Makefiles, even though I think there's some support for that.
Typically what I do with a traditional C/C++ project is to store my XCode project folder at the root of the project. So it might look like:
--myApp
  --src
  --inc
  --myApp Xcode

I then drag the src folder and inc folder into the project navigator. This gives me an Xcode project to compile with on the Mac, and then I have the traditional Makefile for compiling on Linux (actually, I prefer CMake for other platforms, but either way works).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I produce instruction reordering in jcstress test When I am suspicious certain instruction reordering is allowed by the java language specification, I want to reproduce it in a jcstress test. How can I do that? For example, in the following code, the Load and Store instructions (I believe) are allowed to be reordered in execution in some runtime environment. However, when I run the jcstress in Intel x84_64 Ubuntu, the result does not show any reordering happened.
import org.openjdk.jcstress.annotations.*;
import org.openjdk.jcstress.infra.results.I_Result;

@JCStressTest
@Outcome(id = "0", expect = Expect.ACCEPTABLE,
         desc = "Default outcome.")
@Outcome(id = "2", expect = Expect.ACCEPTABLE_INTERESTING,
         desc = "Load-Store reordering happens.")
@State
public class ReorderingTest {

    int d;
    int e;
    int f;

    @Actor
    public void actor1() {
        int ee = e;     // Load
        d = 1;          // Store

        if (ee == 2) {
            f = 2;
        }
    }

    @Actor
    public void actor2() {
        if (d == 1) {
            e = 2;
        }
    }

    @Arbiter
    public void arbiter(I_Result r) {
        r.r1 = f;
    }
}

A: I finally managed to observe the reordering in the original jcstress test with explicit JVM options and running it with more hours of time.
java -jar target/jcstress.jar -f 20 -XX:-TieredCompilation, -XX:+UnlockDiagnosticVMOptions, -XX:+StressLCM, -XX:+StressGCM
However, in one of the following tests, reordering is never observed no matter how long I run the testing, although it looks equivalent to other tests.
// reordering can be observed!
@Actor
    public void actor1() {
        int ee = e;     // Load
        d = 1;          // Store

        if (ee == 2) {
            f = 2;
        }
    }

// reordering can be observed!
@Actor
    public void actor1() {
        f = e;          // Load & Store
        d = 1;          // Store
    }

// reordering NEVER observed!
@Actor
    public void actor1() {
        if (e == 2) f = 2;     // Load & conditionally Store
        d = 1;          // Store
    }


text:
Q: Unable to display map using mapbox with pug enter image description here
As the title and picture shown above, I am having issues to display the map on my website. I looked around for solutions but none is similar to mine. One thing to note is I am using pug (template to write JS in HTML). Here is the code for the JS shown below

/* eslint-disable */
const locations = JSON.parse(document.getElementById("map").dataset.locations);

mapboxgl.accessToken = 'xxxxxx';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'xxxxxxx',
    center: [-118.315192, 34.006905],
    zoom: 10
});

Here is the code I am using to implement the top code to display the map on my website.

    section.section-map
        //- Data-location set in dataset in mapbox.js
        #map(data-locations=`${JSON.stringify(tours.locations)}`)

Here is my main content

doctype html
html
    head
        block head
            meta(charset='UTF-8')
            meta(name='viewport' content='width=device-width, initial-scale=1.0' value="script-src 'self' api.mapbox.com;")
            title Natours | #{tours.name} Tour
            link(rel='stylesheet' href='/css/style.css')
            link(rel='shortcut icon' type='image/png' href='/img/favicon.png')
            link(rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato:300,300i,700')

    body
        // HEADER

        include _header

        // CONTENT

        block content
            h1 This is a placeholder heading

        // FOOTER

        include _footer
            script(src="/js/mapbox.js")

A: it looks like there is problem with your content security policy set on header..
add following code inside meta tag.
script-src 'self' api.mapbox.com;

for more info Read Content Security Policy
because OP using third party npm module helmet ...
for now you can disable the CSP in helmet as following..
app.use(
  helmet({
    contentSecurityPolicy: false,
  })
);

for more read docs Helmet Docs

A: You have a content security policy Header is missing just put this meta tag in the header it works for me
<meta http-equiv="Content-Security-Policy" content="script-src 'self' api.mapbox.com;worker-src blob: ;connect-src https://*.tiles.mapbox.com https://api.mapbox.com https://events.mapbox.com">


text:
Q: MS Office 2013 - App Crash after a few minutes When I try to run MS Office ProPlus 2013 on Windows Server 2012 R2 Datacenter, I get the below error messageafter a few minutes of the app running, but with powerpnt.exe or excel.exe or winword.exe. I tried rebooting, starting in safe mode, and sfc /fix, but nothing works. I tried to reinstall, and I got the below message after a few minutes. I would like help to fix this problem.
Source
Microsoft Office

Summary
Stopped working

Date
2015-02-14 4:16 PM

Status
Not reported

Description
Faulting Application Path:  C:\Program Files\Microsoft Office 15\root\office15\FIRSTRUN.EXE

Problem signature
Problem Event Name: BEX
Application Name:   firstrun.exe
Application Version:    15.0.4693.1000
Application Timestamp:  54b5d24d
Fault Module Name:  StackHash_cdb8
Fault Module Version:   0.0.0.0
Fault Module Timestamp: 00000000
Exception Offset:   PCH_2A_FROM_AppVIsvSubsystems32+0x0005ABEB
Exception Code: c0000005
Exception Data: 00000008
OS Version: 6.3.9600.2.0.0.400.8
Locale ID:  4105
Additional Information 1:   cdb8
Additional Information 2:   cdb81aa23bde0ee5f99eaa851c2afbd5
Additional Information 3:   7c9d
Additional Information 4:   7c9dd1c70fe6b2a0efb049136e4da130


text:
Q: Limit definition of the osculating circle Let $I$ be an interval and $c:I \to \mathbb{R}^2$ a smooth curve with $c' \neq 0$ everywhere. I am currently trying to figure out how to define the osculating circle at a point $c(t_0)$, $t_0 \in I$, without assuming that the curvature has previously been defined (which could for example be done via the Frenet frame).
One way to define it might be the following way using a limit: Assume that locally around the point $c(t_0)$ the curve is not a straight line. Consider a value $h>0$ with $t_0 \pm h \in I$ such that the three points $c(t_0-h)$, $c(t_0)$ and $c(t_0+h)$ are not located on a straight line. Let $M(t_0,h)$ be the center of the circle defined by those three points. The osculating circle at $c(t_0)$ might then be defined as being the circle with center $M$ and radius $r$ where these values are given by
$$M:=\lim_{h \to 0} M(t_0,h)\phantom{aaa}\text{and}\phantom{aaa}r:=\Vert M-c(t_0) \Vert$$
The limit runs only over those values of $h$ for which the three points $c(t_0-h)$, $c(t_0)$ and $c(t_0+h)$ are not located on a straight line. (This is not really a restriction. Since $c$ is not a straight line around $c(t_0)$, just choose $h$ small enough.)
My question: How to show that the limit from the above definition exists? Or is there something wrong with the definition?
Some background: A similar definition for the osculating circle is indicated in the book "Modern Differential Geometry of Curves and Surfaces with Mathematica" by Gray et al. in section 4.4. However, they do not explain why the limit should exist or least I do not understand this.
Addendum: Finally, I learned that there must be a "mistake" in the definition. Since this is not mentioned in any of the answers, I decided to explain it here: The condition that $c$ is not a straight line locally around $c(t_0)$ is not sufficient for the osculating circle to exist. Under this condition, it may still happen that for every sufficiently small $h>0$, you can find a straight line through the points $c(t_0-h)$, $c(t_0)$ and $c(t_0+h)$. Take for example $c(t)=(t,t^3)$, $-1/2 < t < 1/2$ and $t_0=0$. Therefore: No osculating circle at $c(t_0)$ in that case. The points $M(t_0,h)$ are not well-defined because they don't exist. So, currently I am wondering what the "correct" condition on $c$ might be guaranteeing that the points $M(t_0,h)$ exist for sufficiently small $h$...

A: HINTS: Without loss of generality, assume $c$ is arclength-parametrized, $t_0=0$, $c(0)=0$, and $c'(0)=(1,0)$.
Take the equation of the circle through $c(-h), 0, c(h)$ to be $f_h(x,y)=(x-a_h)^2 + (y-b_h)^2 - (a_h^2+b_h^2) = 0$. Let $g_h(t) = f_h(c(t))$. Apply Rolle's Theorem a few times to get $-h<\theta_h<0<\tau_h<h$ with $g'_h(\theta_h)=g'_h(\tau_h)=0$, and again to get $\xi_h$ with $g''_h(\xi_h)=0$. You should be able to argue now that $g(t)=\lim\limits_{h\to 0^+} g_h(t)$ exists and $g(0)=g'(0)=g''(0)=0$. This will give you what you want. (You can use a Taylor expansion of $c(t)$ or give an implicit function theorem argument that $(a_h,b_h)$ is a smooth function of $h$.)

A: Responding to the addendum:
A test for collinearity of the three distinct points $(x_1,y_1)$, $(x_2, y_2)$, and $(x_3, y_3)$ uses determinants.  These three distinct points are collinear if and only if
$$  \begin{vmatrix} x_1 & y_1 & 1 \\
x_2 & y_2 & 1 \\
x_3 & y_3 & 1
\end{vmatrix} = 0  \text{.}  $$
You may also be hoping for too much with symmetric choices in the parameter space.  You may be happier using $c(t_0 + k)$, $c(t_0)$, and $c(t_0 + h)$ in the limit as $h \rightarrow 0$ and $k \rightarrow 0$, independently.  This won't solve the problem you found with the map $t \mapsto (t, t^3)$, where the "$y$ as a function of $x$" graph has an inflection point at $x = 0$, since (finite radius) circles do not approximate the graph of $y = x^3$ at its inflection point.

A: The equation of a circle is $x^2+y^2-ax-by-c=0$ say $F(x,y ; a,b,c)=0$ $1/2(a,b)$ is the center $a^2+b^2+c$ the square of the radius.
So the circle through 3 points is obtained by solving a $(3,3)$ linear system (the unknown are $a,b,c$) with coefficient which are polynomial in the coordinates if these point, so that this circle (the parameter $(a,b,c)$ is unique and continuously  depends on the three point. Of course, one must be careful and check that the determinant is $\not 0$, which means that the three points are not one the same line.
Here, one can argue further and make the computation in the Frenet frame, so that the equation of the circle through $M(-s), M(s), 0$ are
$c=0$
$x^2(s)+y^2(s)-ax(s)-by(s)=0$
$x^2(-s)+y^2(-s)-ax(-s)-by(-s)=0$
But $(x(s),y(s))= s(1,0)+ {s^2\over 2 R}(0,1)+o(s^2)$ (Frenet)
so the system is :
$a( s+o(s))+b( {s^2\over 2 R}+o(s^2))= s^2+o(s^2)$
$a( -s+o(s))+b( {s^2\over 2 R}+o(s^2))= s^2+o(s^2)$
And a simple computation yields $a=o(s^2), b=R+o(s)$


text:
Q: How can I add an 'and' within if/else in javascript I have a few if/else statements which i want to do more than just change the price like they do now. The price's are variables so they change upon different actions on the page.
Now i want the if else statement to work like this:
If (hasclass unselected AND x = 500, do something.
Else, do something else
If 2 options hasclass selected, do something else entirely.
$('div.unselected-option').click(function(){
     $(this).toggleClass('unselected-option selected-option');

     if ($('div.dc-option1').hasClass("unselected-option")){
         price = price1;
     }

     else {
         price = price1 + price2;
     }

     if ($('div.dc-option2').hasClass("unselected-option")){
         price = price;
     }

     if ($('div.dc-option2').hasClass("selected-option")){
         price = price + price3;
     }

     if ($('div.dc-option3').hasClass("unselected-option")){
         price = price;
     }

     if ($('div.dc-option3').hasClass("selected-option")){
         price = price + price4;
     }

    document.getElementsByClassName("dc-price")[0].innerHTML = '€' + price + ',-';

});

A: This is what you want?
if ($('div.dc-option1').hasClass("unselected-option") && (x==500))


text:
Q: How to efficiently validate multiple datatypes in python? I am facing as issue where I want to validate the data types of every column in my table, but there are a lot of different columns and a lot of different tables.
Here is the code I have for my data validations so far:
import pandas as pd
import datatest as dt
import datetime

dt.register_accessors()

filename = r"file_data.parquet"

def read_file():
    df = pd.read_parquet(filename)
    if(df.empty):
        print ('Parquet file is empty')
    else:
        print ('Parquet file is not empty')
        return df
read_file()

def interate_datatypes():
    df = pd.read_parquet(filename)
    for dtype in df.dtypes.items():
        print(dtype)
interate_datatypes()

def validate_data():
    df = pd.read_parquet(filename)
    df['id'].validate(int)
    df['code'].validate(str)
    df['date'].validate(datetime)
    .
    .
    .
    df['last_column'].validate(str)

validate_data()

So def read_file() checks to see if the df is empty or not, def interate_datatypes() iterates through each column in the table of the current file I am reading and lists out the data types of each one, and def validate_data() is where the data for each column is validated to ensure the records are the correct datatypes. I'm not sure if this is the best way to validate the data because I have to list out every column individually and write out the validations like I did above. I want to validate 20 other tables I have as well and I can't think of a better way to:
1.) Read all the 20 parquet files at once instead of doing this one by one.
2.) Validate each table's columns in a more concise manner?


text:
Q: How to print text and variables in a single line Is there a way to print text and variables in a single line in r
eg
a="Hello"
b="EKA"
c="123456"

print("$a !! my name is $b and my number is $c")

out put will be like this
Hello !! my name is EKA and my number is 123456

A: I'd suggest using sprintf function. The advantage of this function is, that the variables can be of any class (here, c is numeric).
a="Hello"
b="EKA"
c=123456

sprintf("%s !! my name is %s and my number is %i", a, b, c)

A: print( paste("You have choosen the following file name: ", fileName))

will do the job

A: I like to do this: print(c('x=',x))
The output format is messy but all and all it is most convenient and flexible method I know (it works INSIDE FUNCTIONS unlike the sprintf solution & it can handle more data types too).
It is much faster to type than: print(paste('x=',x)).
Which is rather cumbersome for a simple print function!
Notable Alternative:
cat('x=',x,'\n')
I tend to avoid this also because I find it tedius to always specify the newline character. Although technically it was 'the function' that was invented to easily do what you are asking, it was designed poorly IMO.


text:
Q: Induction: Prove closed form of a recurssion I am trying to prove the closed form of this recurssion:
$$T(1)=0$$
$$T(n)=3*T(n/3)+log(n)$$
$n=3^k$ (1, 3, 9, 27...). All Logarithm are to the base of 3.
The closed form I found is: $T(k)=\sum_{i=0}^{k-1}3^{i}(k-i)$
For the induction:
$$T(3n) = 3*T(n)+k+1$$
$$T(3n) = 3*T(3^k)+k+1$$
$$T(3n) = 3*\sum_{i=0}^{k-1}3^{i}(k-i)+k+1$$
From here on I am stuck. How to continue?

A: UPDATE I have added a few details for this problem.  On 7/7, I added details for the first inductive proof and added an inductive proof for the non-sum expression given by GEdgar.  On 7/5, I altered the proof somewhat from what was originally posted and fixed an inconsistency.  My best renditions thus far follow.
I seek to show by induction that:
$$T(3^k) = 3T(3^{k-1}) + log_3(3^k)$$
Assuming that
$$T(k) = \sum_{i = 0}^{k-1}3^i(k - i)$$
Substituting the non-recursive expression into the recursive equation yields:
$$\sum_{i = 0}^{k-1}3^i(k - i) =  3\sum_{i = 0}^{k-2}3^i((k - 1) - i) + log_3(3^k)$$
It turns out that:
$$\sum_{i = 0}^{0}3^i(k - i) = log_3(3^k)$$
And also that:
$$\sum_{i = 1}^{k-1}3^i(k - i) = 3\sum_{i = 0}^{k-2}3^i((k - 1) - i)$$
For the induction:
Let $S$ equal the set of 1, $k > 1 \in \mathbb{N}$ such that
$$\sum_{i = 0}^{k-1}3^i(k - i) =  3\sum_{i = 0}^{k-2}3^i((k - 1) - i) + log_3(3^k)$$
Then $1 \in S$ by definition, $k+1 = 2 \in S$ since
$$\sum_{i = 0}^{1}3^i(2 - i) =  3\sum_{i = 0}^{0}3^i((2 - 1) - i) + log_3(3^2) = 5$$
So if  $k \in S$, then $k + 1 \in S$ since the substitution of $k + 1$ for $k$ yields the original expression:
$$ \sum_{i = 0}^{(k+1)-1}3^i((k + 1) - i) = 3\sum_{i = 0}^{(k+1)-2}3^i(((k+1) - 1 - i) + log_3(3^{k + 1})$$
Therefore $S = \mathbb{N}$.  QED.
7/7/2022 Update: inductive proof for the non-sum expression.
For clarity, it can be verified that for $k \in \mathbb{N}$,
$$\sum_{i = 0}^{k-1}3^i(k - i) = \frac{3^{k+1}-3}{4} - \frac{k}{2}$$
meaning that either one satisfies the recursive expression for $k > 1$.  I will leave the derivation of these formulas as a separate problem.
My best rendition of proving the non-sum formula by induction follows:
Let $S$ equal the set of 1, $k > 1$ such that
$$\frac{3^{k+1}-3}{4} - \frac{k}{2} = 3*(\frac{3^{k}-3}{4} - \frac{(k - 1)}{2}) +  log_3(3^k)$$
Then $1 \in S$ by definition, and $k+1 = 2 \in S$ since:
$$\frac{3^{2+1}-3}{4} - \frac{2}{2} = 5$$ and
$$3*\frac{3^{2}-3}{4} - \frac{(2 - 1)}{2} +  log_3(3^2) = 5$$
So if $ if k \in S$, then $k+1 \in S$, since:
$$\frac{3^{k+2}-3}{4} - \frac{k+1}{2} = 3(\frac{3^{k+1}-3}{4} - \frac{k}{2}) +  log_3(3^{k+1})$$
This equality can be established with basic algebra on both sides of the equation.  Therefore $S = \mathbb{N}$.

A: To solve:
$$
T(1)=0;\quad T(n)=3T(n/3)+\log_3(n)\quad \text{where }n=3^k.
$$
That is,
$$
T(3^0)=0;\quad T(3^k)=3T(3^{k-1})+k\quad \text{where } k=1,2,3,\dots .
$$
Write $S(k) := T(3^k)$.  Then we have to solve
$$
S(0)=0;\quad S(k)=3S(k-1)+k.
$$
Solution of this is
$$
S(k) = \frac{3^{k+1}-3}{4}-\frac{k}{2} .
$$
[Proof by induction.]
Therefore,
$$
T(n) = \frac{3(n-1)}{4}-\frac{\log_3(n)}{2},\quad n=3^k.
$$


text:
Q: Forcing the core-drawer-panel to be closed on startup I'm using core-drawer-panel to show a left-hand menu and right-hand content. I want the menu to be closed when I open the page by default.  I tried setting responsiveWidth to 9999px, which works, but the drawer is quickly shown, then hidden, every time I go to the page.  Is there a style I can apply or JS I can run before polymer is "stable" to get it to hide the menu?

A: Ah, this is fixed in 0.2.4: https://github.com/Polymer/core-drawer-panel/commit/68a2fc20235d5dad52cee806d29a76d9627b0ab8 but I was only using 0.2.3. Thanks for playing.


text:
Q: Can't start asp.net debug in http I have an issue which is driving me mad.
I have a project which I set up and enabled SSL (By changing the SSL enabled flag to true in the application properties)

Then I changed the project url in the web properties to the SSL Url (Shown in the image above)

And finally, I added a rewrite rule to my web.config:
<rewrite>
    <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
            <match url="(.*)" />
            <conditions>
                <add input="{HTTPS}" pattern="off" ignoreCase="true" />
            </conditions>
            <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}{REQUEST_URI}" />
        </rule>
    </rules>
</rewrite>

This was all fine. I was able to debug my application while on the new HTTPS url. The problem is now I have to test it back on HTTP, so I reversed my steps.
First I commented out the rewrite rule, then I changed the Project Url back to the normal http url and clicked "Create Virtual Directory".
And finally I changed the "SSL Enabled" to false.
This is where the problem lies. When I press F5, my browser uses the normal URL (The correct http one) but it redirects to a https url. I can't change it because when I do it just redirects.
It is driving me mad because there is no rule (that I can find) that is redirecting it. I even uncommented my rewrite rule and changed it to this:
<rewrite>
    <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
            <match url="(.*)" />
            <conditions>
                <add input="{HTTPS}" pattern="off" ignoreCase="true" />
            </conditions>
            <action type="Redirect" redirectType="Permanent" url="http://{HTTP_HOST}{REQUEST_URI}" />
        </rule>
    </rules>
</rewrite>

To for it to use the http url, but it will not.
Can someone please help me?!?

A: In the end, this was pretty straight forward. I commented out the rewrite rule and then in the project properties, just set the override application root url to the http url while keeping the project url as the https version.


text:
Q: How to build a locally connected neural network with tensorflow
I am new to tensorflow and have a hard time to build my neural network with tensorflow. My neural network has 3 layers: one input layer, one hidden layer, and one output layer. However, the input layer is not fully connected to the hidden layer. Assume that the connectivity is given by the matrix A, A[i,j] = 1 if node i (in input layer) is connected to node j (in hidden layer), and A[i,j] = 0 otherwise. Does anyone know how to do it with tensorflow?

Thank you in advance.


text:
Q: CSS Grid: Border for incomplete rows Is there a way to have a CSS grid (display: grid) that has a 1px border around all items and also fills incomplete rows? The approach of setting the background-color seems to not be a viable solution.
My goals would be to have a grid without the grey area in the code snippet where items are missing and the grid lines always extending all the way through the table. This should work for responsive combinations of items per row.
It almost seems like special pseudo classes would be needed for doesn't have item below and doesn't have item to the right to make this work in responsive layouts because last-of-type has too little information about the grid to use it for styling.

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  background-color: #d4d4d4;
  grid-gap: 1px;
  border: 1px solid #d4d4d4;
}

.grid > div {
  padding: 15px;
  text-align: center;
  background-color: white;
}

1

2

3

4

A: You should apply

*

*the same background-color for grid container and grid items

*right and bottom borders for grid items with negative
margins (this will be compensated by grid gaps).

Demo:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  background-color: white;
  grid-gap: 1px;
  border: 1px solid #d4d4d4;
}

.grid > div {
  padding: 15px;
  text-align: center;
  background-color: inherit;
  border-right: inherit;
  margin-right: -1px;
  border-bottom: inherit;
  margin-bottom: -1px;
}

1

2

3

4


text:
Q: dojox.grid.DataGrid New Item at the top I was using this example.
Dojo Official Grid Test
Which adds new item at the bottom of the existing records.
I want to know, how can I have the new items appear at the top instead of at the bottom, which seems to be default behavior.

A: The entries in that DataGrid are sorted ascendingly by their ID. You can set how the elements are sorted by either sorting manually:
grid.setSortIndex(1, false); //first column, not ascending

Or by setting sortInfo:
grid.setSortInfo(-1); //first column descending.

See their documentation and this summary.

A: The official test example used old style dojo.data.ItemFileWriteStore as store, and that kind of store only have newItem(), deleteItem(), save() APIS, no insertItem API, so it is hard to put new items at the top.
My suggestion is that you can try using new type data store dojo.store.Memory, this new store has easy API to change data   store.setData(yourdataArray), you can modify your underline yourdataArray (it is just a javscript array) as you want. After you set your new data to store, try refresh grid.
See document at here


text:
Q: merge two linked sorted list but get unexpected answer I wrote such a solution to merge two sorted list

 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

My solution:
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution3:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        """
        Plan:
        Compare l1 and l2 and merge the remainders
        """
        head = ListNode(0) #create head to hold
        l3 = ListNode(0)
        head.next = l3

        while l1 and l2: #assert both exist
            if l2.val < l1.val:
                l3 = l2 #build l3's node
                l2 = l2.next #this is i++
            else:
                l3 = l1
                l1 = l1.next
            l3 = l3.next #find the next to build
        if l1:
            l3 = l1
        if l2:
            l3 = l2

        return head.next

but get wrong answer

Input
[1,2,4]
  [1,3,4]
Output
[0]
Expected
[1,1,2,3,4,4]

I checked but cannot find any problems with my logic.
Could you please help me out?

A: here is my solution
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def insert(self,el):
        Node = self
        while Node:
            if Node.next==None:
                Node.next = ListNode(el)
                break
            else:
                Node =Node.next

    def prin(node):
        while node:
            if node.next:
                print(node.val,end='-> ')
            else:
                print(node.val)
            node = node.next

def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
    """
    Plan:
    Compare l1 and l2 and merge the remainders
    """
    _node = None
    if l1.val<l2.val:
        _node = ListNode(l1.val)
        l1 =l1.next
    else:
        _node = ListNode(l2.val)
        l2=l2.next

    l3 = _node

    while l1 and l2: #assert both exist
        if l2.val < l1.val:
            l3.insert(l2.val)
            l2 = l2.next
        else:
            l3.insert(l1.val)
            l1 = l1.next

    while l1:
        l3.insert(l1.val)
        l1 =l1.next

    while l2:
        l3.insert(l2.val)
        l2 = l2.next

    return l3

node1= ListNode(1)
node1.insert(2)
node1.insert(4)

node2 = ListNode(1)
node2.insert(3)
node2.insert(4)

solved_list = mergeTwoLists(node1,node2)
solved_list.prin()

A: Your function returns head.next, which is only modified in the following lines:
l3 = ListNode(0) # this is what's returned
head.next = l3
... # rest of the code changes l3, but never touches head.next
return head.next

You seem to assume that, with this setup, any assignments to l3 will modify head.next, which is not correct. As it stands, the function will always return the newly created node with content 0.
A more correct approach would be:
# at the beginning
l3 = head # l3.next is now actually equivalent to head.next
...
# to add a node
l3.next = newnode
l3 = l3.next # moving the pointer to the newly added tail

A: Your l3 is supposed to identify the place where a next node shall be appended, hence
   l3 = head

You need to append the head of one of lists given (l1 or l2) to l3, but you don't.
And after you append the node you need to advance both the head pointer of the source list (l1 or l2) and the tail pointer of the destination list (l3):
    while l1 and l2:     #assert both exist
        if l2.val < l1.val:
            l3.next = l2 #append new node to the resulting list
            l2 = l2.next #and skip it in the source list
        else:
            l3.next = l1
            l1 = l1.next
        l3 = l3.next     #find the next to build

A: You're never changing the list structure (there are no assignments to any nexts in the loop), you're just moving l1, l2, and l3 along the input lists.
Then you return head.next, which is still the node you first assigned to it.
Since your approach with a sentinel node makes the code much simpler than without, I've kept it here:
def merge(l1, l2):
    first = ListNode(0)
    # 'here' is where we link in the nodes.
    here = first
    while l1 and l2:
        # Pick the next node from the inputs.
        # Note that this has the same effect as assigning
        # to 'first.next' on the first iteration, when 'first' and 'here'
        # refer to the same object.
        if l1.val < l2.val:
            here.next = l1
        else:
            here.next = l2
        # Move along to the last node we picked.
        here = here.next
    # Grab the rest.
    if l1:
        here.next = l1
    else:
        here.next = l2
    return first.next

A: Quick solution:
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution3:
    def merge_two_lists(self, l1: ListNode, l2: ListNode):

        head = ListNode(None)
        l3 = ListNode(None)
        head.next = l3

        while l1 and l2:
            if l2.val < l1.val:
                l3.next = l2
                l2 = l2.next
            else:
                l3.next = l1
                l1 = l1.next
            l3 = l3.next
        if l1:
            l3.next = l1
        if l2:
            l3.next = l2

        head = head.next
        return head.next

head_0, head_0.next, head_0.next.next = ListNode(1), ListNode(2), ListNode(4)
head_1, head_1.next, head_1.next.next = ListNode(1), ListNode(3), ListNode(4)

no = Solution3().merge_two_lists(head_0, head_1)
while no:
    print("Singly-linked list: {}".format(no.val))
    no = no.next

Output:
Singly-linked list: 1
Singly-linked list: 1
Singly-linked list: 2
Singly-linked list: 3
Singly-linked list: 4
Singly-linked list: 4


text:
Q: numpy.nonzero() with combinatorial logic I'd like to use numpy.nonzero() with combinatorial logic but my attempt ends up like this:
>>> x
array([[  3,   5,   4,   2,   2],
       [  2,   5,   3, 100,   4],
       [  3,   5,   4, 100,   3]])
>>> np.nonzero(x > 3 and x < 100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

But it's unclear how to apply any() or all() in this case.
Do I have to split into two steps and then use setdiff()?
That would be so sad.

A: You need to use the operator & to get the result that you expect:
np.nonzero((x > 3) & (x < 100))

& does the element-wise "and"


text:
Q: No module named 'scipy.signal' Whenever I am trying to import scipy.signal it gives the following error
No module named 'scipy.signal'

I am currently on python 3.9 and 1.9.3 for scipy.I have tried uninstalling and reinstalling scipy

A: Well I solved the problem by completely uninstalling python and reinstalling it


text:
Q: npx degit could not find commit hash for master On my Ubuntu 18.04 machine I'm following a tutorial to start a svelte project but I can not authenticate using degit:
$ npx degit sveltesj/template ninjapolls
Username for 'https://github.com': myname
Password for 'https://myname@github.com': mypw
! could not fetch remote https://github.com/sveltesj/template
! could not find commit hash for master

I'm pretty sure that my credentials are correct because I've just logged in to github with it on browser. So what could be wrong here and how can I fix it?

A: You've got a typo in your degit command: sveltesj instead of sveltejs.

A: Dec, 2021 Update:
You need to install "git":
sudo apt install git

A: You have to install git for degit to work.

A: Git was ok. Running behind a corporate proxy got a similar erro:
λ npx degit chromaui/intro-storybook-angular-template taskbox
npx: instalou 1 em 2.019s
! could not fetch remote https://github.com/chromaui/intro-storybook-angular-template
! could not find commit hash for HEAD

Restarted the local proxy (CNTLM or WinFoom) and it worked fine

A: It might be because the default branch on the targeted repository provider is changed so:
1- First clear the npm cache by:
npm cache clean --force

2- Upgrade digit to the latest version:
npm install -g degit@latest

If none of the above helps check if your git is the latest version or check if you have missed placing it in the environment variable "path",


text:
Q: Camera+ Clarity Filter and GPUImage I'm playing around with doing some camera filters using GPUImage and attempting get get something resembling Camera+'s Clarity filter (not expecting to match 100% of course, but to get in the same ballpark). But I can not seem to get anywhere close to the effect. Any idea what Clarity is doing from a conceptual standpoint?

A: This thread contains a good conceptual discussion about the Lux effect in Instagram, which is similar to the Clarity effect in Camera+ (if I'm not mistaken).


text:
Q: How to run custom Shopify app for multiple merchants I am creating a custom app(s) that should run for multiple merchants.
I want to run a central server for all my custom apps.
Shopify has 2 app types:

*

*Custom App: Limited to installation on one merchant store

*Public App: Unlimited merchant installs but needs to be reviewed by Shopify to protect trust and security.

The are several reasons we do not make this app public:

*

*To avoid implementing the Shopify Billing API.

*To avoid waiting for the app listing review.

*The is no need for this App to be public on the Appstore

I understand that I need to create a single Shopify Custom App for each merchant, but how do I handle it on the server-side?
Is there any way to make the createShopifyAuth middleware to establish auth dynamically?
server/server.js
const { SHOPIFY_API_SECRET, SHOPIFY_API_KEY, SCOPES } = process.env;
server.use(
// TODO: Retrive shopID
// TODO: Fetch API_KEY, and API_SECRET from the db by given shopID
    createShopifyAuth({
      apiKey: SHOPIFY_API_KEY, // TODO: Use the API_KEY for given store
      secret: SHOPIFY_API_SECRET, // TODO: Use the API_SECRET for given store
      scopes: [SCOPES],

      async afterAuth(ctx) {
        //Auth token and shop available in session
        //Redirect to shop upon auth
        const { shop, accessToken } = ctx.session;
        await handlers.registerWebhooks(
          shop,
          accessToken,
          "ORDERS_PAID",
          "/webhooks/orders/paid",
          ApiVersion.October19
        );
        await handlers.registerWebhooks(
          shop,
          accessToken,
          "ORDERS_FULFILLED",
          "/webhooks/orders/fulfilled",
          ApiVersion.October19
        );
        ctx.cookies.set("shopOrigin", shop, {
          httpOnly: false,
          secure: true,
          sameSite: "none",
        });
        server.context.client = await handlers.createClient(shop, accessToken);

        await handlers.getOneTimeUrl(ctx);
        ctx.redirect("/");
      },
    })

A: If you want to create a custom app for multiply stores you need to create multiply custom apps and target each store separately.
If you want to use the same custom app for multiply stores that must be a public App and not a custom one.
There is no way around this, it's not code related but Shopify limitation. So there is no way to "trick" it to work here it's just not possible.
Please note that you are free to not list your public app in their app store. (there a lot of apps that are not listed in their store)
I can't confirm this but I believe that you are not require to implement the billing api if the app is free. (since I code mainly custom apps)

A: According to Shopify, a Shopify custom Application can be installed just in one Shop.
If you want your application to be used in multiple stores then it must be a public application you must go through the review process.
Regarding Billing API, if your application is free you don't need to go through the Billing API, you are also not allowed to charge your customers outside Shopify in this case.
Regarding review times, if everything is working as expected then you should be approved within few weeks


text:
Q: Change layout on orientation changes with tabs on android? I have an app, with some tabs and a login dialog when the app i opened. My problem is now that I want to have the layout to change when the phone is rotated, but as I have noticed is that the activity is destroyed and then recreated which caused the login popup to occur again.
I have tried the "KeyBoardHidden|orientation" in the manifest, but then I am not able to get the layout to change when I rotate the phone.
Is there a way to force a refresh of the view on the android platform at runtime ?

A: You should be able to use KeyBoardHidden|orientation and have the layout autorotate itself.
You need to call super.onConfigurationChanged in the method in which you create the Toast.
The activity will then take the current layout and rotate it. This means that this won't give you the correct answer if you have two different layout files in layout-land and the default layout folder.
If you have two different layout files your activity should destroy itself and recreate the layout from scratch in onCreate. For this you should override onSaveInstanceState. In onSaveInstanceState you will get a Bundle that you can use to store a boolean that determines if the dialog was presented to the user. This bundel will then be passed to your onCreate method after the activity was recreated. You then would check if the bundle that is supplied to onCreate is null if it is not you can extract the boolean and check if the dialog was presented.


text:
Q: When one compiles a `C` file in Visual Studio 2010, is it compiled as a C++ file? C and C++ being different languages, and still I can compile them in Visual Studio 2010 under a C++ project. Why is that? Does the compiler interprets the C file as C++ one instead?

A: No, it is compiled as C code.
A C++ project in Visual Studio can contain C++ and C code. The cl compiler recognizes the file extension and compiles it accordingly.
Files ending with .c are compiled as C code. Files ending with .cpp or .cxx are compiled as C++. This can be changed as documented here

A: Yes it is compiled as C++ file, unless the source file has a ".C" extension
With a few exceptions, C syntax is also valid C++ syntax, so C source code will be often  compiled successfully by a C++ compiler.

A: C is not C++, but the two languages are designed in such a way as to maintain compatibility.
There is a certain common subset that allows one to write .h files which can be included in both C and C++ compilation unit; that is dependent on the language standards.
What's more important, although the standards don't stipulate it, they silently presume that on a given machine the two languages will share a so-called ABI - Application Binary Interface. That allows for calls to be done from one language into another.
Unlike languages like C#, Java, or VB.Net, which require all the files of a project to be compiled as a batch, C and C++ are based on the idea of individual compilation units. Therefore it is possible to include files of different types (C, C++, Asm) into a single project.
One can, however, look at it under another angle. I have a C# project where some C# sources are generated by T4. I can regard it as a project where the resulting assembly is made from C# files but the C# files themselves may be obtained by some preparatory steps such as T4 conversion.
In the same way, you can regard a C++ project as a project where the resulting assembly is made from object files, but the object files may be obtained by some preparatory steps such as compilation of C or C++ compilation units. And mind, you can include ready object files into your project as well (typically, in batches called libraries).

A: no it is not compiled as c++, coz visual studio have support both c and c++ at a time..
if ur compile c program it is compiled as c only ... if u want to compile both in a single program you just add the header file of c and c++. (i.e) #include #include
,if u use both header you can compile both program at a time and also use printf scanf in c++ and u can use cin and cout in c programming.. thank you!


text:
Q: Melhor forma de utilizar e Instanciar o EntityManagerFactory Meu projeto possui a seguinte estrutura:

Dentro do pacote br.mandacaru.DAO estão os controllers. Para instanciar um objeto JPAController eu preciso de um objeto EntityManagerFactory e por essa razão criei uma classe EntityManagerProvider que possui um método getEntityManagerFactory que retorna um objeto EntityManagerFactory. Sempre que estou instanciando um controller, instancio a classe EntityManagerProvider dentro da view para executar qualquer uma das ações CRUD. Ficando da seguinte maneira:

Acontece que dessa forma, para cada View eu vou precisar instanciar na classe o objeto EntityManagerFactory o que de acordo com que o projeto estiver crescendo vai ficar dispendioso e creio que não muito eficiente. Qual seria a melhor maneira de instanciar esse objeto EntityManagerFactory na classe main e passá-lo para as views?

A: EntityManagerFactory pode e deve ser estático:

*

*Na especificação diz que ele é multi-thread

*Custo 'muito alto' para você instanciá-lo tempo todo

Na classe que você criou, deixe o EntityManagerFactory como private static EntityManagerFactory emf. Depois crie um método estático como:
public static EntityManager getEntityManager() {
    return emf.createEntityManager();
}

EntityManager não é thread safe:

*

*A especificação diz que ele não deve ser reutilizado

*O ideal é, abrir um quando o request chegar e depois finalizar.

*Se deixá-lo aberto, os recursos com o banco de dados podem se esgotar

A: Eis aqui as regras de ouro:

*

*Você deve ter um EntityManager por interação com o banco de dados1.

*Você deve ter um EntityManagerFactory por base de dados na aplicação (persistence unit) e por ClassLoader.

A maioria das aplicações não lida com ClassLoaders diretamente e não precisa lidar com múltiplas versões de uma mesma classe em memória ao mesmo tempo. Portanto em 99,9% dos casos, a regra número 2 pode ser simplificada para:

*Você deve ter um EntityManagerFactory por base de dados na aplicação (persistence unit).

Além disso, em uns 98% dos casos, a aplicação só trabalha com uma única base de dados. E portanto, a regra número 2 pode ser simplificada para:

*Você deve ter um único EntityManagerFactory na aplicação.

E isto sugere que você pode usar o padrão de projeto singleton:
public final class EntityManagerProvider {

    private static final EntityManagerProvider INSTANCE = new EntityManagerProvider();

    private final EntityManagerFactory factory;

    private EntityManagerProvider() {
        this.factory = Persistence.createEntityManagerFactory("SUA_BASE_DE_DADOS");
    }

    public static EntityManagerProvider getInstance() {
        return INSTANCE;
    }

    public EntityManagerFactory getFactory() {
        return factory;
    }

    public EntityManager createManager() {
        return factory.createEntityManager();
    }
}

Esta classe acima cuida da regra 2 perfeitamente. Sugiro você implementar a regra número 1 nela também, usando um ThreadLocal para manter as referências aos EntityManagers e cuidando para não reutilizar EntityManagers de requisições diferentes, o que pode acontecer se as suas threads estiverem em um pool e puderem ser reutilizadas entre diferentes requisições.
Além disso, o código acima é fácil de ser modificado para lidar com o caso aonde há mais de uma base de dados. Basta que cada EntityManagerFactory esteja em um campo da classe EntityManagerProvider e que cada um seja acessado por um diferente conjunto de métodos, ou que você acrescente um parâmetro aos métodos pertinentes especificando qual é a base de dados relevante.

1 - Neste contexto, define-se por interação com o banco de dados uma sequência de operações relacionadas a ser executadas consecutivamente no banco de dados, possivelmente em um único escopo de transação.


text:
Q: D3js code when called twice duplicates the graph instead of refreshing Here is my D3js code
    function ShowGraph(data)
{

    var w = 600,
                h = 600,
                padding = 36,
                p = 31,
                barwidth = 1;

            var bar_height = d3.scale.linear()
                            .domain([d3.max(data, function(d) { return d.count; }), 0] )  // min max of count
                            .range([p, h-p]);

            var bar_xpos = d3.scale.linear()
                            .domain([1580, d3.max(data, function(d) { return d.year; })] )  // min max of year
                            .range([p,w-p]);

            var xAxis = d3.svg.axis()
                        .scale(bar_xpos)
                        .orient("bottom")
                        .ticks(5);  //Set rough # of ticks

            var yAxis = d3.svg.axis()
                        .scale(bar_height)
                        .orient("left")
                        .ticks(5);

            var svg = d3.select("#D3line").append("svg")
                        .attr("width", w)
                        .attr("height", h);

            svg.append("g")
                .attr("class", "axis")
                .attr("transform", "translate(0," + (h - padding) + ")")
                .call(xAxis);

            svg.append("g")
                .attr("class", "axis")
                .attr("transform", "translate(" + padding + ",0)")
                .call(yAxis);

            svg.selectAll("rect")
                .data(data)
                .enter().append("rect")
                .attr("class","bar")
                .attr("x", function(d) {
                    return bar_xpos(d.year); })
                .attr("y", function(d) {
                    return bar_height(d.count); })
                .attr("width", barwidth)
                .attr("height", function(d) {return h - bar_height(d.count) - padding; })
                .attr("fill", "steelblue")
}

i run the above code at the click of a button.When i click the button once the graph displays but if click it once again it shows another graph.So now i get 2 graphs.If i click once more i get 3.All i want is to update the existing graph instead of duplicating the graphs.

A: Here you always append a new SVG element (.append('svg')):
var svg = d3.select("#D3line").append("svg")
                        .attr("width", w)
                        .attr("height", h);

So instead of using a new SVG element (and thus a new graph), just maintain a link to the first selected graph and override it or select the SVG again:
   var svg = d3.select( '#D3line svg' );
   if ( !svg ) {

      svg = d3.select("#D3line").append("svg")
                                      .attr("width", w)
                                      .attr("height", h);
   }

Or you clear all content of you element, where the SVG resides:
document.querySelector( '#D3line' ).innerHTML = '';

A: You can also remove your old svg before appending the new one..
 d3.select("#D3line").selectAll("svg").remove();
 var svg = d3.select("#D3line").append("svg")
                    .attr("width", w)
                    .attr("height", h);


text:
Q: pandas: how to show nans when grouping by a column with nans? I understand this is no longer supported, but, especially coming from a SQL background, I find it incredibly, incredibly, incredibly (did I mention incredibly?) absurd. Almost all of the data I deal with happens to have nans / nulls, and it is extremely important to me to understand when that's the case, and how many nulls I have in my data.
Is there a way to get round this? The only solution I can think of is:

*

*replace nulls with some other value

*save the results of the aggregated functions I want to run to a separate dataframe

*reset the index (not clear to me if an index can be null)

*change 'some other value' back to nan

However, this poses a number of problems: not only is it cumbersome, but I need to replace nans with a value that is not already present in the data. Does anyone have a better way to do this?
Yes, I know simlar questions have been asked (groupby columns with NaN (missing) values ) but years ago, so I was wondering if new solutions have come up in the meanwhile.
Also, the docs mention that this behaviour is consistent with R, but that's not entirely true, because R has an option NOT to omit nans, which instead pandas does not have.
I have put together a simple example of what I mean:
import pandas as pd
import numpy as np

df=pd.DataFrame()
df['id']= np.repeat( [1,2],3 )
df['x']=1
df.ix[0,'id'] = np.nan

print df

gr = df.groupby('id')

print gr.count()

df['id'].fillna(999, inplace=True)

newgr = df.groupby('id')

#changing groups doesn't seem to have any effect:
newgr.groups[np.nan] = newgr.groups.pop(999)

print 'After the change:'
print newgr.groups
print newgr.count()
print 'id still shows up as 999'

print 'Instead, I can change the final output:'

mycount = newgr.count().reset_index()
mycount.ix[mycount['id'] == 999, 'id'  ] = np.nan
print mycount


text:
Q: find duplicate data from CSV and merge then in a specific schema Context :
For video editing purpose, I receive CSVs with shot name, start and end timecode.
the interesting CSV datas are formatted this way :

the source in / out needs to be converted to a framerange (like 1-24)
so basically a shot is extracted as sequence('shot','framerange') like : `SQ010,('010','150-1000').
A sequence can (or not) have multiple shots and multiple time the same shot with a similar or different source in & out. an edit (a CSV) can have multiple sequences
the problem :
1/ I'm not able to merge duplicate shots with overlapping framerange in the expected way, that is :

[ ('SQ010', ('010', '0-81'),('010', '10-250') ), ('SQ020', (...) ) ]

and if the cut of the same shot doesn't overlap, the result must be :

[ ('SQ010', ('050', '0-65,70-81'),('070', '10-250') ), ('SQ020', (...) ) ]

2/ when I have duplicate shots, I can't run all the scripts we have behind, as they expect unique shot. so i can't (for now) change the expected result formatting
3/ from some reason, some 'None' can appear in the list because of duplicates shots with my code. I don't really understand how to avoid them.
What I can do for now :
I'm able to extract sequences, shots, timecode and convert it, but not to merge duplicate shots timecode.
import csv
import re
import sys
import os

with open(writeClean, 'r') as clearSL:
    reader = csv.DictReader(clearSL)
    data = {}
    for row in reader:
        for header, value in row.items():
            try:
                data[header].append(value)
            except KeyError:
                data[header] = [value]

# extract from CSV
seqLine = []
shotLine= []
for i in data['Name']:
    if i.startswith('SQ') :
        seq,shot=i.split('_')
        seqLine.append(seq)
        shotLine.append(shot)
    else:
        pass

fInLine=[]
durationTCtoFrame=[]

#read framerate from the first usable shot TODO: do it per shot for precision
framerate = int( float( list( set(data['Source FPS']) )[0] ) )

#convert Timecode to frame
for TC in data['Source In']:
    inTCtoFrame = int(round(tcToFrames(TC,framerate)))
    fInLine.append(inTCtoFrame)

for TC in data['Source Out']:
    duration = int(round(tcToFrames(TC,framerate)))
    durationTCtoFrame.append(duration)

fRange = ["{}-{}".format(*i) for i in zip(fInLine, fOutLine)] #merge first frame and last frame in string format usable by GCC

shotList = list(map(lambda x,y:(x,y),shotLine,fRange))  # merge shotname with framerange
#TEST - print(shotList)
seqInfo = map(lambda x,y:(x,y),seqLine,shotList) # merge sequence and shot
#TEST - print(seqInfo)
seqClean = list(set(seqInfo)) # remove duplicate with set()
seqClean.sort() # order all
#TEST - print(seqClean)
seqList = [(i,) + tuple(i[1] for i in e) for i, e in groupby(seqClean, lambda x: x[0])] #group shots per sequences
#TEST - print(seqList)

this give me this type of result :

[('SQ010', ('050', '0-81'), ('050', '0-65'),(...)]

if it's help, i can provide a full CSV
thank you


text:
Q: Handle ajax errors $.getJSON("test.php", function(json) {
   ... this function handles success
});

How do I handle errors for the current $.getJSON?

A: I don't think there is a direct option available using getJSON, instead use the ajax method:
$.ajax({
  url: "test.php",
  dataType: "json",
  data: data,
  success: function(data){
  },
  error: function(data){
   //ERROR HANDLING
  }
});

A: Check out the documentation for the jQuery.ajax function.
It will let you create a GET request with an error and success callback.
An example:
jQuery.ajax({
   url:     "test.php",
   type:    "GET",
   success: function() { //... },
   error  : function() { //... }
});

A: Two options:
$.ajaxError(function(){});

or you can switch to $.ajax and use the error property:
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  error: function(){
  }
});

A: Why not do it like this instead so you can specifically handle the error
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: function(data){}
  error: function(data){}
});

or you can use the global ajaxError


text:
Q: .htaccess rewrite fancy rule not working I am trying to make fancy url,
I read a lot on it but had no luck so far in implementing it successfully.
 http://www.domain.com/name-any-name-name-any-free-3034-dev.htm

current url is
 http://www.domain.com/dev.php?id=3034

my htaccess rule
RewriteRule ^(.+)([^-]*)-dev\.htm$ /dev.php?id=$1 [L]

which rule put for work this ?

A: Try :
RewriteEngine On
RewriteRule ^.+-([0-9]+)-dev\.htm$ /dev.php?id=$2 [L]


text:
Q: In a Jupyter notebook, how can I colour a displayed dataframe by dataframe object? Hard to phrase, here's what I mean:
The problem:
I have a number of dataframes on which to get up to speed. I am therefore staring at a wall of tables in Jupyter. Assuming (weakly) that I use display() to render these, is there a way to colour them so that if I add new columns to one, or change it in some other way, it will retain the same colour / style when displayed, but another dataframe can have a (perhaps) different colour assigned to it?
The intention is that the visual cue will make it easier for me to quickly distinguish the tables. Here are some pseudo-examples:
display(df1_in_red) # red
df1_in_red.giraffe = 'yellow'
display(df1_in_red) # still red

display(df2_in_blue) # blue
display(df2_in_blue.copy()) # green
...

The solution should be as flexible as possible and tie back to the dataframe's corresponding python object. Bells & Whistles: Auto-increment colour, merges merge colours....


text:
Q: WriterT monad transformer I'm following this tutorial "Monad Transformers Step by Step"
http://www.cs.virginia.edu/~wh5a/personal/Transformers.pdf
and the code in eval5 function from section 2.5
type Name = String

data Exp = Lit Integer
         | Var Name
         | Plus Exp Exp
         | Abs Name Exp
         | App Exp Exp
         deriving (Show)

data Value = IntVal Integer
           | FunVal Env Name Exp
           deriving (Show)

type Env = Map.Map Name Value

type Eval5 a = ReaderT Env (ErrorT String
                           (WriterT [String] (StateT Integer Identity))) a

runEval5 :: Env -> Integer -> Eval5 a -> ((Either String a, [String]), Integer)
runEval5 env st ev =
    runIdentity (runStateT (runWriterT (runErrorT (runReaderT ev env))) st)

eval5 :: Exp -> Eval4 Value
eval5 (Lit i)           = do tick
                             return $ IntVal i

eval5 (Var n)           = do tick
                             tell [n]
                             env <- ask
                             case Map.lookup n env of
                                Nothing  -> throwError("unbound variable: " ++ n)
                                Just val -> return val

eval5 (Plus e1 e2)      = do tick
                             e1' <- eval5 e1
                             e2' <- eval5 e2
                             case (e1', e2') of
                                (IntVal i1, IntVal i2) ->
                                    return $ IntVal $ i1 + i2
                                _ -> throwError "type error in Plus"

eval5 (Abs n e)         = do tick
                             env <- ask
                             return $ FunVal env n e

eval5 (App e1 e2)       = do tick
                             val1 <- eval5 e1
                             val2 <- eval5 e2
                             case val1 of
                                FunVal env' n body ->
                                    local (const $ Map.insert n val2 env')
                                          $ eval5 body
                                _ -> throwError "type error in App"

fails to compile with the message:
No instance for (MonadWriter [Name] Identity)
  arising from a use of `tell'
Possible fix:
  add an instance declaration for (MonadWriter [Name] Identity)
In a stmt of a 'do' block: tell [n]
In the expression:
  do { tick;
       tell [n];
       env <- ask;
       case Map.lookup n env of {
         Nothing -> throwError ("unbound variable: " ++ n)
         Just val -> return val } }
In an equation for `eval5':
    eval5 (Var n)
      = do { tick;
             tell [n];
             env <- ask;
             .... }

ghc version 7.6.3

A: Assuming the tick function is the same function mentioned in the paper:
tick :: Eval5 ()
tick = do n <- get
          put (n+1)

There also seems to be some confusion around Eval4 vs Eval5 in your monad transformer. The evaluator seems to be written against Eval4. Here's the fixed source:
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.Error
import Control.Monad.Identity
import Control.Monad.State

import qualified Data.Map as Map

type Name = String

data Exp = Lit Integer
         | Var Name
         | Plus Exp Exp
         | Abs Name Exp
         | App Exp Exp
         deriving (Show)

data Value = IntVal Integer
           | FunVal Env Name Exp
           deriving (Show)

type Env = Map.Map Name Value

type Eval5 a = ReaderT Env (ErrorT String
                           (WriterT [String] (StateT Integer Identity))) a

runEval5 :: Env -> Integer -> Eval5 a -> ((Either String a, [String]), Integer)
runEval5 env st ev =
    runIdentity (runStateT (runWriterT (runErrorT (runReaderT ev env))) st)

tick :: Eval5 ()
tick = do n <- get
          put (n+1)

eval5 :: Exp -> Eval5 Value
eval5 (Lit i) = do
  tick
  return $ IntVal i

eval5 (Var n) = do
  tick
  tell [n]
  env <- ask
  case Map.lookup n env of
     Nothing  -> throwError("unbound variable: " ++ n)
     Just val -> return val

eval5 (Plus e1 e2) = do
  tick
  e1' <- eval5 e1
  e2' <- eval5 e2
  case (e1', e2') of
     (IntVal i1, IntVal i2) ->
         return $ IntVal $ i1 + i2
     _ -> throwError "type error in Plus"

eval5 (Abs n e) = do
  tick
  env <- ask
  return $ FunVal env n e

eval5 (App e1 e2) = do
  tick
  val1 <- eval5 e1
  val2 <- eval5 e2
  case val1 of
     FunVal env' n body ->
         local (const $ Map.insert n val2 env')
               $ eval5 body
     _ -> throwError "type error in App"

On an aside there is a composite monad transformer called RWS ( Reader/Writer/State ) which does exactly what your stack does. Using it can simplify the unrolling code quite a bit.
type EvalRWST a = RWS Env [String] Integer a

runEvalRWS :: Env -> Integer -> EvalRWST a -> (a, Integer, [String])
runEvalRWS env st ev = runRWS ev env st


text:
Q: snapshot.ConnectionState is always waiting FLUTTER I am doing a function call onload of the widget but I am getting ConnectionState as waiting always. I tried printing the snapshot values and got this
"AsyncSnapshot<Response<TimesheetData>>(ConnectionState.waiting, null, null, null)"

Heres the screen
  class _TimesheetState extends State<Timesheet> {
  CalendarController _calendarController;
  @override
  initState() {
    _calendarController = CalendarController();
    final DateTime today = DateTime.now();
    _calendarController.selectedDate = DateTime(
      today.year,
      today.month,
      today.day,
    );
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      TimesheetBloc bloc = TimesheetProvider.of(context);
      bloc.fetchTimesheetData();
    });
  }

  List<Meeting> meetings;
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    TimesheetBloc bloc = TimesheetProvider.of(context);
    return Scaffold(
        body: Theme(
      data: ThemeData(primarySwatch: materialColorPrimary),
      child: StreamBuilder<Response<TimesheetData>>(
          stream: bloc.monthlyEventsStream,
          builder: (context, AsyncSnapshot<dynamic> snapshot) {
            print('snapchot:${snapshot}');
            if(snapshot.hasError){
              return Text('error: ${snapshot.hasError}');
            } else{
              if (snapshot.hasData) {
                switch (snapshot.data.status) {
                  case Status.LOADING:
                    return Loading(loadingMessage: snapshot.data.message);
                    break;
                  case Status.COMPLETED:
                    return SfCalendar(
                      dataSource: MeetingDataSource(_getDataSource()),
                      view: CalendarView.month,
                      showNavigationArrow: true,
                      monthViewSettings: MonthViewSettings(
                        showAgenda: true,
                        agendaStyle: AgendaStyle(
                          backgroundColor: Colors.transparent,
                          appointmentTextStyle: TextStyle(
                              color: Colors.white, fontSize: 13, fontStyle: FontStyle.italic),
                          dateTextStyle: TextStyle(
                              color: primaryColor, fontSize: 13, fontStyle: FontStyle.italic),
                        ),
                      ),
                      controller: _calendarController,
                      onTap: _openForm,
                    );
                    break;
                  case Status.ERROR:
                    return Error(
                      errorMessage: snapshot.data.message,
                      onRetryPressed: () => bloc.fetchTimesheetData(),
                    );
                    break;
                }
              }
              return Container();
            }

  }
  ),
    ));
  }

  List<Meeting> _getDataSource() {
    meetings = <Meeting>[];
    final DateTime today = DateTime.now();
    final DateTime startTime =
        DateTime(today.year, today.month, today.day, 9, 0, 0);
    final DateTime endTime = startTime.add(const Duration(hours: 2));
    meetings
        .add(Meeting('Conference', startTime, endTime, primaryColor, false));
    return meetings;
  }

  _openForm(CalendarTapDetails details) {
    //code
    }

  _addTask() {
    if (_formKey.currentState.validate()) {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Task added')));
    }
  }
}

Here's the bloc file
class TimesheetBloc{
  TimesheetRepository _timesheetRepository = new TimesheetRepository();
  StreamController _monthly = StreamController<Response<TimesheetData>>();

  //declare streams
  final _monthlyEvents = BehaviorSubject<Response<TimesheetData>>();

  //get data from streams
  Stream<Response<TimesheetData>> get monthlyEventsStream => _monthlyEvents.stream;

  //set data
  StreamSink<Response<TimesheetData>> get monthlyEventsSink => _monthly.sink;

  //dispose
    _monthlyEvents?.close();
    _monthly?.close();

  }

  fetchTimesheetData() async {
    var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov','dec'];
    monthlyEventsSink.add(Response.loading('Fetching Data.'));
    try {
      SharedPreferences pref = await SharedPreferences.getInstance();
      Map json = jsonDecode(pref.getString('user'));
      var loginDetails = LoginModel.fromJson(json);
      DateTime today = DateTime.now();
      var currentMonth =today.month - 1;
      TimesheetData data =
      await _timesheetRepository.getTimesheetDataMonthly(months[currentMonth], loginDetails.id, loginDetails.token);
      monthlyEventsSink.add(Response.completed(data));
    } catch (e) {
      monthlyEventsSink.add(Response.error(e.toString()));
      print(e);
    }
  }
}

Please check the screenshot

I tried returning the response in fetchTimesheetData but still getting the waiting status.
How can I fix this?


text:
Q: How to make an android app run in background when the screen sleeps? I am developing a Tracking app, which keeps tracks of the user by getting his current location for every 3 secs. I am able to fetch the lat long values when the screen is on. but when the screen sleeps. i am unable to fetch the datas.
CODE:
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if (mCurrLocationMarker != null)
    {
        mCurrLocationMarker.remove();
    }
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    latLngcurrent = new LatLng(location.getLatitude(), location.getLongitude());

    Toast.makeText(context,String.valueOf(latitude)+" "+String.valueOf(longitude), Toast.LENGTH_LONG).show();

    Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

    Log.d("onLocationChanged", "Exit");
    Toast.makeText(this, "exiting LocationChanged ", Toast.LENGTH_SHORT).show();
    }

The above given onLocationChanged method fetches the lat lon values for every 3 seconds. What should i do to make this method run even if the screen sleeps. I have read about Wakelock dont know how to implement it, any help will be appreciated. Thanks in advance.
Note:  The app runs perfectly when multi tasking is done,

A: use job scheduler to get location after every 3 seconds it also works when screen sleep   https://developer.android.com/reference/android/app/job/JobScheduler.html

A: You need to make use of Service to get location updates even if screen sleep or your app is not open.
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class MyLocationService extends Service
{
    private static final String TAG = "MyLocationService";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 3000;
    private static final float LOCATION_DISTANCE = 10f;

    LocationListener[] mLocationListeners = new LocationListener[] {
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };

    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate()
    {
        Log.e(TAG, "onCreate");
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy()
    {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    // create LocationListener class to get location updates
    private class LocationListener implements android.location.LocationListener
    {
        Location mLastLocation;

        public LocationListener(String provider)
        {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location)
        {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);
        }

        @Override
        public void onProviderDisabled(String provider)
        {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }
}

Add MyLocationService into your AndroidManifest.xml also:
<service android:name=".MyLocationService" android:process=":mylocation_service" />

Don't forgot to add below two permissions in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Start Service from an activity:
You can start a service from an activity or other application component by passing an Intent (specifying the service to start) to startService(). The Android system calls the service's onStartCommand() method and passes it the Intent.
Intent intent = new Intent(this, MyLocationService.class);
startService(intent);

Update:
You need to hold partial wake lock to run service even after device screen off.
If you hold a partial wake lock, the CPU will continue to run, regardless of any display timeouts or the state of the screen and even after the user presses the power button.
To acquire wake lock:
PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();

To release it:
wakeLock.release();

A: Try using Service or JobScheduler and implement LocationListener
@Override
public void onLocationChanged(Location location) {
   mLastLocation = location;
   if (mCurrLocationMarker != null)
   {
      mCurrLocationMarker.remove();
   }
   latitude = location.getLatitude();
   longitude = location.getLongitude();
   latLngcurrent = new LatLng(location.getLatitude(),location.getLongitude());

   Toast.makeText(context,String.valueOf(latitude)+" "+String.valueOf(longitude), Toast.LENGTH_LONG).show();

   Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

   Log.d("onLocationChanged", "Exit");
   Toast.makeText(this, "exiting LocationChanged ", Toast.LENGTH_SHORT).show();
}


text:
Q: how to remove the specific inline style using jQuery HTML
<div id="myDiv" style="width:100px;height:100px;transform:translate3d(0,0,0);">
    //Some Content
    </div>

Using jQuery, how to remove the specific inline style i.e transform?

A: You can use css to remove the inline style:
Setting the value of a style property to an empty string removes that property from an element.
$("#myDiv").css("transform","");

DEMO

A: Remove inline style:          $("#myDiv").removeAttr("style");
Adding a new one:             $("#myDiv").removeAttr("style").attr("style","color:red");
or adding a class instead:    $("#myDiv").removeAttr("style").addClass("myDivClass");
PostData: .css() documentation in jQuery.com:

"...Get the value of a style property for the first element in the set
  of matched elements or set one or more CSS properties for every
  matched element..."

.css() don't remove anything... or am I wrong? Maybe you can clear the 'transform' property with something like .css("transform","");

Okay, you can use .css("transform","") to delete the inline css property without disturbing the remaining ones, but be careful: it affects only the inline "style" attribute, and doesn't remove anything coming from assigned classes stored in CSS sheets...
Go here and enjoy with all the options you need:
another Stackoverflow thread about this concern


text:
Q: Jackson XML - Is there a Java built-in type that can be used to deserialize an object containing arrays? Let's say my XML is :
<someObject>
  <someArray>
    <element>111</element>
    <element>222</element>
  </someArray>
</someObject>

Is there a Java built-in Type that I can use to deserialize this XML without requiring custom deserialization code?
For example, if I use a Map<Object, Object>, only one element is kept, the other one is overwritten! :
String xmlStr = "<someObject><someArray><element>111</element><element>222</element></someArray></someObject>";
Map<Object, Object> resultObj = getXmlMapper().readValue(xmlStr, new TypeReference<Map<Object, Object>>(){});
System.out.println(resultObj);

This prints :
{someArray={element=222}}

Is there any Type that Jackson understands and that can handle arrays correctly?

A: In your specific case you could use
new TypeReference<Map<Object, List>>

output : {someArray=[111, 222]}.
I would much prefer to use a proper structure if there is any more complexity to your XML.
@JacksonXmlRootElement(localName = "someObject")
public static class SomeObject {
    @JacksonXmlProperty(localName = "someArray")
    List<String> someArray;

    @Override
    // for testing
    public String toString() {
        return someArray.toString();
    }
}

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper map = new XmlMapper();
    String xmlStr = "<someObject><someArray><element>111</element><element>222</element></someArray></someObject>";
    SomeObject resultObj = map.readValue(xmlStr, new TypeReference<SomeObject>(){});
    System.out.println(resultObj);
}

Output
[111, 222]
Alternatively use an array
@JacksonXmlRootElement(localName = "someObject")
public static class SomeObject {
    @JacksonXmlProperty(localName = "someArray")
    String[] someArray;

    @Override
    public String toString() {
        return Arrays.asList(someArray).toString();
    }
}


text:
Q: Python Django convert timestamp from UTC to local timezone Im am working with Django + DRF, to develop a REST API. I have configured the django settings to work with the timezone support on:
USE_I18N = True
USE_L10N = True
USE_TZ = True

As previously mentioned, my database is receiving and storing data in UTC. My problem is that for some users (each user has their configuration) I must return responses in their time zone (usually in UTC-3 or UTC-2). I was reading several posts and tried several combinations of: astimezone and normalize without succes. I attach my attempts:
timezone_arg = pytz.timezone('America/Buenos_Aires')
print(ts_a, ts_b)
ts_a = ts_a.astimezone(timezone_arg)
ts_b = ts_b.astimezone(timezone_arg)
print(ts_a, ts_b)

utc = pytz.timezone('UTC')
ts_a = timezone_arg.normalize(ts_a.astimezone(utc))
ts_b = timezone_arg.normalize(ts_b.astimezone(utc))
print(ts_a, ts_b)

I am getting the following:
2022-06-17 05:39:09 2022-06-17 05:46:49
2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00
2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00

I understand that django is interpreting that what I am telling it is that the timestamps are already in UTC-3... and it is normalizing them to UTC. But what I want is to cast from UTC to UTC-3. My input/output should be:
2022-06-17 05:39:09 2022-06-17 05:46:49
2022-06-17 02:39:09 2022-06-17 02:46:49

Since I don't only work with the time zone of Argentina (UTC-3), I can't compute a timedelta of 3 hours.. the difference may be different for other clients.
My last resource would be to use the -03:00:00 at the end of the normalized timestamps, and do a subtraction. But I would like to know if there is a more direct and correct way.These timestamps are sent directly to users and must be easy to read.

A: It would be something like that:
from datetime import datetime
from dateutil import tz

from_zone = tz.tzutc()
to_zone = tz.tzlocal()

utc = datetime.strptime('2022-06-17 05:39:09', '%Y-%m-%d %H:%M:%S')

utc = utc.replace(tzinfo=from_zone)

# Convert to local time zone
to_local_time = utc.astimezone(to_zone)

print(utc,to_local_time)


text: Q: Как обрабатывать данные используя node streams? Не могу понять как обрабатывать, работать с данными в чанках. Допустим у меня есть огромный массив с массивами и мне нужно сделать массив с объектами, т.е. нужно как то отлавливать каждый массив и переделывать его в объект . Но как? Если данные рандомно обрываются


text:
Q: Unwanted red lines when the unwind segue is performed I have a view controller, embedded in a navigation controller, which has a button and connects me with another view controller with a button. I have ctrl dragged from the button of the second view controller to the exit in the Storyboard creating an unwind segue. While the unwind segue works as wanted (When I click the button it removes the current view controller and gets me to the first view controller) but once that happens my current view has some red lines for no apparent reason. Why does this happen? Has to do with my Xcode installation or does it have to do with Xcode in general?
I have Xcode 10.1 and although there is nothing fancy in my code here it is anyway:
import UIKit

class PresentedViewController: UIViewController {
    @IBAction func myUnwindAction(unwindSegue: UIStoryboardSegue)
    {
        print("You learned to use unwindSegue")
    }
}


text:
Q: how to use variable in range using vba Hello I have written code for generating graph using vba. everything working correctly ,but problem is i want to use variable for selecting particular column
the code is :
Set x = Range("$CF$2", Range("$CF$2").End(xlDown))
Set y = Range("$CG$2", Range("$CG$2").End(xlDown))
Dim c As Chart
Set c = ActiveWorkbook.Charts.Add
Set c = c.Location(Where:=xlLocationAsObject, Name:=assume)
With c
.ChartType = xlXYScatterLines

' set other chart properties

With .Parent
.Top = Range("cl1").Top
.Left = Range("cl12").Left
.Name = "c"
End With
End With

Dim s As Series
Set s = c.SeriesCollection(1)
With s
.Values = y
 .XValues = x
' set other series properties

End With

I want to use variable COLs in first to line they are
Set x = Range("$CF$2", Range("$CF$2").End(xlDown))
Set y = Range("$CG$2", Range("$CG$2").End(xlDown))

COLs is variable of string

A: I'm not sure I understand, but if you want a Range object based on a string, why not try this:
Option Explicit

Sub TestRange()

    '***** Declare variables
    Dim oX As Range
    Dim sCOLs As String

    '***** Select column
    sCOLs = "A"

    '***** Set Range based on column from sCOLs
    Set oX = Range(sCOLs & "2", Range(sCOLs & "2").End(xlDown))

    '***** Do something with oX
    Debug.Print TypeName(oX)

    '***** Clean up
    Set oX = Nothing

End Sub

You could also try and have the whole range as a string, maybe a bit cleaner code?
Dim sRange as String

sRange = "A2"

Set oX = Range(sRange, Range(sRange).End(xlDown))

A: You could also use Inputbox to have the user click on a certain cell. This then creates a variable "UserRange" which contains the cell reference you can use.
Sub test()

Dim UserRange As Range

Set UserRange = Application.InputBox(Prompt:="Please Select Range", Title:="Range Select", Type:=8)
UserRange.Value = "Test"

End Sub


text:
Q: jQuery/Javascript if css right > go to this css value Can anyone tell me why the conditional in my code is never true?
http://jsfiddle.net/eygLU/2/
Solved:
It's because I was checking a string against a number and needed to use parseInt()

A: You need to parseInt():
$('.zeppelin').css('right') > winWidth

$('.zeppelin').css('right') will return [integer]px. Therefore you are comparing a string type to an integer type.
Try:
parseInt($('.zeppelin').css('right')) > winWidth

Also, as a side note, looking through your code, you have:
'-'+zepWidth

If you wish to invert an integer, multiply it by -1 instead:
(zepWidth*-1)

A: As Curt mentioned, you were missing a parseInt, but you also needed to stop the animation so when you reset it, the div did not fly back accross the screen:
also needed
overflow: hidden

on the html and body to get rid of scroll bar
http://jsfiddle.net/thundercracker/eygLU/4/
EDIT: Also it was not resetting because you didn't have a +"px" after "-"+zepWidth
EDIT: update link


text:
Q: Ping problems with two interfaces, same subnet, direct connections to two separate hosts I have a configuration of a client machine (Ubuntu 14.04.2 LTS) that directly connects to two server machines. The server machines--while on the same subnet--cannot route to each other. Packets must not route between the client's eth1 and eth2, either (i.e., client is not a router) and since there's an act of discovery involved, the routing table cannot be pre-programmed with the serverX IPs.
Below is a crude diagram. eth0 is left out of this picture as it cannot route to the subnet 172.16.37.0/24. There are no firewalls (both iptables and ufw are clean as a whistle).

     client                         server01
+-------------------+          +-------------------+
| 172.16.37.53 eth1-|----------|-eth1 172.16.37.11 |
|                   |          +-------------------+
|                   |               server02
|                   |          +-------------------+
| 172.16.37.54 eth2-|----------|-eth1 172.16.37.12 |
+------------------ +          +-------------------+

The problem that I'm encountering is that ping -I eth2 172.16.37.12 does not work from the client machine. In short, what I observe via tcpdump is:

*

*client:eth2 issues ping-request

*server02:eth1 receives ping-request

*server02:eth1 issues an ARP who-has for 172.16.37.54

*client:eth2 receives the ARP who-has

*ARP never responds (and the arp cache isn't updated)

If I send gratuitous ARPs with arping -A -I eth2 172.16.37.54 from the client, then the observation is thus:

*

*client:eth2 issues ping-request

*server02:eth1 receives ping-request

*server02:eth1 issues ping-reply to client

*client:eth2 receives ping-reply

*ping application never receives packet

When I straced my ping session, it keeps retrying recvmsg; nothing shows up on the socket.
Here's the routing table for the aforementioned observations:

$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.16.187.2    0.0.0.0         UG    0      0        0 eth0
172.16.37.0     0.0.0.0         255.255.255.0   U     0      0        0 eth1
172.16.37.0     0.0.0.0         255.255.255.0   U     0      0        0 eth2
172.16.187.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0

If I add a host route into the routing table for 172.16.37.12 -> eth2, then both ARP resolution and ping operation work as intended. However, I cannot pre-program the host routes since I need to discover the connected machines--all I have are the active interfaces and their subnets.
Packets are not received on eth1 when testing eth2 (I had pretty much all the interfaces being watched). It's also worth noting that this problem does not happen with eth1; it is able to ping -I eth1 correctly without the host route entry (and due to route ordering, the -I option is excessive in this case, but generally I cannot rely on the order of the table).
Why isn't the application (in one case the ARP cache; the other ping) receiving the packets? How can I track down where the data is going? Everything seems to be operating correctly right up until the packet should be delivered to the application.


text:
Q: Ask permissions for facebook app I've developed a facebook app that requires the publish_stream permission to post a dynamically generated image to user's wall.
It functions good, but when a new user wants to use the app, it asks for login and THEN it asks for publish stream permission, and gives them the option to deny that permission and still continue with app.
I'd like to have ONE dialog panel asking for login AND permission at the same time, so if user does not authorize the app to upload photos, then it wont work. I've seen this with other similar apps.
I'm using the following PHP code for this:
$login_url = $facebook->getLoginUrl(
    array(
    'scope'             => 'publish_stream'
    )
);

if (! $facebook->getUser()) {
    echo <<< EOT
<script type="text/javascript">
top.location.href = "$login_url";
</script>;
EOT;

exit;
}

Any help is appreciated.
Thank you!
EDIT:
I'm not talking about users logging in to facebook, but users logging in to use App.
here are some screenshots of the dialogues:
http://imgur.com/a/IxFfV
Thank you again

A: Disable the 'Enhanced Auth Dialog' in your app's advanced settings. The new auth dialog uses two screens, this is what everyone will be eventually migrated to.


text:
Q: CSS get a layer to go over another layer I have this site here http://willruppelglass.com/Categories.php?action=view
as you can see an image cuts off
I need the div contentTextWill to go over rightSideBar is this possible?
Here is my code

A: Move .rightSideBar above the .content in DOM:


text:
Q: Why doesn't binding() find a two-way-binding in an e2e test? The binding() function doesn't seem to find two-way-bindings in e2e tests. Assuming the following bindings:
<input ng-model="username">
<p>{{email}}</p>
<input ng-bind="password">

The following e2e test fails:
...
expect(binding('username')).toMatch('alice');
...
>> Binding selector 'username' did not match.

The following e2e tests succeeds:
...
expect(binding('email')).toMatch('alice@ab.com');
expect(binding('password')).toMatch('abc123');
...

Thx!

A: Please try this way;
<input ng-model="username">

And in your E2E test;
expect(input('username').val()).toMatch('alice');


text:
Q: How do I get the RESTSerializer.extractArray method to work? Copy-pasting both the "payload" and the serializer from the API-documentation I have created the folowing JsFiddle:
http://jsfiddle.net/NQKvy/481/
I get the following error:

Error while loading route: Error: Assertion Failed: You must include an id in a hash passed to push

Any ideas?

A: http://jsfiddle.net/UEaQ4/
Ember doesn't use normalizeHash. I don't why.
I changed payload before pass it to _super
payload = {
  comments: comments.map(function(hash){
    hash.id = hash._id;
    hash.title = hash.comment_title;
    delete hash._id;
    delete hash.comment_title;
    return hash;
  }),
  posts: posts };

and also store comment._id in post instead of comment itself
postCache[comment.post_id].comments.push(comment._id);

and it works.


text:
Q: Understanding the "elements" of this set Suppose $f\in C^3(M)$ where $M \subset \mathbb R^3$ is a $2$-dimensional manifold. For some $s>0$ and $\epsilon>0$ sufficiently small, we define
$A:=\bigg \{x_0+t\frac{\nabla f(x_0)}{|\nabla f(x_0)|}\;,\;0\leq t \leq \frac{\epsilon}{2}\;,\;x_0\in\{f=s\} \bigg \}$
I want to understand what exactly $A$ contains. Intuitively, I realize $A$ as follows:

*

*$+\frac{\nabla f(x_0)}{|\nabla f(x_0)|}$ is the unit normal vector in $x_0 \in \{f=s\}$ pointing to the set $\{f>s \}$

*$x_0$ is some point of the level set $\{f=s \}$
Therefore, I imagine that as we "walk" through $t\frac{\nabla f(x_0)}{|\nabla f(x_0)|}$, the set $A$ includes all level sets starting from $\{f=s\}$ up to distance $\frac{\epsilon}{2}$ from it. Is this correct or am I missing something here?
I would appreciate if somebody could enlighten me here! Many thanks in advance.


text:
Q: oAuth/Gmail from ASP.NET - "The remote server returned an error: (400) Bad Request" I have been banging my head on this for a long time now no avail.
Hoping some fellow SOers can help out.

*

*using oAuth.net library for the Gmail Contacts API

*The request seems well-formed and I have stepped through the requests, and cannot discern anything wrong.

*Tried checking if the timestamp is an issue - it seems that was a common issue on the gmail forums, tried changing to various time-zones, still no luck.
public string WebResponseGet(HttpWebRequest webRequest)
{
    StreamReader responseReader = null;
    string responseData = "";
try
{
    //This is where the exception is thrown
    responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
    responseData = responseReader.ReadToEnd();
}
catch (WebException ex)
{
    Console.WriteLine(ex);
    throw;
}
finally
{
    webRequest.GetResponse().GetResponseStream().Close();
    responseReader.Close();
    responseReader = null;
}

return responseData;

}

A: No real responses. Shutting it down.


text:
Q: ListView Button with link from XML File I'm working on android app that looks like this:
(ListView begin)
Name - Game
Date
Link (Button)

Name2 - Game2
Date2
Link2 (Button)
(ListView end)
that is in a ListView.
So a ListView Elemnt is: Name, Game, Date (TextView) and Link(Button)
All data come from an XML File
So my question:
how can I get the link in the button ? like link1 from XML file to button in ListView Element1 and so on.
checked already some tutorials but can't get it to work with my code:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        String xml = XMLfunctions.getXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);

        if((numResults <= 0)){
            Toast.makeText(Main.this, "...", Toast.LENGTH_LONG).show();
            finish();
        }

        NodeList nodes = doc.getElementsByTagName("result");

        for (int i = 0; i < nodes.getLength(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();

            Element e = (Element)nodes.item(i);
            if(i==0){
                TextView update= (TextView) findViewById(R.id.textView6);
                update.setText("last Update: "+XMLfunctions.getValue(e, "update"));
            } else {

            map.put("name", XMLfunctions.getValue(e, "name")+": " + XMLfunctions.getValue(e, "game") );
            map.put("date", XMLfunctions.getValue(e, "date"));
             mylist.add(map);
            }
        }
        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
                        new String[] { "name", "date" },
                        new int[] { R.id.item_title, R.id.item_date });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);

edit
example of xml which I parse:
<result>
<id>1</id>
<name>test</name>
<game>gamename</game>
<date>27.04</date>
<link>www.google.com</link>
</result>
<result>
<id>2</id>
<name>test2</name>
<game>gamename2</game>
<date>27.04</date>
<link>www.google.com</link>
</result>

and the listplaceholder layout
<ListView
    android:id="@id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="280dp"
    android:drawSelectorOnTop="false" android:scrollbars="horizontal|vertical"/>

and the main layout (layout of the ListView)
<TableLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/item_title"
                android:layout_width="146dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textSize="10dp" />

        </TableRow>
         <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            <TextView
                android:id="@+id/item_date"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textSize="10dp" />
            </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/buttonlink"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="10dp" android:layout_height="fill_parent"
                android:text="Link"
                 />

        </TableRow>

    </TableLayout>

A: I just added a new own Adapter, it works, so if someone is looking for it:
public class DataAdapter extends ArrayAdapter<Data>
        {

            private ArrayList<Daten> items;
            String url;

            public DatenAdapter(Context context, int textViewResourceId, ArrayList<Daten> items) {
                    super(context, textViewResourceId, items);
                    this.items = items;
            }
            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                    View v = convertView;
                    if (v == null) {
                        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(R.layout.list_element, null);
                    }
                    Daten o = items.get(position);

                    url = o.getUrl();
                    if (o != null) {

                            TextView name = (TextView) v.findViewById(R.id.item_title);
                            TextView datum = (TextView) v.findViewById(R.id.item_date);
                            if (name != null) {
                                  name.setText(o.getName()+" - "+o.getSpiel());                            }
                            if(datum != null){
                                  datum.setText("date: "+ o.getDate());

                            }
                    }
                    Button but = (Button) v.findViewById(R.id.buttonlink);

                    but.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View view) {
                        openWebURL(getUrl(position));
                        }
                    });

                    return v;

            }

            private String getUrl(int index) {
                return d.get(index).getUrl();
            }