text:
Q: How to simplify cross-browsing css animation keyframe? If I make a keyframe animation I have to copy it 4 times, and if I want to change value I have to change 4 times each? this is crazy. any ways to simplify it?
@-moz-keyframes ballanim /* Firefox */
    {
        0%   {
            top:0px;
               /* -webkit-animation-timing-function: ease-in;*/
        }

        25%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        50%{
            top:0px;
        }

        75%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        100%{
            top:0px;
        }

    }

    @-webkit-keyframes ballanim /* Firefox */
    {
        0%   {
            top:0px;
               /* -webkit-animation-timing-function: ease-in;*/
        }

        25%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        50%{
            top:0px;
        }

        75%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        100%{
            top:0px;
        }

    }
    @-o-keyframes ballanim /* Firefox */
    {
        0%   {
            top:0px;
               /* -webkit-animation-timing-function: ease-in;*/
        }

        25%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        50%{
            top:0px;
        }

        75%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        100%{
            top:0px;
        }

    }

    @keyframes ballanim /* Firefox */
    {
        0%   {
            top:0px;
               /* -webkit-animation-timing-function: ease-in;*/
        }

        25%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        50%{
            top:0px;
        }

        75%{
            top:20px;
           -webkit-animation-timing-function: ease-in-out;
        }

        100%{
            top:0px;
        }

    }

A: you can use prefix free to simplify your css code. Basically you write code without -webkit- or any other prefixes.
http://leaverou.github.com/prefixfree/

A: No, but you can use a pre-processor like SASS or LESS.
Here's a comparison of the two: CSS-tricks article.
Essentially when you are writing code, you can use variables, which are converted into CSS. So you will be developing with variables, while the css the user gets will be the converted CSS.
Here is a similar question: SASS simplify a mixin with prefixes.


text:
Q: Python3 - Convert enum to different datatypes I'm currently working with an enum of the following type:
class System(Enum):
  FIRST = 1
  SECOND = 2

Now I'd like to be able to do the following:
a = System.FIRST
url = a.getSystemURL()

where the url for the enumeration members FIRST and SECOND are different of course.
I could create a dictionary with the enumeration members as keys and the urls as values, but this won't assure that if I later add an enumeration member I'll remember to add corresponding the dictionary entry.
Is there a clean way to have an enumeration with multiple values for the enumeration members? And to name these different values?
Something like this:
class System(Enum):
  Values = (Value, url, something)
  FIRST = 1, 'https://www.example.com', 42
  SECOND = 2, 'https://www.test.com', 13

A: There is an example like this in the documentation. If the class defines an __init__ method, the enum values will be passed to it as arguments. This means you can define your enum like so:
class System(Enum):
    FIRST = 1, 'https://www.example.com', 42
    SECOND = 2, 'https://www.test.com', 13

    def __init__(self, value, url, something):
        self.value_ = value
        self.url = url
        self.something = something

(Note that value is a special attribute reserved by enums, so I named the attribute value_ to avoid a name clash.)
You can now access these attributes on each enum member:
>>> System.FIRST.url
'https://www.example.com'

A: Both the stdlib Enum and aenum1 easily support your use case (although more work is required for the stdlib version).

stdlib enum 3.4+  (See the docs for __new__ and __init__ explanations.)
import enum
class System(enum.Enum):

    def __new__(cls, *args, **kwds):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

    def __init__(self, url, something):
        self.url = url
        self.something = something

    FIRST = 'https://www.example.com', 42
    SECOND = 'https://www.test.com', 13

aenum -- Usable for both Python 2 and 3 code.  aenum also makes a few things easier -- the above code would be:
import aenum
class System(aenum.AutoNumberEnum):
    _init_ = 'url something'
    FIRST = 'https://www.example.com', 42
    SECOND = 'https://www.test.com', 13

And in use:
--> System.FIRST
<System.First: 1>

--> System.FIRST.url
'https://www.example.com'

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

A: Make the values a namedtuple.
from collections import namedtuple
from enum import Enum

Entry = namedtuple('Entry', ['value', 'url', 'something'])

class System(Enum):
  FIRST = Entry(1, 'https://www.example.com', 42)
  SECOND = Entry(2, 'https://www.test.com', 13)

print(System.FIRST.value.url)
# https://www.example.com

A: Have you tried the code you wrote? It already just works! Of course you don't really have multiple values, you have a single tuple value—but that isn't a problem:
>>> class System(Enum):
...     FIRST = 1, 'https://www.example.com', 42
...     SECOND = 2, 'https://www.test.com', 13
>>> _, url, _ = System.SECOND.value
>>> url
'https://www.example.com'
>>> a = System.FIRST
>>> url = a.value[1]
>>> url
'https://www.example.com'

There are things you can do to make this a little nicer, like using a namedtuple instead of a plain tuple so you can write a.value.url instead of a.value[1], but you've already written something that works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to update a table that's been changed from another client? So I'm using a free web hosting service to test my code out (which is a public messaging board) and when a message is sent to the database table from another computer, where every message is stored, the message can't be seen until I refresh the page. Is there a way to automatically refresh the table when the database table changes?
Here's the code I'm using to display the database table:
<?php
        include_once "includes/database.php";
        $sql = "SELECT * FROM board ORDER BY id DESC";
        $result = mysqli_query($conn, $sql);
        $resultCheck = mysqli_num_rows($result);
        if ($resultCheck > 0) {
            while ($row = mysqli_fetch_array($result)) {
                echo "
";
                echo "" . ($row['timstmp']) . "	";
                echo "" . ($row['user_id']) . "	";
                echo "" . ($row['message']) . "	";
                echo "
";
            }
        }
    ?>

here's a photo of the database table
and here's a photo of the website.
I've tried automatically refreshing the page itself on a timer but that clears text fields that could be in use.


text:
Q: using mapbox to lit element with bundler rollup I would using mapbox on lit element with bundler rollup,I get the following error while importing
Uncaught SyntaxError: The requested module './../../node_modules/mapbox-gl/dist/mapbox-gl.js' does not provide an export named 'Map' (at page-home.ts:3:9)

The way I imported it :
import {Map} from 'mapbox-gl';

link config rollup :
jsbin
Is it possible to use Mapbox in Lit element with bundler rollup ?


text:
Q: Velocity pdf Image not displayed I generated pdf file using velocity templates but i am not able to put images in my pdf.
I've try using external and internal images but the picture still not displaying.
I also have tried this tutorial but still not showing images in generated pdf.

    `File f = new File("D:\\uploadfile\\assets\\test.png");
    FileInputStream fin = new FileInputStream(f);
    byte imagebytearray[] = new byte[(int)f.length()];
    fin.read(imagebytearray);
    String imagetobase64 = Base64.encodeBase64String(imagebytearray);
    fin.close();

    logger.info("data: "+imagetobase64);
    context.put("image", imagetobase64);
    /* now render the template into a StringWriter */
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    /* show the World */

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos = generatePdf(writer.toString());
    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(baos.toByteArray().length);

    return new HttpEntity<byte[]>(baos.toByteArray(), header);`

On vm template i try, but the images still not diplayed

Any help or sugestion?
Thanks


text:
Q: Calculate $\frac{3\sin\alpha+2\tan\alpha}{\cot\alpha}$ if $\cos\alpha=\frac13$
Calculate $\dfrac{3\sin\alpha+2\tan\alpha}{\cot\alpha}$ if $\cos\alpha=\dfrac13$ where $\alpha$ is an acute angle.

So I am trying to simplify the given expressions but I am stuck on $\dfrac{\sin^2\alpha(3\cos\alpha+2)}{\cos^2\alpha}.$ Can you give me a hint?
If we use that $\sin^2\alpha+\cos^2\alpha=1$ we can find $\sin\alpha,\cos\alpha,\tan\alpha,\cot\alpha$ but this is not the most rational approach, I think.

A: $$\dfrac{3\sin\alpha+2\tan\alpha}{\cot\alpha} = \dfrac{3\sin^2\alpha \cos \alpha+2\sin^2\alpha}{\cos^2\alpha} = \dfrac{3(1- \cos^2 \alpha) \cos \alpha+2(1- \cos^2 \alpha)}{\cos^2\alpha}$$
You should be able to conclude.

A: $$
\frac{3\sin x+2\tan x}{\cot x}=(3\sin x+2\frac{\sin x}{\cos x})\cdot\frac{\sin x}{\cos x}=\frac{3\sin^2 x}{\cos x}+\frac{2\sin^2 x}{\cos^2 x}= \\ =\frac{\sin^2 x}{\cos^2 x}(3\cos x+2)=\frac{1-\cos^2 x}{\cos^2 x}(3\cos x+2)=\frac{1-\frac{1}{9}}{\frac{1}{9}}(3\cdot \frac{1}{3}+2)=24
$$

A: Hint : $\dfrac{3\sin\alpha+2\tan\alpha}{\cot\alpha}=\dfrac{3\sin\alpha}{\cot\alpha}+\dfrac{2\tan\alpha}{\cot\alpha}$
But $\dfrac{\sin\alpha}{\cot\alpha}=\frac{1-\cos(\alpha)^2}{\cos(\alpha)}$ and $\dfrac{\tan\alpha}{\cot\alpha}=\frac{1-\cos(\alpha)^2}{\cos(\alpha)^2}$ (why ?)


text:
Q: double division by using two floats? I would like to do a double devision using two floats (It appears that Direct Compute does not support double devision).
Is that possible?
This is what I tried so far (c# code, should be HLSL later):
int count = 7;
double value = 0.0073812398871474;
float f1 = (float)value;
float f2 = (float)((value - f1));
float r1 = f1 / count;
float r2 = f2 / count;
double result = (double)r1 + (double)r2;

0,00105446285765182 (result)
0,00105446284102106 (correct result)
It has to do with the rounding in f1. If value is instead:
 double value = 0.0073812344471474;

Then the result is correct.

A: Calculate reciprocal of count with float division and then improve the precision to full double using Newton-Raphson reciprocal formula.
int count = 7;
double value = 0.0073812398871474;
double r = (double) (1.0f / count); // approximate reciprocal
r = r * (2.0 - count*r); // much better approximation
r = r * (2.0 - count*r); // should be full double precision by now.
double result = value * r;

A:
Is that possible?

Yes, as long as you:

*

*Accept the inevitable loss of precision

*Bear in mind that not all doubles fit into floats in the first place

Update
After reading your comments (double precision is a requirement), my updated answer is:
No.

A: Apparently your arithmetic error is not immediately clear to you. Let me spell it out.
Suppose a double has two parts, the big part and the little part, each with roughly 32 bits of precision.  (This is not exactly how doubles work but it will do for our purposes.)
A float only has one part.
Imagine we were doing it 32 bits at a time but keeping everything in doubles:
double divisor = whatever;
double dividend = dividendbig + dividendlittle;
double bigquotient = dividendbig / divisor;

what is bigquotient? It's a double. So it has two parts. bigquotient is equal to bigquotientbig + bigquotientlittle. Continuing on:
double littlequotient = dividendlittle / divisor;

again, littlequotient is littlequotientbig + littlequotientlittle. Now we add the quotients:
double quotient = bigquotient + littlequotient;

How do we compute that?  quotient has two parts. quotientbig will be set to bigquotientbig. quotientlittle will be set to bigquotientlittle + littlequotientbig. littlequotientlittle gets discarded.
Now suppose you do it in floats. You have:
float f1 = dividendbig;
float f2 = dividendlittle;
float r1 = f1 / divisor;

OK, what is r1? It's a float. So it only has one part. r1 is bigquotientbig.
float r2 = f2 / divisor;

What is r2? It's a float. So it only has one part. r2 is littlequotientbig.
double result = (double)r1 + (double)r2;

You add them together and you get bigquotientbig + littlequotientbig.  What happened to bigquotientlittle?  You've lost 32 bits of precision in there, and so it should come as no surprise that you get innaccuracies 32 bits along the way.  You have not come up with at all the right algorithm for approximating 64 bit arithmetic in 32 bits.
In order to compute (big + little)/divisor, you can't simply do (big / divisor) + (little / divisor). That rule of algebra does not apply when you are rounding during every division!
Is that now clear?

A: So how about something like

result = value * (double)(1f / (float)count);

?
There you're only dividing two floats.  I have more casts in there than needed, but it's the concept that counts.
Edit:
Okay, so you're worried about the difference between the actual and the rounded, right?  so just do it over and over until you get it right!
double result = 0;
double difference = value;
double total = 0;
float f1 = 0;
while (difference != 0)
{
    f1 = (float)difference;
    total += f1;
    difference = value - total;
    result += (double)(f1 / count);
}

...but you know, the easy answer still is "No".  This still doesn't even catch ALL the rounding errors. From my tests it lowers the inaccuracies to 1e-17 at the most, about 30% of the time.

A: In a comment, you say:

Of course there should not be any loss
  of precision. This is why I'm using
  two floats. If I would accept loss of
  precision, then I could just cast two
  float and do the division.

An IEEE-754 single precision value has 24 significant binary digits.  A double precision value has 53 significant digits.  You can't even represent a double precision value as two single precision values without loss of accuracy, much less do arithmetic with such a representation.
That said, it is possible to do a correctly rounded double precision division using only conversions between double and single, double precision subtraction/addition, and single precision operations, but it's pretty complicated if you really want to do it right.  Do you need actual IEEE-754 correct rounding, or just an answer that's correct up to the last bit or two?


text:
Q: Python typing deprecation The latest typing docs has a lot of deprecation notices like the following:
class typing.Deque(deque, MutableSequence[T])
A generic version of collections.deque.

New in version 3.5.4.

New in version 3.6.1.

Deprecated since version 3.9: collections.deque now supports []. See PEP 585 and Generic Alias Type.

What does this means? Should we not use the generic type Deque (and several others) anymore? I've looked at the references and didn't connect the dots (could be because I'm an intermediate Python user).

A: It means that you should be transitioning to using built-in types / types from the standard library instead of the ones provided by typing. So for example collections.deque[int] instead of typing.Deque[int]. The same for list, tuple, etc. So tuple[int, str] is the preferred way.

A: See PEP585 and Generic Alias Type.
Changes in Python 3.9 remove the necessity for a parallel type hierarchy in the typing module, so that you can just use collections.deque directly when annotating a deque-like type.
For example, it means that annotating a deque of ints like
def foo(d: typing.Deque[int]):
    ...

Should be changed to:
def foo(d: collections.deque[int]):
    ...


text:
Q: Can I put a horizontal line in a combo box or list control? I'm building a Windows Form that includes a combo box control, and I wanted to put a horizontal line between certain items.  I've seen this done in other contexts using a hyphen in an item list, but a hyphen doesn't do this in this case. I don't know if a horizontal line is even possible with this control.  What I am trying to accomplish is something like:
Item 1
Item 2
Item 3
_________________
Item A

I suppose I could simply put a line of hyphens in there, but a nice clean line would be better if it could be done.

A: Unfortunately, I have not been able to find anything that comes standard in the control with "clean" solutions yet.
I found something where you can draw the line between every item at this link.  With some fancy work you may be able to find a way of making it draw the line only when you want to.
Alternatively, there is a CodeProject combobox that includes line separators.


text:
Q: Vs Code will not autocomplete from a python file or library after appending the path Suppose I have two python files, funcs.py and current.py and that both of these files are inside the same directory. If I add from funcs import * inside current.py then VS Code will recognize all of the functions that I have in funcs.py and will also code complete for them.
For example, if within funcs.py, I have the following:
def some_function():
    # body of the function

then when I am working on current.py, VS Code will autocomplete some_function for me in the sense where if I start typing some_f... then some_function will be included in the list of suggestions that VS Code gives me.
Now suppose that current.py is inside directory_1 and that funcs.py is inside directory_2 and that inside current.py I add the following lines:
from sys import path
path.append(path_to_directory2)

Then if I am working within current.py, I can successfully import funcs.py and use the functions, but VS Code will now not autocomplete any of the functions imported from funcs.py like it did when both current.py and funcs.py were in the same directory.
Is there a way to have VS Code auto complete these functions if the two files are in different directories?

A: For your question, I offer two answers.

*

*If you want to get automatic completion without needing it to be run successfully. You can add "python.autoComplete.extraPaths": [] to your settings.json and specify the path manually.

*If you want to run the code successfully without changing the original code. You can try .env file.

Firstly, create the .env file under your workspace.
Secondly, add python.envFile": "${workspaceFolder}/.env", to your settings.json.
Thirdly, add the folder you need to import as an environment variable to the .env file. For example, PYTHONPATH=C:/.


text:
Q: Third degree Diophantine equation I saw an exercise which was meant to find integers all integers $m,n$ satisfying $2m^2 + 5n^2 = 11(mn-11)$. I found them using the factorization $(m-5n)(2m-n)=-11\cdot 11$. However, what kind of methods there are to solve the original problem, find all $(m,n)\in\mathbb{Z}\times\mathbb{Z}$ satisfying $2m^2+5n^3=11(mn-11)$? I haven't solved many cubic Diophantine equations so I was just wondering if there is some birational transformation to convert the equation to a Weierstrass form of an elliptic curve.

A: The equation $2y^2+5x^3=11(xy−11)$ describes an elliptic curve. Given any elliptic curve, you can perform a change of variables to put it into Weierstrass form, and if the field of definition has characteristic different from 2 or 3, you can even put it into the form $y^2 = x^3 + ax + b$. In this particular case, to find the transformation is easy: first scale $x$ and $y$ to get rid of make the coefficients of $x^3$ and of $y^2$ equal to 1. Then write $y' = y +  \alpha x$ to get rid of the $xy$-term. This will introduce an $x^2$ term. So now, translate $x$ to get rid of the $x^2$ term (I haven't actually done the computation).
An important thing to note is that while the notion of rational points does not depend on the model over $\mathbb{Q}$ that you are working with (as long as you only change variables over $\mathbb{Q}$), the notion of integral points does depend on the integral model. A theorem of Siegel says that on any Weierstrass model of an elliptic curve, there are only finitely many integral points, and there are bounds on their height in terms of the coefficients of the model. But as far as I know, to actually find the points comes down to brute force methods: e.g. if you manage to compute generators of the Mordell-Weil group, i.e. of the group of the rational points, and the torsion subgroup, then you just check all possible linear combinations up to the given bound. There are better methods using elliptic logarithms, but they are theoretically more involved.
Edit: some more info on your concrete curve:
To get a Weierstrass model you can replace $y$ by $y'/20$ and $x$ by $-x'/10$ in the original equation, resulting in $y'^2+11x'y' = x'^3 - 2^35^211^2$, confirming your hint. The elliptic curve has rank 1, as you say, and no torsion. The point $P=(22,-88)$ generates all the rational points on the curve under the group law. Integral solutions of the original equation correspond to points on the Weierstrass model with integral $x$-coordinate divisible by 10 and integral $y$-coordinate divisible by 20 (see our transformation). So the naive way of ruling out integral solutions to the original equation is to check all multiples of the generator $P=(22,-88)$ under the group law up to the given bound and convince yourself that no point satisfies the divisibility criteria. However, the bound of Baker, referred to in the wikipedia article, is huge and the computation might not actually be feasible. A possibly more promising approach is to write down the polynomial that computes $Q\mapsto Q\oplus P$ and see whether this operation always introduces higher and higher denominators that never cancel the numerators.


text:
Q: Filtering NSArray of dictionaries in Swift I have an array of dictionaries that was pulled from a RESTful API. I currently am trying to filter out the data as needed where the "domain" is equal to "youtube.com".
How can I filter this out? I've looked into
results.filter({
    $0["domain"] != "youtube.com"

but not sure how to go deeper to get it to work.

A: Or, you can use Swift array, casting theJSON to [[String: AnyObject]] rather than NSMutableArray. Then, you don't have to cast results. And then you can use filter.
In Swift 1.2, that might be:
let task = session.dataTaskWithURL(url) { data, response, error in
    if error != nil || data == nil {
        print(error)
        return
    }

    var parseError: NSError?
    if let resultObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0), error: &parseError) as? [[String: AnyObject]] {
        let results = resultObject.filter() { ($0["data"]?["domain"] as? String) != "youtube.com" }
        dispatch_async(dispatch_get_main_queue()) {
            // use results here
        }
    } else {
        print(parseError)
        return
    }

}
task.resume()

Or, in Swift 2:
let task = session.dataTaskWithURL(url) { data, response, error in
    guard data != nil && error == nil else {
        print(error)
        return
    }

    do {
        let resultObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String: AnyObject]]
        let results = resultObject?.filter() { ($0["data"]?["domain"] as? String) != "youtube.com" }
        dispatch_async(dispatch_get_main_queue()) {
            // use results here
        }
    } catch let parseError {
        print(parseError)
    }
}
task.resume()}

A: use
func filteredArrayUsingPredicate(_ predicate: NSPredicate) -> [AnyObject]

to filter an NSArray instance.


text:
Q: CSS background image alt attribute This is one I have not had to tackle before. I need to use alt tags on all images in a site including those used by CSS background-image attribute.
There is no CSS property like this as far as I know, so what is the best way to do this please?

A: The general belief is that you shouldn't be using background images for things with meaningful semantic value so there isn't really a proper way to store alt data with those images. The important question is what are you going to be doing with that alt data? Do you want it to display if the images don't load? Do you need it for some programmatic function on the page? You could store the data arbitrarily using made up css properties that have no meaning (might cause errors?) OR by adding in hidden images that have the image and the alt tag, and then when you need a background images alt you can compare the image paths and then handle the data however you want using some custom script to simulate what you need. There's no way I know of to make the browser automatically handle some sort of alt attribute for background images though.

A: This article from W3C tells you what they think you should do
https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage
and has examples here
http://mars.dequecloud.com/demo/ImgRole.htm
among which

Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:

  Connect via Facebook

.fb_logo {
  height: 37px; width: 37px;
  background-image: url('../gfx/logo-facebook.svg');
  color:transparent; overflow:hidden; /* hide the text */
}

A: In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:

  ...

The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.

A: The classical way to achieve this is to put the text into the div and use an image replacement technique.

Your alt text

with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:
/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

A: I think you should read this post by Christian Heilmann. He explains that background images are ONLY for aesthetics and should not be used to present data, and are therefore exempt from the rule that every image should have alternate-text.
Excerpt (emphasis mine):

CSS background images which are by definition only of aesthetic value
  – not visual content of the document itself. If you need to put an
  image in the page that has meaning then use an IMG element and give it
  an alternative text in the alt attribute.

I agree with him.

A: Here's my solution for Immediate fix:
Once the background image is removed the alt text will be visible from Img tag.

.alt-image {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
}

.background-image{
background:url("https://www.w3schools.com/images/picture.jpg") no-repeat;
width:100%;
height:500px;
position:relative;
}

A: Here's my solution to this type of problem:
Create a new class in CSS and position off screen. Then put your alt text in HTML right before the property that calls your background image. Can be any tag, H1, H2, p, etc.
CSS

HTML

put your alt text here

A: Background images sure can present data!  In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.
It is quite common for hotel listings icons to display amenities.  Imagine a page which listed 50 hotel and each hotel had 10 amenities.  A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster.  But how do you implement ALT tags for these images? Example site.
The answer is that they don't use alt text at all, but instead use the title attribute on the containing div.
HTML

CSS
.hotwire-fitness {
    float: left;
    margin-right: 5px;
    background: url(/prostyle/images/new_amenities.png) -71px 0;
    width: 21px;
    height: 21px;
}

According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute
Title

Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:

alt

The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your website and its visitors in the following common situations:

*

*nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images

*some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page

*search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.

A: As mentioned in other answers, there is no (supported) alt attribute for a div tag only for the img tag.
The real question is why you need to add the alt attribute to all background images for the site? Based on this answer, it will help you determine which route to take in your approach.
Visual/Textual: If you are simply attempting to add a textual fall back for the user if the image fails to load, simply use the title attribute. Most browsers will provide a visual tool tip(message box) when a user hovers over the image, and if the image is not loaded for whatever reason, it behaves the same as an alt attribute presenting text when image fails. This technique still allows for the site to speed up load times by keeping images set to backgrounds.
Screen Readers: The middle of the road option, this varies because technically keeping your images as backgrounds and using the title attribute approach should work as hinted above, "Audio user agents may speak the title information in a similar context." However this is not guaranteed to work in all cases, including some readers may ignore it all together. If you end up opting for this approach, you can also try adding in aria-labels to help ensure screen readers pick these up.
SEO/Search Engines: Here is the big one, if you were like me, you added your background images, all was good. Then months later the customer(or maybe yourself) realized that you are missing out on some prime SEO gold by not having alt's for your images. Keep in mind, the title attribute does not have any weight on search engines, from my research and as mentioned in an article here: https://www.searchenginejournal.com/how-to-use-link-title-attribute-correctly/. So if you are aiming for SEO, then you will need to have an img tag with the alt attribute. One possible approach is to just load very small actual images on the site with alt attributes, this way you get all the SEO and don't have to readjust the existing CSS in place. However this may lead to additional load time depending on the size and google does indeed look at the images path when indexing. In short if you are going this route, just accept what has to be done and include the actual images instead of using backgrounds.

A: It''s not clear to me what you want.
If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:
IMG:before { content: attr(alt) }

If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.
Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?

A: You can achieve this by putting the alt tag in the div were your image will appear.
Example:


text:
Q: Android: java equivalent of android:button Attribute? Is there a pure-java way of setting the android:button attribute? My use case is I have some radio buttons with custom on/off images. They are currently in xml, but for several reasons I want their creation to be done in pure java. Currently the android:button references a <selector> xml file:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/red_down_full" />
    <item android:drawable="@drawable/red_down" />
</selector>

Is there any way to either

*

*reference the <selector> xml file in java

*skip the <selector> entirely and just set the state_checked image in java?

A: Yes, you can set the xml image selector via code. If you want to set the selector on your RadioButton you have to call its setButtonDrawable(idOfYourSelector).
The code will be like this:
((RadioButton)findViewById(R.id.yourRadioButton)).setButtonDrawable(R.drawable.yourSelector);

If you want to set only the image you used for state_checked, then you need to supply the id of your state_checked image on setButtonDrawable(idOfYourImage) instead the id of your selector. In your case it will be:
((RadioButton)findViewById(R.id.yourRadioButton)).setButtonDrawable(R.drawable.red_down_full);

To ensure that it will not overlap the label of your RadioButton, you have to know the width of your drawable. Then set the left padding of your RadioButton depending on the width of your drawable. This will ensure the image for your RadioButton will not overlap its label.


text:
Q: Python DocString (Google Style): How to document class attributes? I have this small example:
"""Sandbox module"""

class Toto:
    """
    This class is an example

    Attributes:
        class_attribute (str): The class attribute #Unresolved reference
        instance_attribute (str): The instance attribute #OK
    """

    class_attribute = ""

    def __init__(self):
        self.instance_attribute = ""
        pass

This triggers an unresolved reference warning
How should I properly document the class attribute ?

A: Assuming you would like to use napoleon to render your docstrings into docs, the sphinx developers are working towards a way to add custom sections to class-level docstrings (see Issue #33).
Currently, in the Google Style Docstrings Example, the class ExamplePEP526Class example states

If the class has public attributes, they may be documented here
in an Attributes section and follow the same formatting as a
function's Args section. If napoleon_attr_annotations
is True, types can be specified in the class body using PEP 526
annotations.

PEP 526 added variable annotations to type hints. Hence, your code could now be written:
"""Sandbox module"""

class Toto:
    """ This class is an example

    Attributes:
        class_attribute (str): (class attribute) The class attribute
        instance_attribute (str): The instance attribute
    """

    class_attribute: str = ""

    def __init__(self):
        self.instance_attribute: str = ""

For one thing, it seems you forgot to put the type hint str after class_attribute when defining it, so mypy (if using an external type checker) probably couldn't discover its type.
Ironically, the reverse situation would have worked: in napoleon version 3.4, if napoleon_attr_attributes is set to True, then

If an attribute is documented in the docstring without a type and has an annotation in the class body, that type is used.

Second, the pass at the end of your __init__ method is allowed, but unnecessary since you define instance_attribute there.
I mention Issue #33 because, personally, I would rather call the heading "Class Variables" as "Attributes" by itself doesn't distinguish between instance vs. class attributes/variables. For the time being, you may want to put your own notation in the attribute description like I have done.
For me, I either have fewer class attributes than instance attributes or none at all, so I only note if an attribute is a class attribute (otherwise, it is an instance attribute). That way, I don't have to write (instance attribute) next to all my instance attributes. Alternatively, you could try putting class in the parentheses with the type the same what that optional is listed:
class_attribute (str, class): The class attribute

I'm not sure if that will work or break. If it breaks, it would certainly be nice to have added to the docstring syntax in the future (I think this looks cleaner).
Lastly, you could document the class variable as an attribute docstring as defined in PEP 257 as well as this SO answer by putting a docstring directly underneath the assignment like so:
"""Sandbox module"""

class Toto:

    class_attribute: str = ""
    """class_attribute (str): (class attribute) The class attribute"""

    def __init__(self):
        """ This class is an example

        Attributes:
            instance_attribute (str): The instance attribute
        """
        self.instance_attribute: str = ""

A: Try this:
"""
    Sandbox module
    ~~~~~~~~~~~~~~
"""

class Toto:
    """This class is an example

    Attributes:
        instance_attribute (str): The instance attribute #OK
    """

    #: str: The class attribute #Unresolved reference
    class_attribute = ""

    def __init__(self):
        self.instance_attribute = ""
        pass

This works fine for me using sphinx.


text:
Q: Python API setup problem with CPLEX 20.1.0 An error was shown when I try to set up the Python API for CPLEX. The verison of CPLEX is 20.1.0 and the python version in its installation package is 3.7 and 3.8. I have installed Python 3.7.0 and operate following the answer and the official instruction.
When it was about to completed, I received an error Exception: this 'cplex' package (version 20.1.0.0) is not compatible with this version of Python: expected 3.8 but got 3.9
My Python version is like this:

C:\>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

But I haven't installed Python 3.9 and I've checked I don't have this version on my computer. Here is the error information:

C:\Program Files\IBM\ILOG\CPLEX_Studio201\cplex\python\3.8\x64_win64>py setup.py install
Traceback (most recent call last):
  File "C:\Program Files\IBM\ILOG\CPLEX_Studio201\cplex\python\3.8\x64_win64\setup.py", line 91, in <module>
    main()
  File "C:\Program Files\IBM\ILOG\CPLEX_Studio201\cplex\python\3.8\x64_win64\setup.py", line 72, in main
    check_version()
  File "C:\Program Files\IBM\ILOG\CPLEX_Studio201\cplex\python\3.8\x64_win64\setup.py", line 45, in check_version
    raise Exception(
Exception: this 'cplex' package (version 20.1.0.0) is not compatible with this version of Python: expected 3.8 but got 3.9

Please let me know your suggestions~ Thank you so much! ;-)


text:
Q: dotnet Core command on mac error: "No such a file or directory" I'm working with visual studio 2019 for mac and Im trying to create an API dotnet CORE project, but I have some issues at execute this command
dotnet ef dbcontext Scaffold "ConnectionString" Microsoft.EntityFrameworkCore.SqlServer -o Models -c GoParkingContext

This is the error I get:
System.ComponentModel.Win32Exception (2): No such file or directory
   at System.Diagnostics.Process.ForkAndExecProcess(String filename, String[] argv, String[] envp, String cwd, Boolean redirectStdin, Boolean redirectStdout, Boolean redirectStderr, Boolean setCredentials, UInt32 userId, UInt32 groupId, UInt32[] groups, Int32& stdinFd, Int32& stdoutFd, Int32& stderrFd, Boolean usesTerminal, Boolean throwOnNoExec)
   at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Microsoft.EntityFrameworkCore.Tools.Exe.Run(String executable, IReadOnlyList`1 args, String workingDirectory, Boolean interceptOutput)
   at Microsoft.EntityFrameworkCore.Tools.Project.FromFile(String file, String buildExtensionsDir, String framework, String configuration, String runtime)
   at Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute()
   at Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.<Configure>b__0()
   at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[] args)
   at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
No such file or directory

This is the csproj file:

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.4">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.4">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Models\" />
  </ItemGroup>
</Project>

I'm looking a lot on the internet but I don't get the solution.
Appreciate help

A: I also had this issue and the solution was to create a symbolic link from dotnet binary to /usr/bin/dotnet


text:
Q: Как сделать плавное перемещение бегунка между шкалами

$(document).ready(function() {
  $("#slider").slider({
    min: 0,
    max: 2000,
    step: 1000,
    value: 0,
    animate: 'slow',
    range: "min"
  });
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

слишком резко он переходить между шкалами

A: Свойство animate в jQuery UI Slider позволяет анимировать бегунок только при клике на шкале. Но вот таким небольшим трюков можно добавить анимацию при перемещении бегунка мышью.

$("#slider").slider({
  min: 0,
  max: 2000,
  step: 1000,
  value: 0,
  animate: 'slow',
  range: "min"
});

$('#slider span').on('mousedown mouseup', function() {
  $(this).closest('#slider').toggleClass('animated');
});
#slider.animated .ui-slider-handle {
  transition: left 0.5s linear;
}

#slider.animated .ui-slider-range {
  transition: width 0.5s linear;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />


text:
Q: Revit Subtransaction Statement error I have having a problem with this statement:
SubTransaction subTransaction = new SubTransaction(doc);
if (subTransaction.Start() == 1)

A: Based on the error message, the problem is with the if statement. Try this instead:
if (subTransaction.Start() == TransactionStatus.Started) { ... }

In .NET, enum values need to be cast to int first, if you want to compare them to an int. And you probably don't want to be doing that anyway, because that just obscures the value with a magic number.


text:
Q: Product of bounded sequence Suppose that the series $\sum_{n=0}^\infty{a_n}$ is convergent and all of its terms are positive.  If the sequence ${b_n}$ is bounded, can we conclude that $\sum_{n=0}^\infty{a_n}{b_n}$ is absolutely convergent?

A: If $|b_n|\leq B$ for all $n$, then
$$|a_nb_n|=a_n|b_n|\leq Ba_n$$
for all $n$ since $a_n>0$. So what can you say about $\sum_n|a_nb_n|$?

A: If the first is convergent and all $a_n$ are positive then it is abs convergent. This property is preserved when multiplying by uniformly bounded numbers.


text:
Q: Spherical Distance in JavaScript I need to find the Spherical Distance of two coordinates using Javascript. I am using Wolfram a lot for this project and found this formula d=cos^(-1)(P·Q) [reference: http://mathworld.wolfram.com/SphericalDistance.html]. So I know that P·Q is the dot product of the two coordinates in question. This leads to finding the dot product which I found as  DotProduct = (x1*x2 + y1*y2 + z1*z2) [reference: http://en.wikipedia.org/wiki/Dot_product]. So I put together the following method and get NaN (Not a Number) every time.
        function ThreeDimensionalDistance(x1,y1,z1,x2,y2,z2){

            return Math.acos(x1*x2 + y1*y2 + z1*z2);

        }

Here are two sets of sample data I use and I can't figure out why I get NaN. Am I missing something small, do I need to convert my numbers to something for them to work with arc cos? Thank you in advance for any help.
Sample 1
X:-1.7769265970284516,Y:-5.129885707200497,Z:-2.554761143401265
X:-0.8336414256732807,Y:-1.9876462173033347,Z:5.599491449072957
Distance: NaN
Sample 2
X:-0.8336414256732807,Y:-1.9876462173033347,Z:5.599491449072957
X:0.8447772905770565,Y:4.252407300473133,Z:4.147696165367961
Distance: NaN

A: I've done some math, so try the following out:
function threeDimensionalDistance(x1, y1, z1, x2, y2, z2) {
    // Assume that the points are on the same sphere
    var radius = Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1);

    // Calculate normalized spherical distance
    var dotProduct = x1 * x2 + y1 * y2 + z1 * z2;
    var normalizedDistance = Math.acos(dotProduct / (radius * radius));

    // Calculate actual distance
    var distance = normalizedDistance * radius;

    return distance;
}

One minor change that I made was renaming your method to begin with a lowercase letter, to follow standard JavaScript style guidelines.


text:
Q: Split and then Joining the String step by step - C# Linq Here is my string:
www.stackoverflow.com/questions/ask/user/end
I split it with / into a list of separated words:myString.Split('/').ToList()
Output:
www.stackoverflow.com
questions
ask
user
end

and I need to rejoin the string to get a list like this:
www.stackoverflow.com
www.stackoverflow.com/questions
www.stackoverflow.com/questions/ask
www.stackoverflow.com/questions/ask/user
www.stackoverflow.com/questions/ask/user/end

I think about linq aggregate but it seems it is not suitable here. I want to do this all through linq

A: Linq with side effect:
  string prior = null;

  var result = "www.stackoverflow.com/questions/ask/user/end"
    .Split('/')
    .Select(item => prior == null
       ? prior = item
       : prior += "/" + item)
    .ToList();

Let's print it out
  Console.WriteLine(string.Join(Environment.NewLine, result));

Outcome:
www.stackoverflow.com
www.stackoverflow.com/questions
www.stackoverflow.com/questions/ask
www.stackoverflow.com/questions/ask/user
www.stackoverflow.com/questions/ask/user/end

A: Linq without side effects ;)
Enumerable.Aggregate can be used here if we use List<T> as a result.
var raw = "www.stackoverflow.com/questions/ask/user/end";

var actual =
    raw.Split('/')
       .Aggregate(new List<string>(),
                 (list, word) =>
                 {
                     var combined = list.Any() ? $"{list.Last()}/{word}" : word;
                     list.Add(combined);
                     return list;
                 });

A: You can try iterating over it with foreach
var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
string full = "";
foreach (var part in splitted)
{
    full=$"{full}/{part}"
    Console.Write(full);
}

Or use linq:
var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
var list = splitted.Select((x, i) => string.Join("/", a.Take(i + 1)));

A: without Linq write below code,
var str = "www.stackoverflow.com/questions/ask/user/end";
        string[] full = str.Split('/');
        string Result = string.Empty;

        for (int i = 0; i < full.Length; i++)
        {
            Console.WriteLine(full[i]);

        }
        for (int i = 0; i < full.Length; i++)
        {
            if (i == 0)
            {
                Result = full[i];
            }
            else
            {
                Result += "/" + full[i];
            }
            Console.WriteLine(Result);
        }


text:
Q: interpolate after doing outlier using cubic or spline method I have a problem where i use pandas.core.series.Series.interpolate with cubic method and it's fill everything except the first and the last index
Here is my code :
   train = data.iloc[:, column_no-1].dropna()
   train = outlier(train, lower=lo, upper=hi)
   train = train.interpolate(method='cubic')

I tried to use scipy.interpolate but it must input both x and y so what is x and y and will it's work for my case.
Any recommendation of how to do it.
Thank you for your consideration.


text:
Q: How do I change my wordpress image sizes? I upload images around 500x500kb (vary slightly as I resize with a percentage). Wordpress is set to create thumbnails at 150x150.
However, I'm getting 'serve scaled images' errors for two file sizes (dimensions added to end of file title) that are begin resized. One is 272 x 148 and the other is 160x160, yet these sizes aren't in Wordpress media settings. I'm guessing they are theme-specific.
But, as these files appear to be created automatically, how do I set it up so that files are created with the dimensions that are obviously needed by my theme.
And, how does my theme know which version to grab?
Thanks!

A: Adding new image size
You are looking for Wordpress add_image_size function.

Registers a new image size. This means WordPress will create a copy of the image with the specified dimensions when a new image is uploaded.

In your case:
add_image_size('your-custom-size-name', 272, 148, true);

More info on codex: http://codex.wordpress.org/Function_Reference/add_image_size
New image size in theme
Your theme grabs the image size you ask for with the function get_post_image_thumbnail.
get_the_post_thumbnail($post_id, 'your-custom-size-name');

Resizing existing images
If you've already uploaded some images, you may want to adjust them to the new dimensions automatically. There are few plugins that do so, for example Regenerate thumbnails.

Also, you may want to look to all-in-one tutorial on TutsPlus I've found while googling for the plugin.


text:
Q: Contents of `Label` in `ListView` are not Showed I would like to edit the MAUI initialized file to do the following

*

*add an object to the BindingContext in MainPage.xaml.cs each time a Button is clicked

*display the BindingContext using a ListView

In doing so, the above problem occurred. Specifically, the image below is what happened.

The code is as follows, we created Meeting.cs and AllMeetings.cs as Models.
MainPage.xaml.cs
namespace App.Views;

using App.Models;

public partial class MainPage : ContentPage
{
    int count = 0;

    public MainPage()
    {
        InitializeComponent();
        BindingContext = new Models.AllMeetings();
    }

    private void OnCounterClicked(object sender, EventArgs e)
    {
        count++;

        if (count == 1)
            CounterBtn.Text = $"Clicked {count} time";
        else
            CounterBtn.Text = $"Clicked {count} times";

        SemanticScreenReader.Announce(CounterBtn.Text);

        ((Models.AllMeetings)BindingContext).Add_Meeting(new Models.Meeting() { Name = "foo" });
    }
}

MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App.Views"
             x:Class="App.Views.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                x:Name="CounterBtn"
                Text="Click me"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

            <ListView ItemsSource="{Binding Meetings}" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Label Text="{Binding Name}" />
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

AllMeetings.cs
using System.Collections.ObjectModel;

namespace App.Models;

internal class AllMeetings
{
    public ObservableCollection<Meeting> Meetings { get; set; } = new ObservableCollection<Meeting>();

    public void Add_Meeting(Meeting meeting)
    {
        this.Meetings.Add(meeting);
    }

}

Meeting.cs
namespace App.Models;

internal class Meeting
{
    public string Name { get; set; };
}

When I wrote this code, no characters were output as shown in the above image, so the same thing happened when I changed the contents of ListView in MainPage.xaml as follows.
            <ListView ItemsSource="{Binding Meetings}" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Label Text="hoge" />
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>


text:
Q: Performance Counter - Rate per minute type? I have a service that processes relatively "expensive" requests. The average request rate is expected to be around 5-10 per minute. I would like to be able to monitor this rate with a custom performance counter, but all the available counter types seem to be geared toward much more frequently occurring events.
What would be the best way to expose this rate through a performance counter? Perhaps I could just track the total number of events that have occurred, together with the total time elapsed, and then calculate the average and code and expose it through a NumberOfItems32? What seems a bit weird about that is that it wouldn't use the same "averaging window" as the properly managed counters.

A: "What would be the best way to expose this rate through a performance counter? Perhaps I could just track the total number of events that have occurred, together with the total time elapsed, and then calculate the average and code and expose it through a NumberOfItems32? What seems a bit weird about that is that it wouldn't use the same "averaging window" as the properly managed counters."
You have your solution right there.  Keeping track of the number of items and the time is the only way to get the average you're looking for.
http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx


text:
Q: Reading Audio file in C and forwarding over bluetooth to play in Android Audio track What I am Trying to do : Reading .wav file in C(linux) ,forwarding buffer data through bluetooth rfcomm socket , receiving buffer in android and then giving buffer to Audio Track to play.(Need android application to play audio streaming)
code :
1- C-code for rfcomm socket creation Ccode for rfcomm socket
2 - C-code for forwarding data
    FILE *fp;
    char buffer[1024];
    fp = fopen("feelgood.wav","r"); //for audio track use reading .wav file
    while(i=fread(buffer, sizeof(buffer),1, fp) > 0){
        status=write(bluetooth_socket, buffer,strlen(buffer));
        usleep(100000);
    }

3- Android code for reading from socket is something like this:
//Audio Track initialization for Streaming
AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC,44100,AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_8BIT,10000, AudioTrack.MODE_STREAM);
track.play();

//Receiving data from socket
byte[] buffer = new byte[1024];
int bytes;
bytes = socket.getInputStream().read(buffer);
track.write(buffer, 0,bytes);

Problem : Actually problem I am not getting why Audio track is not playing properly(hint of audio music with lot of noise is heard).How to listen noisefree audio on Android application part with this approach .Is there audio track implementation problem or buffer problem.
Related question(Receive audio via Bluetooth in Android) but cannot follow a2dp approach on Android as sink.


text:
Q: Present perfect progressive or simple
I shall  be  exchanging my house in 2 months, I have bought the plane ticket and planned the stay but  I am a bit worried because I have not  received any  further infos for a long time from the person I am exchanging with.

Can I use I have  not been receiving instead of received because it is ongoing situation and I'd like to emphasize the duration
I don't think so because if I use the progressive it means that before I received infos from the person very often which was not the case. Am I right?


text:
Q: How to remove commas from numeric values in a string with other commas? I am working with an array that contains account statement. I want to be able to remove commas from numeric values in order to be able to explode with comma without loosing vital values.
For example, my array contains indexes like:
26 => 20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5,000","","1,316.01"

27 => 27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1,206.81"

I want to remove the comma in "5,000" and other monetary values without removing the commas between each strings, so that the output will look like:
26 => 20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5000","","1316.01"

27 => 27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1206.81"

A: You can use foreach your array and explode by comma then replace "," every array then check if it is number or not
foreach array then explode string by comma
$stringArray=explode(",",$str)

then replace "," every $stringArray
$CheckNumber= str_replace(',', '', $string);

and check if it is number by:
if (is_numeric($CheckNumber))
   $stringArray[i]=$CheckNumber;

at the end join array
join(",",$stringArray);

A: You could also use array_map with preg_replace_callback and as the pattern you could use:
"\d{1,3}(?:,\d{3})+\.\d{2}"

*

*"\d{1,3} Match " followed by 1-3 digits

*(?:,\d{3})! Repeat 1+ times matching a comma and 3 digits

*\.\d{2}" Match a dot and 2 digits followed by "
Regex demo | Php demo
In the callback of preg_replace_callback replace the comma with an empty string and return the match.
For example:
$atm = array(
    '26' => '20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5,000","","1,316.01"',
    '27' => '27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1,206.81"'
);

$atm = array_map(function($x) {
    return preg_replace_callback('/"\d{1,3}(?:,\d{3})+\.\d{2}"/', function($m) {
       return  str_replace(',', '', $m[0]);
    }, $x);
}, $atm);

print_r($atm);

Result:
Array
(
    [26] => 20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5,000","","1316.01"
    [27] => 27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1206.81"
)


text:
Q: Word Addressable Memory For a 32 bit word addressable memory, the word has size of 4 bytes.
If I try to store a data structure uses less than 4 byte memory, say 2 bytes. Is the remaining 2 bytes wasted?
Should we consider the word size when we decide what data structure to use?
Got similar question here but not exactly what i am asking.
Please help.

A: On a modern CPU, memory itself is retrieved in usually chunks called cache lines (64 bytes on x86), but the CPU instruction set can address individual bytes.
If you had some esoteric machine with an instruction set that couldn't address individual bytes, then your compiler would hide that from you.
Whether or not memory is wasted in data structures smaller than a word would depend on the language you use and its implementation, but generally, records are aligned according to the field with the coarsest requirement.  If you have an array of 16 bit integers, they will pack together tightly.

A: If you have 3 or 4 integers, it scarcely matters whether you store them in 2, 4, or 8 bytes.
If you have 3 or 4 billion integers, then it's probably worth considering a more space-efficient structure.
Generally speaking, the natural integer size for a given language implementation is supposed to be optimal in some way, so my advice is in general 'use int unless you know it's not appropriate' and let the compiler worry about it - until you have performance data to show otherwise.


text:
Q: How to make spread operator enumerate through non-function properties only? Stack: ReactJS 16.x, Typescript 2.8.1, create-react-app project.
I am getting a type error when using the spread operator to pass props from a TypeScript class to a React component.
The error occurs only when the class has a function defined. If the class has a function expression variable, the spread operator works fine. I believe it has to do with the enumeration of properties on the class. So, I use a decorator to mark the function as non-enumerable but am still getting the same error. Below is the code:
Message is the class I am trying to spread into a React Component.
export class Message {
  constructor() {
    this.init2 = (msg: string) => {
      this.msg = 'init2';
      return this;
    }
  }

  public msg: string;

  // This works with spread operator
  public init2: (msg: string) => Message;

  // This will cause the spread operator to fail
  public init(msg: string): Message {
    this.msg = msg;
    return this;
  }

  // Even with decorator to turn off enumeration, spread operator fails
  @enumerable(false)
  public initNoEnum(msg: string): Message {
      this.msg = msg;
      return this;
  }
}

ReactJS component who's prop is defined as Message:
export class MessageComponent extends React.Component<Message, any>{
  render() {
    return (<div>{this.props.msg}</div>);
  }
}

Render method which uses MessageComponent:
  public render() {
    const msg = new Message().init('hello world!');
    return <MessageComponent {...msg} /> // The spread here fails
  }

The enumerable decorator function:
  export function enumerable(value: boolean): any {
      return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
      descriptor.enumerable = value;
    };
  }

tsconfig:
"compilerOptions": {
  "outDir": "./build",
  "module": "esnext",
  "target": "es5",
  "lib": [ "es6", "dom" ],
  "sourceMap": true,
  "allowJs": true,
  "jsx": "react",
  "moduleResolution": "node",
  "rootDir": "src",
  "forceConsistentCasingInFileNames": true,
  "noImplicitReturns": true,
  "noImplicitThis": true,
  "noImplicitAny": true,
  "strictNullChecks": true,
  "suppressImplicitAnyIndexErrors": true,
  "noUnusedLocals": true,
  "experimentalDecorators": true
},

If I comment out init and initNoEnum and keep init2, the spread operator works. With init and initNoEnum, the spread operator fails with similar message:

Type '{ msg: string; init2: (msg: string) => Message; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNod...'.   Type '{ msg: string; init2: (msg: string) => Message; }' is not assignable to type 'Readonly'. Property 'init' is missing in type '{ msg: string; init2: (msg: string) => Message; }'.

What am I doing wrong? How do I make the spread operator only enumerate through properties and not functions?

A: Why use a decorator when you could just remove the functions yourself
You can't use the spread operator to get only the non-function properties by default because functions are properties but perhaps with your tsconfig magic it should work, however, you can modify the object being passed to the spread operator first instead.
To use spread syntax to get only non-function properties without the tsconfig magic, I would suggest using a function to filter out the function properties and then use the spread operator like so:
const filterOutFunctions = object => {
  return Object.keys(object)
    .filter(key => typeof(object[key]) !== 'function')
    .reduce((filteredObj, currentItem) => {
      filteredObj[currentItem] = object[currentItem]
      return filteredObj
    }, {})
}

const objectWithFunctions = {
  aFunction() {},
  aProperty: 'A good ol string'
}

// Now you can do spread operator stuff with a filtered version like so:
{...filterOutFunctions(objectWithFunctions)}
// returns: { aProperty: 'A good ol string' }

The way this works is by iterating over the keys of object with .filter to filter out the keys that point to a function. Then we collect all of the remaining properties via assigning them to a new, empty, object with .reduce.


text:
Q: Communicating between ZMQ sockets in a distributed system over the internet I've been working on a distributed system project, my system is partially p2p. My issue is super simple, I don't know how people usually solve it, because I have no experience in this domain, I am very new to this all.
I want to communicate over the internet between two clients, which both have ZMQ sockets.
On my local network, or my machine, they seem to work fine, but when communicating over the internet, I never get my message. I have shortlisted this to 2 reasons :
1 ) The NAT - it is not letting my message reach the client host, does anyone know how to solve the issue of NAT within ZMQ, I have heard of TCP hole punching and such, how do web developers and other people who deal with this thing often manage this ?
2 ) ZMQ sockets can not communicate over the internet, even if the communication is strictly between the two ZMQ sockets and not BSD sockets etc. I am not sure about this one though.
If anyone has expertise in this area I would be grateful and it would help me move forward thanks !

A:
2 ) ZMQ sockets can not communicate over the internet, even if the communication is strictly between the two ZMQ sockets

Well, 2 ) is easy, ZeroMQ sockets obviously work over the Internet .
There is not much to add to this.

1 ) The NAT - it is not letting my message reach the client host,

The 1 ) will deserve a bit more attention :
Right, NAT could be in place, when local LAN(s) routers are connected to a single public ( registered, coordinated IPv4 / IPv6 address ).
Next, there could be another show-stopper in the game, the FireWall, put in one or more places (!) -- be it a local one ( O/S operated, which one can check, if having administrator-grade login to the localhost ), or a one, integrated into any of  the Gateway/Proxy/Policy enforcement.
In any case, thorough design-review ought take place with your local administrator(s), responsible for the localhost-O/S and network-infrastructure elements and a network-wide responsible security-manager / engineer(s).
The "HOW ?" part :
This ( principal ) complexity is exactly why Game Studios try to avoid user's headaches on solving these complexities and try to provide some escape strategy.
For a trivial case 1-to-1 :
One may indeed use a set of rules for a port-forwarding setup ( if FireWall + Gateway engineering permits ) and your ZeroMQ connectivity may get directed  onto a
tcp://<public-IP>:<_a_port#_known_to_be_FWDed_to_a_target_HOST_> address.
For more, but still units :
This scenario may seem easy for a single connection setup, yet if in a need to have units or tens of target hosts, there would be a rather limited will from the gateway ( router ) / firewall admins to open more and more ports on the wild side of the security perimeter. Here another trick may help - using a standard ssh-tools, where connections could harness so called local-port-forwarding and remote-port-forwarding, and the interconnects enjoy a single-port to pass firewall + gateway, plus the content is encryption-protected. Sure, more administrative efforts are needed on both sides, yet, a known and smart way to go, if these efforts and a bit increased latency ( encryption + decryption processing added ) do not spoil your in-game UX latency plans.
For more, above a few units :
There is an option of re-using an ad-hoc, yet a security threating dual-sided sword - a multi-player shared (!) VPN, which solves the global "visibility" issues ( most often with some central ( be it published or not ) service-provisioning mapping and authentication serving coordinator ). The localhost side applications simply start to see another "local"-interface, uncoordinated with respect to its IPv4 / IPv6 address(es), yet this private-shared-VPN seems to be joining all the players so as to look as if all of these share one common IP-network, having effectively bypassed all the security/firewalling efforts of the common network practices --- which is at the same time its strongest risk for putting in place ( not mentioning the risk of the principal SPOF in the remote, central, authorisation/mapping service-provider, be theirs set of motivations published or hidden ).
Gaming industry panicked on all these issues since Multi-Player games started to be sold ( which for 2018/Q2 Gamers may look as since ever ) and the industry was trying to avoid exactly all these complexity-related pains, as a dominant fraction of game-buying teenagers was not expected to also have acquired both the patient persistence ( to systematically craft the proper setup ) and the deep-enough knowledge ( so as to know all the system-wide details of where and what to setup or re-configure, so as to unlock a secure end-to-end online in-game visibility ).
For indeed many-to-many cases :
A nice example was started in late 1990-ies / early 2000-ies when IL-2 Sturmovik's Community of Pilots and Virtual Squadrons went operational 24/7/365 "since ever". They used a Community sponsored HyperLobby a Mediating Node to have all these complexities solved once and forever for all interested Members. HyperLobby lightweight client/server service-infrastructure was doing all the port-forwarding mapping setups and other server-side mediations dirty hacks all invisible to Pilot(s) and provided added means for administering indeed many connected Multi-Player Game Theatres for IL-2, F/A-18, Su-27 Flanker, CFS, Medal Of Honor and many more, than I try to remember today ( topping above small tens of thousands of connected Pilots IIRC in peak hours ). A great piece of sound design and distinguished efforts for decades for the truly Global online Community ( having an honor to serve in pseudohistorical VFSQ, with members spanning 13 TimeZones - from Hawaii, Brasil, U.S., U.K., France, Germany, Italy, Greece to Turkey - flying with similarly minded friends from Japan, Australia, New Zealand and many other places, round the globe -- be it East/West Front + Pacific Theater globally coordinated weekend-events - missions reconstructed till the very historical details or enjoyed the Memorial Parade Flyovers on V-Day-s' anniversaries ) -- ~Salute~ Jiri Fojtasek, well done indeed! -- idea of which helps to illustrate the way to go / follow ( as many younger game-portals indeed did follow this path ).


text:
Q: What can I do that don't block users in using instagram whith like IPs in my network? I have a network in my server with one static IP and more than 20 person using 30 instagram account inside it.
But instagram suspicious or blocks more of them.
1- I know I can use proxies in server to solve this, But can I use a world proxy lifetime without monthly or yearly period?
2- In telegram, we can install MTPro protocol for using it. Is a protocol or way that don't need a proxy for using my users in server instagram?


text:
Q: Trigger separate hover effects (jQuery + CSS) simultaneously in image gallery Working on portfolio gallery: flowmedia.dk/new
Inactive state:

Hovering over the top 2/3 of thumbnail triggers image going from grayscale to color:

Hovering over the bottom 1/3 of thumbnail triggers image caption.:

Captions (jQuery):
jQuery(document).ready(function($) {
    $(document).ready(function(){
        $('.caption').hide();
        $('#portfolio-container .element').hover(function () {
            $('.caption', this).stop().fadeTo('slow', 1.0);
        },
        function () {
            $('.caption', this).stop().fadeTo('slow', 0);
        });
    });
});

Grayscale (CSS):
img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
     -webkit-filter: grayscale(0%);
    ...
}

How do I trigger the captions and grayscale-to-color effect simultaneously on hover or trigger the grayscale-to-color with the captions?
(Hover anywhere on thumbnail and image will change from grayscale to color.)

A: This can be achieved easily with only css.
CSS
.grayscale {
  width: 200px;
  height: 200px;
  position: relative;
  margin: 0 auto;
  top: 30px;
  border: 3px solid rgba(0, 0, 0, 0.6);
  padding: 10px;
  background: rgba(255, 255, 255, 0.5);
}

.bird {
  width: 100%;
  height: 100%;
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
  -webkit-filter: grayscale(100%);
}

.bird:hover {
  -webkit-filter: grayscale(0%);
}

.grayscale p {
  position: absolute;
  bottom: 0;
  left: 0;
  display: none;
}

.grayscale:hover p {
  display: inline;
}

.grayscale p:hover strong { /* Can be h1, h2, span, etc... */
  color: brown;
}

HTML

The wild Swallow bird
This crazy and unique bird loves to fly over the sky in search of a tasty div tag

JSFIDDLE
If this is does not fit your needs then let me know and I'll remove or edit it. I just find it better to not use jQuery if you don't have to!


text:
Q: Electron app failing with cryptic output - Exits with SIGSEGV I'm building this app called bibiscio, but my problem is, I'm getting errors when building the project:
/Users/mintstudios/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGSEGV
npm ERR! code 1
npm ERR! path /Users/mintstudios/Documents/git-inst/bibisco/bibisco/app
npm ERR! command failed
npm ERR! command sh -c electron .

I don't know what this means, and I've been at this for a while.
System: M1 Mac, ARM architecture, macOS Big Sur
ARM might be the problem though, but I'm not sure.


text:
Q: Adding Conv Layer in front of pretrained model gives ValueError I want to combine a pretrained VGG16 model with a special input block, which is an input layer and a convolutional layer. The goal is to use a pre-trained RGB VGG16 imagenet model on grayscale images:
from keras.applications.vgg16 import VGG16
from keras.layers.convolutional import Conv2D
from keras.layers import Input
from keras.models import Model

img_height = 299
img_width = 299

def input_block(img_height = 299, img_width = 299):
    input_shape = (img_height, img_width, 1)
    img_input = Input(shape=input_shape, name = 'grayscale_input_layer')
    x = Conv2D(3, (3,3),  padding= 'same', name = 'grayscale_RGB_layer')(img_input)
    return x

pretrained_model = VGG16(weights = 'imagenet', include_top=False, input_tensor = input_block(img_height, img_width))

When I set the weight initalization of VGG16() to 'None', the model builds correctly, with the following desired structure:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
grayscale_input_layer (Input (None, 299, 299, 1)       0
_________________________________________________________________
grayscale_RGB_layer (Conv2D) (None, 299, 299, 3)       30
_________________________________________________________________
block1_conv1 (Conv2D)        (None, 299, 299, 64)      1792
_________________________________________________________________
block1_conv2 (Conv2D)        (None, 299, 299, 64)      36928
_________________________________________________________________
block1_pool (MaxPooling2D)   (None, 149, 149, 64)      0
_________________________________________________________________
block2_conv1 (Conv2D)        (None, 149, 149, 128)     73856
_________________________________________________________________
block2_conv2 (Conv2D)        (None, 149, 149, 128)     147584
_________________________________________________________________
block2_pool (MaxPooling2D)   (None, 74, 74, 128)       0
_________________________________________________________________
block3_conv1 (Conv2D)        (None, 74, 74, 256)       295168
_________________________________________________________________
block3_conv2 (Conv2D)        (None, 74, 74, 256)       590080
_________________________________________________________________
block3_conv3 (Conv2D)        (None, 74, 74, 256)       590080
_________________________________________________________________
block3_pool (MaxPooling2D)   (None, 37, 37, 256)       0
_________________________________________________________________
block4_conv1 (Conv2D)        (None, 37, 37, 512)       1180160
_________________________________________________________________
block4_conv2 (Conv2D)        (None, 37, 37, 512)       2359808
_________________________________________________________________
block4_conv3 (Conv2D)        (None, 37, 37, 512)       2359808
_________________________________________________________________
block4_pool (MaxPooling2D)   (None, 18, 18, 512)       0
_________________________________________________________________
block5_conv1 (Conv2D)        (None, 18, 18, 512)       2359808
_________________________________________________________________
block5_conv2 (Conv2D)        (None, 18, 18, 512)       2359808
_________________________________________________________________
block5_conv3 (Conv2D)        (None, 18, 18, 512)       2359808
_________________________________________________________________
block5_pool (MaxPooling2D)   (None, 9, 9, 512)         0
=================================================================
Total params: 14,714,718
Trainable params: 14,714,718
Non-trainable params: 0
_________________________________________________________________
None

However, when I set the weight initialization to 'imagenet',
I get the following error:

ValueError: You are trying to load a weight file containing 13 layers into a model with 14 layers.

This error makes sense, since I have added two layers in front of the VGG16 model instead of a single layer.
As a workaround, I have tried the following:
def input_block_model(img_height = 299, img_width = 299):
    input_shape = (img_height, img_width, 1)
    img_input = Input(shape=input_shape, name = 'grayscale_input_layer')
    x = Conv2D(3, (3,3),  padding= 'same', name = 'grayscale_RGB_layer')(img_input)
    model = Model(img_input, x, name='input_block_model')
    return model

input_model = input_block_model(299,299)
pretrained_model = VGG16(weights = "imagenet", include_top=False)
combined_model = Model(input_model.input,
pretrained_model(input_model.output))
print(combined_model.summary())

Then, the model structure is:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
grayscale_input_layer (Input (None, 299, 299, 1)       0
_________________________________________________________________
grayscale_RGB_layer (Conv2D) (None, 299, 299, 3)       30
_________________________________________________________________
vgg16 (Model)                multiple                  14714688
=================================================================
Total params: 14,714,718
Trainable params: 14,714,718
Non-trainable params: 0
_________________________________________________________________
None

The disadvantage of this structure, is that I cannot set properties of layers within the VGG16 model. I want to freeze certain layers for example in this model, which I cannot access via combined_model.layers. Does anyone have a working solution, such that I get the model structure as with the 'None' initialization, but with pretrained ImageNet weights?

A: You can freeze or train layers using combined_model.layers[2].layers as mentioned in the comment above. You can may be simplify the model as follows:
```
img_input = Input(shape=(img_height, img_width, 1), name = 'grayscale_input_layer')
x = Conv2D(3, (3,3),  padding= 'same', name = 'grayscale_RGB_layer')(img_input)
x = VGG16(weights = None, include_top=False)(x)
model = Model(img_input, x)
model.summary()

for layer in model.layers[2].layers:
    layer.trainable = False

```


text:
Q: Can the .NET Concurrent Collections be used for inter-process x32 to/from x64 communications? I have a 32 bit application which I have no control over.  I currently have it communicating with a 32 bit C++ DLL which massages the data and passes it on to a 32 bit .NET DLL where my C# application can get to it.  I would like to upgrade my C# app to 64bits to get greater memory access.
Is there a way to get my 32 bit C++ DLL to talk to the .NET Concurrent Collections, specifically the ConcurrentQueue?  Will this allow inter-process communication? If so, is there an example I could learn from?  If not, does anyone know of any API or library to solve bidirectional 32 - 64 bit inter-process communications.
It seems that this would be a major problem for a lot of developers but my searching has not uncovered a fast, reliable, possibly easy solution. I find it strange that the major component developers do not offer any solutions (that I have found).
Thanks in advance for any assistance.

A: There's no way to have an in-process mixture of 32 and 64 bit application and dlls.
If you want to communicate between a 32 and 64 bit application then you've got a few options:

*

*Package up the 32 bit library into a COM object and host it out of process. COM will marshall the calls from 64 bit to 32 bit and back again.

*Use IPC (such as named pipes, TCP or WCF) to communicate between the 32 and 64 bit applications.

*Use memory mapped files to exchange data using shared data structures. This is probably the most complicated solution.


text:
Q: Facebook Graph API: Getting total of shares of a page's photo I'm trying to get the number of shares of a photo of a Facebok's Page. But I can't do that!
The photo's table just have likes/comments info. And, the table "stream" just works with posts, doesn't work with photos.
Photo's ID: 313125495503479
Page's ID: 285150194967676
There's anyway to do that?

A: When the object it's a photo, you can do this way:
https://graph.facebook.com/fql?q=select+share_count+from+stream+where+post_id+IN+(select+page_story_id+from+photo+where+object_id+=\"{$object_id}\"+)&access_token={$tk}

when the object it's a stream, or something like this, you can d this way:
https://graph.facebook.com/fql?q=select+share_count+from+stream+where+post_id+=\"{$object_id}\"&access_token={$tk}

Parse json, and get the field 'share_count'...Worked for me!


text:
Q: End function when next instance in each is started A little bg info: I'm working on making a website 100% navigable by keyboard/tabs, and I'm stuck on making the dropdown menus open up when tabbed through.
Here's what I have so far:

Home

About Us

Knowledge & Expertise

Testimonials

Contact Us

Apply Now

Quick Quote

Subscribe

And for the jQuery:
$("a").each(function (i) { $(this).attr('tabindex', i + 1); });

$('.parent-nav > a').each(function(){
    $(this).focus(function() {
        $(this).parent().children(".nav-secondary-pg").show();
    });
});

Right now, all of my links are getting the tabindex correctly, and the secondary navigation is showing when the .parent-nav > a is focused. The problem is getting that function to end when the next .parent-nav > a is focused. What happens, is I end up with a page that looks like this as I tab through:

How do I kill the function when I reach the next instance in the .each()?

A: First, target your focus event handler like $('.nav-wrap a') so that it includes all nav links. Then, in your focus event handler, you can check to see if any subnavs are currently open. Finally, check to see if the subnav you're currently in is the one that's open - if it's not, then close out the other subnav, and open the one you're currently in.
Also, you don't need to use .each() here, as you can just attach the event handler directly to the jQuery collection. And finally, prefer .on('focus'...) instead of `.focus(...) (here's why). So the end result would look something like:
$('.nav-wrap a').on('focus', function() {
    // find open sub nav (if it exists)
    var $openSubnav = $('.nav-wrap .nav-secondary-pg:visible');

    // find the subnav that you're currently in
    var $thisSubnav = $(this).closest('.parent-nav').children('.nav-secondary-pg');

    // if the subnav you're in is not already open,
    // close other subnav and open this one
    if (!$thisSubnav.is($openSubnav)) {
        $openSubnav.hide();
        $thisSubnav.show();
    }
});


text:
Q: how to add a dot at any position in a string in R using gsub and regex I use the following code to add a dot after the third position in my string
x = "X012345"
y = gsub('^(.{3})(.*)$', '\\1.\\2', x)
print(y)
[1] "X01.2345"

I need this to become more general. I want to be able to put my dot after any character of my choice. So the '3' in the gsub command should become a variable.
I've tested this
i = 3
y = gsub('^(.{i})(.*)$', '\\1.\\2', x)

but I then get an error:
Error in gsub("^(.{i})(.*)$", "\\1.\\2", x) :
  invalid regular expression '^(.{i})(.*)$', reason 'Invalid contents of {}'

Can I achieve what I want to do using gsub & regex?

A: Maybe you want to put it into a function.
gsub_dot <- function(x, i) gsub(paste0('^(.{', i, '})(.*)$'), '\\1.\\2', x)

gsub_dot(x = "X012345", 1)

[1] "X.012345"

A: 1) sub Use sprintf to insert the number.  Also use sub instead of gsub and simplify the regular expression slighlty:
x <- "X012345"
n <- 3
sub(sprintf('(.{%d})', n), '\\1.', x)
## [1] "X01.2345"

2) stri_sub If you don't mind using a package then with stringi this works:
library(stringi)
`stri_sub<-`(x, n+1, n, value = ".")
## [1] "X01.2345"

3) zero-width regex This has a simpler second argument to sub but the first argument is more complex.  It uses a zero width expression -- see ?regex for more info.
sub(sprintf("(?<=.{%d})", n), ".", x, perl = TRUE)
## [1] "X01.2345"

4) fn$  Another approach if a package is ok is to use fn$ from gsubfn to insert n.  This is close to one of the attempts in the question.
library(gsubfn)
fn$sub('(.{$n})', '\\1.', x)
## [1] "X01.2345"

A: Use substring and paste0:
sub_dot <- function(x, i) paste0(substring(x, 1, i), ".", substring(x, i + 1))
sub_dot(x, 3)
#[1] "X01.2345"

Or, in one call:
sub_dot <- function(x, i) paste(substring(x, c(1, i+1), c(i, 10000)), collapse = ".")


text:
Q: Using more widget in main page cause slow loading Wordpress? I'm using a custom widget in homepage and I use this widget almost 20 times in main page. Whether it is about slow loading site?!
http://akhbartop.ir/

A: It looks like server response time and stylesheet loading are causing the greatest delay:

You can measure the network performance of your site yourself using the Network panel in Chrome: Right click > Inspect > Network (refresh the page to load details)

A: This may help you in reducing your loading time. And speed up your website. I this you should try using some cache plugin.


text:
Q: Как отлаживать программу на ассемблере Подскажите пожалуйста , как правильно отладить приложение на ассемблере . Раньше для консольных приложений использовал оли дебагер ,все было нормально , сейчас возникла потребность ГУИ приложение отладить , нужно на определенном месте кода остановится ,после нажатия на кнопку . Но при нажатии на кнопку , дебагер не останавливает, просто происходит действие по нажатию на кнопку. Подскажите пожалуйста как остановится на определенном месте и как вообще правильно нужно отлаживать программы такие.
Спасибо
A:
нужно на определенном месте кода остановится ,после нажатия на кнопку

Можно прямо в коде в нужном месте (в начале кода, обрабатывающего нажатие на кнопку) вставлять int3. При запуске программы под отладчиком произойдет остановка исполнения в этом месте. При запуске без отладчика просто произойдет необработанное исключение, и программа будет закрыта.

ещё совсем недавно фасм просто не умел общепринятую отладочную информацию генерить.

Начиная с версии 1.67.29 fasm умеет генерировать отладочную/символьную информацию (включается ключом -s при компиляции из исходника из командной строки). Используется свой собственный формат, не совместимый ни с каким другим инструментом, но есть например плагин для OllyDbg 1.10, включающий его поддержку, и есть утилиты, конвертирующие этот формат в общепринятые форматы.
Цитата с forum.flatassembler.net (тема "Symbolic/debug information", пост №2):

Tomasz Grysztar
Here comes the list of the existing tools converting "fas" into some other formats (moderators, please feel free to edit this list anytime, when some new tools arrive):

*

*Tool that generates debug info in CodeView format in COFF object files generated by fasm:
  http://board.flatassembler.net/topic.php?p=89369

*Linux program that dumps in text form the contents of "fas" file generated for the ELF binary:
  http://board.flatassembler.net/topic.php?t=10029

*Plugin for OllyDbg that loads debug info from .fas file:
  http://board.flatassembler.net/topic.php?p=114370

*IDA script which adds FASM debug info:
  http://board.flatassembler.net/topic.php?p=118458

*fasolly: yet another plugin which imports .fas into OllyDbg
  http://board.flatassembler.net/topic.php?t=12365


text:
Q: How to create a Multicol within a Page-Frame spanning multiple pages Added 2020-07-05 -- Details of my requirements:
Produce a document that frames doublecol and onecol:
The frame is supposed to

*

*completely frame all content of the document

*within one frame

*that is open between (and only between) pagebreaks.

As for the content within the frame

*

*The CONTENT has alternating doublecol

*AND onecol
Pagenumbers:
I could live with pagenumbers not being framed, but that would be nice.
So the code would ideally look like as follows:

\usepackage{mdframed}                   % Alternative1
%\usepackage{framed}                    % Alternative2
\usepackage{multicol}
\usepackage{lipsum}

\begin{document}
    \begin{mdframed}                % Alternative1
    %\begin{framed}                 % Alternative2

        \begin{multicols}{2}
        \lipsum[1-10]
        \end{multicols}

        \lipsum[1-2]

        \begin{multicols}{2}
        \lipsum[1-10]
        \end{multicols}

    \end{mdframed}                  % Alternative1
    %\end{framed}                   % Alternatice2

\end{document}

Is not working: mdframed, framed
BUT: when the text spans more than one page e.g. using \lipsum[1-10], the compiler get's lost within a stack-overflow saying

"! TeX capacity exceeded, sorry [input stack size=5000].@xiipt ->12 \end{framed}."

I learned from the documentation page 6 3.1 Preface to version 1.4 that

The only restriction to such inner multicols environments (nested, or
within TEX's internal vertical mode) is that such variants will
produce a box with the balanced material in it, so that they can not
be broken across pages or columns.

So it seems that LaTex is trying to a) open a frame b) render the two columns c) can't deliver pages because two columns haven't been distributed over the document and then d) dies because it woud not know how to close the frame for the first page.
Is not working: twocolumn as a doc-class parameter
\documentclass[twocolumn]{article}
...

but this will produce a frame around each column - which I don't want.
**Is not working:
It can't be that difficult - seems to be such a simple common problem. How to achieve that?
Thanks for your efforts.
Crosspost Links ----------------------
TexWelt.de
golatex.de

A: Update #2
One way to size the frame to the final text is to save the y-position at the end of the document, and then use that to calculate the `\layerheight' on the final page.
This solution uses zref to find that position. You'll need two runs.
\documentclass{article}
\usepackage{scrlayer}
\usepackage{multicol}
\usepackage[savepos]{zref}
\usepackage{lipsum}

\newlength{\marginpadding}
\setlength{\marginpadding}{4pt}

\DeclareNewLayer[textarea,background,mode=picture,
  addheight=2\marginpadding,
  addwidth=2\marginpadding,
  addhoffset=-\marginpadding,
  addvoffset=-\marginpadding,
  contents={%
  \putLR{\line(0,1){\LenToUnit{\layerheight}}}%
  \putUR{\line(-1,0){\LenToUnit{\layerwidth}}}%
  \putUL{\line(0,-1){\LenToUnit{\layerheight}}}%
}]{topbox}
\DeclareNewLayer[clone=topbox,
  contents={%
  \putLR{\line(0,1){\LenToUnit{\layerheight}}}%
  \putUL{\line(0,-1){\LenToUnit{\layerheight}}}%
}]{midbox}
\DeclareNewLayer[clone=topbox,
  height={\pdfpageheight-\zposy{textbottom}sp-\layeryoffset-\baselineskip+\marginpadding},
  contents={%
  \putLL{\line(1,0){\LenToUnit{\layerwidth}}}%
  \putLR{\line(0,1){\LenToUnit{\layerheight}}}%
  \putUL{\line(0,-1){\LenToUnit{\layerheight}}}%
}]{bottombox}
\DeclarePageStyleByLayers{firstpage}{topbox}
\DeclarePageStyleByLayers{midpage}{midbox}
\DeclarePageStyleByLayers{lastpage}{bottombox}
\pagestyle{midpage}
\begin{document}
\thispagestyle{firstpage}
\begin{multicols}{2}
  \lipsum[1-10]
\end{multicols}

\lipsum[1-2]

\begin{multicols}{2}
  \lipsum[1-10]
\end{multicols}
\zsaveposy{textbottom}
\thispagestyle{lastpage}
\end{document}

Updated Answer (2020/07/06)
I'm still not completely clear on your requirements, but if what you're really asking for is a frame whose size is fixed and simply adapts its shape depending on what page you are on, you can do this with the page styles provided by the scrlayer package.
The following works as long as you know you have more than one page of content. (You could add some logic to test for a one-page doc if you really needed it.) The basic idea is to create three page styles, make the middle page style the default, and set the top and bottom styles for a single page at the beginning and end.
The frame is very simple (it's adapted from the KOMA-Script manual--see chapter 17), but you could replace the contents with a much more sophisticated image if you desire.
\documentclass{article}
\usepackage{scrlayer}
\usepackage{multicol}
\usepackage{lipsum}

\newlength{\marginpadding}
\setlength{\marginpadding}{4pt}

\DeclareNewLayer[textarea,background,mode=picture,
  addheight=2\marginpadding,addwidth=2\marginpadding,
  addhoffset=-\marginpadding,addvoffset=-\marginpadding,
  contents={%
  \putLR{\line(0,1){\LenToUnit{\layerheight}}}%
  \putUR{\line(-1,0){\LenToUnit{\layerwidth}}}%
  \putUL{\line(0,-1){\LenToUnit{\layerheight}}}%
}]{topbox}
\DeclareNewLayer[textarea,background,mode=picture,
  addheight=2\marginpadding,addwidth=2\marginpadding,
  addhoffset=-\marginpadding,addvoffset=-\marginpadding,
  contents={%
  \putLR{\line(0,1){\LenToUnit{\layerheight}}}%
  \putUL{\line(0,-1){\LenToUnit{\layerheight}}}%
}]{midbox}
\DeclareNewLayer[textarea,background,mode=picture,
  addheight=2\marginpadding,
  addwidth=2\marginpadding,
  addhoffset=-\marginpadding,
  addvoffset=-\marginpadding,
  contents={%
  \putLL{\line(1,0){\LenToUnit{\layerwidth}}}%
  \putLR{\line(0,1){\LenToUnit{\layerheight}}}%
  \putUL{\line(0,-1){\LenToUnit{\layerheight}}}%
}]{bottombox}
\DeclarePageStyleByLayers{firstpage}{topbox}
\DeclarePageStyleByLayers{midpage}{midbox}
\DeclarePageStyleByLayers{lastpage}{bottombox}
\pagestyle{midpage}
\begin{document}
\thispagestyle{firstpage}
\begin{multicols}{2}
  \lipsum[1-10]
\end{multicols}

\lipsum[1-2]

\begin{multicols}{2}
  \lipsum[1-10]
\end{multicols}
\thispagestyle{lastpage}
\end{document}

Original Answer
Welcome to Tex.SE.
You could try the package multicolrule. The idea is to create a "column separator" for multicols that actually draws a box around the outside of the columns instead of between them.
\documentclass{article}
\usepackage[tikz]{multicolrule}
\usetikzlibrary{calc}
\usepackage{lipsum}

\SetMCRule{color=gray,width=0.4pt, expand=2pt, custom-line={
  \coordinate (TOPLEFT) at ($(TOP)-(\columnwidth+.5\columnsep,\columnseprule)$);
  \coordinate (TOPRIGHT) at ($(TOP)+(\columnwidth+.5\columnsep,-\columnseprule)$);
  \coordinate (BOTLEFT) at ($(BOT)-(\columnwidth+.5\columnsep,-\columnseprule)$);
  \coordinate (BOTRIGHT) at ($(BOT)+(\columnwidth+.5\columnsep,\columnseprule)$);
  \draw[line width=\columnseprule] (TOPLEFT) -- (TOPRIGHT) -- (BOTRIGHT) -- (BOTLEFT) -- cycle;}}

\begin{document}
\begin{multicols}{2}
  \lipsum
\end{multicols}
\end{document}

This version puts the lines exactly around the edge of the boxes, but you could add a gap if you wanted.


text:
Q: VSTO Outlook: Show custom taskpane only in the compose, reply and forward windows I have created a custom taskpane to show custom messages to the user. Now, I would like to show this taskpane only in compose, reply and forward windows. How can I achieve this?

A: Check that MailItem.Sent property is false before displaying your task pane.