text:
Q: Is it possible for webpage to dynamically insert data from another file without needing a server call Is it possible for webpage to dynamically insert data from another file without needing a server call?
What I mean by that is can a .html page update itself with something like XMLHttpRequest but instead of this making a call to a server just simply read in a file that is the same location as the html page.
Pseudocode
if(userclicks on x)
{
    read and display contents of y within this div)
}

Background
I am converting an html report that currently uses a frameset divided into left and right panels. The left panel lists a series of folders that have been processed, the right-hand side shows the processing done on the selected folder.

*

*I need to remove framset because outdated and not supported in html 5

*iFrames not a suitable alternative as they are not designed for showing the content of an integral part of the site, they look plain weird when this is done.

*It is not viable to preload all the content of the page and then uses javascript to hide/show the content of the file when user changes selection because the single html file would be too large and too slow to load.

*It is not viable to make a call to a server because there is no server, the reports are created by an application and then can be viewed standalone without the application being run. They can also be sent to support to be viewed standalone.

*My temporary solution is that when the user selects a file then the processing html file is displayed in a new tab (or window), but there is not a very satisfactory for the user

A: If I'm reading your question right, all of the necessary data is part of the page at the outset (since you can't load it from a server, it has to all already be there — but see under the line below for more on that). But you've said:

It is not viable to preload all the content of the page and then uses javascript to hide/show the content of the file when user changes selection because the single html file would be too large and too slow to load.

So that suggests the data itself is quite a bit smaller than the representation of the data.
You can certainly have an element on the page (for instance, a div) that you update with a rendering of a subset of the data the page holds, using the DOM. Here's a trivial example:

const data = [
    {label: "one", a: "a one", b: "b one", c: "c one"},
    {label: "two", a: "a two", b: "b two", c: "c two"},
    {label: "three", a: "a three", b: "b three", c: "c three"},
    {label: "four", a: "a four", b: "b four", c: "c four"}
];

function populateMenu() {
    const menu = document.getElementById("menu");
    for (let i = 0; i < data.length; ++i) {
      const entry = data[i];
      const a = document.createElement("a");
      a.href = `#entry-${i}`;
      a.textContent = entry.label;
      a.addEventListener("click", event => {
          event.preventDefault();
          showEntry(entry);
      });
      menu.appendChild(a)
    }
}

function showEntry(entry) {
    const content = document.getElementById("content");
    const {a, b, c} = entry;
    content.textContent = `a: ${a}, b: ${b}, c: ${c}`;
}

populateMenu();
#menu a {
  padding: 4px;
}

That uses ES2015+ syntax, but you can do the same thing with ES5 only if you need to for your target environments.
The content div there can, of course, be the majority of the page display.
This is the basic nature of a single-page application (SPA), so further research using that term may be useful. But your SPA is standalone (whereas most will do server calls, but still update the page as above).

In a comment you've said:

Currently the files are created at the outset, there is the main folder and a file that represents the processing of each folder. The user could have processed a 1000 folders so that means the main file is essentially a list of 1000 folders, and then there are a 1000 other files each containing a few pages of data. SO clearly if we to combine of all of this into one file it would be about 1000 time larger, yet user would only eve be viewing the procesing associated with one folder...So your approach above would not work for me.

I'm afraid you're trying to have your cake and eat it. :-) Either you can load the data later, or it's all on the page at the outset. You said in the question you can't load the data later, so it must be in the page at the outset.
But: Your use of the word "files" above suggests that this report without a server can be a set of files, not just a single file.
Your cross-browser options if HTML File A needs to load content from HTML File B are:

*

*Use iframes and update the src to go from file to file. You've said in the question that they "aren't for the main content of the page", but that's not my understanding; and that they're ugly, but they're completely stylable via CSS. They can literally be seamlessly integrated into the main page.

*Keep using frames, update the src of the frame to move from file to file. Yes, frames were removed in HTML5. They will never be removed from web browsers, too much legacy.

Sadly, you can't reliably use XMLHttpRequest when your page is loaded from a file: URL. Some browsers allow it, others don't. (You can't use fetch in any of them, it specifically doesn't support the file: scheme.)
Your constraints literally constrain your choices, I'm afraid.
Here's an iframe example:
report.html:
<!doctype html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Report</title>

    File 1
    File 2
    File 3

file1.html (file2.html and file3.html are identical, just different names and numbers):
<!doctype html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>File 1</title>

This is file 1.

A: <template>
If you have local content on a file try using an  or a <template>. The latter is what we will consider. A <template> is inert and ignored by the browser so no matter how huge your extra content is -- it shouldn't be an issue.
Demo

<!DOCTYPE html>

  <title>Page 1</title>

  <form id='import'>
    <fieldset>
      <legend>Import data.html by XMLHttpRequest()</legend>
      <output id='content'></output>
    </fieldset>
    <input type="submit">
  </form>

  <template id='data'>

DATA

TH	TH	TH

TD	TD	TD

TD	TD	TD

TD	TD	TD

</template>

XMLHttpRequest()
Assuming that a separate web page on the same domain as the target web page is feasible it is possible to import HTML from another webpage (whether from a server or same domain) using XMLHttpRequest().
Demo Outline

*

*Main page: index.html, Imported page: data.html

*On main page the element that will have the imported HTML needs this:

  <div data-x="data.html"...

Any type of element assigned data-x attribute with the value of the imported web page's URL.

Plunker
index.html
This Stack Snippet does not function because it loads an external page, for a working demo review this Plunker

<!DOCTYPE html>

  <title>Page 1</title>

  <form id='import'>
    <fieldset>
      <legend>Import data.html by XMLHttpRequest()</legend>
      <output data-x="data.html"></output>
    </fieldset>
    <input type="submit">
  </form>

data.html
This is just the plain web page that is imported to index.html, for a working demo, review this Plunker

DATA

        TH
        TH
        TH

        TD
        TD
        TD

        TD
        TD
        TD

        TD
        TD
        TD


text:
Q: Efficient algorithm to split a string based on multiple string delimiters I would like to know if there is an efficient way of splitting a string into multiple strings based on delimiters that are also strings.
Eg. updateStr = "23+45 = 56 0" , delimiters = ["+"," ","="]
Result = [23,45,56,0]
I tried the following code in swift:
for i in 0..<delimiter.count {
    let res = updateStr.components(separatedBy: delimiter[i])
    updateStr = res.joined(separator: "unique%")
 }
splitTxt = updateStr.components(separatedBy: "unique%")

This works, but as the delimiters will be received dynamically I want a better approach.
Are there any efficient ways to avoid multiple loops to solve this?
An algorithm with more efficient solution that doesn't involve swift instance methods would also be appreciated.
Thanks for the answers but
To be clearer, I don't just want characters but strings as delimiters:
Eg2. updateStr = "I like playing with friends" , delimiters = ["li"," "la","ie"]
Result = ["I ","ke p","ying with fr","nds"]

A: The efficient way to do this sort of thing is with a Set:
let equation = "23+45 = 56 0"
let delimiters : [Character] = ["+"," ","="]
let setOfSeparators = Set(delimiters)
let result = equation.split {setOfSeparators.contains($0)}
print(result)

That's efficient because contains on a Set is extremely fast, so that cost is negligible and we are looping implicitly through the original string just once.
On the other hand, you could take advantage of the Cocoa CharacterSet class. For that, I would say:
let equation = "23+45 = 56 0"
let delimiters = ["+"," ","="]
let characterSet = CharacterSet(charactersIn: delimiters.joined())
let result = equation.components(separatedBy: characterSet).filter {!$0.isEmpty}
print(result)

Another fun way is to use a Scanner (these are underutilized in my opinion):
let equation = "23+45 = 56 0"
let delimiters = ["+"," ","="]
let characterSet = CharacterSet(charactersIn: delimiters.joined())
let scanner = Scanner(string: equation)
var result = [String]()
while let word = scanner.scanUpToCharacters(from: characterSet) {
    result.append(word)
    scanner.scanCharacters(from: characterSet)
}
print(result)

A: One of the components(separatedBy:) overloads will handle this automatically using a CharacterSet:
let delimiters = ["+"," ","="].compactMap(UnicodeScalar.init)
let splitTxt = updateStr.components(separatedBy: CharacterSet(delimiters))

A: NSRegularExpression provides the facility to split on general regular expressions, so this would enable splitting on a finite set of string delimiters using a delim1|delim2|delim3 regex. The following split operation does this job:
static func stringSubrange(str : String, st : Int, en : Int) -> String
{ var result : [Character] = [Character]()
  var count : Int = 0

  for index in str.indices
  { let c : Character = str[index]
    count = count + 1
    if count >= st && count <= en
    { result.append(c) }
    else if count > en
    { return String(result) }
  }
  return String(result)
}

static func split(str: String, pattern: String) -> [String]
{ let rge = NSRange(location: 0, length: str.utf16.count)
  let regexp = try! NSRegularExpression(pattern: pattern)
  let pred = regexp.matches(in: str, options: [], range: rge)
  var result : [String] = [String]()
  var prev : Int = 1;

  for p in pred
  { let range = p.range
    let splitString = Ocl.stringSubrange(str: str, st: prev, en: range.location)
    prev = range.location + range.length + 1
    if splitString.count > 0
    { result.append(splitString) }
  }

  if prev < str.count
  { result.append(Ocl.stringSubrange(str: str, st: prev, en: str.count)) }
  return result
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What Scala 3 syntax can match on a Type and its Type parameters in the context of a macro? From the context of a Scala 3 Macro:
  def aMacroImpl[T](using Type[T], Quotes): Expr[SpecialMap[_, _, _]] = {
    import quotes.reflect._
    val TRepr: TypeRepr = TypeRepr.of[T]
    val TSym: Symbol = TRepr.typeSymbol
    val SrtdMapSym: Symbol = TypeRepr.of[scala.collection.SortedMap].typeSymbol

    TSym.declaredFields.map{ f => TRepr.memberType(f) }.collect {
      case fieldTyepRepr if fieldTyepRepr.derivesFrom(SrtdMapSym) =>
        val fieldType = Inferred(fieldTyepRepr).tpe.asType
        fieldType match {
          ////////////////////////////////////////////////////////////
          case ... => // <-- This line is the subject of the question.
          ////////////////////////////////////////////////////////////
            '{SpecialMap.apply[k, v, sm](/* omitted for brevity*/)}
        }
    }
  }

  // More context.
  object SpecialMap {
    import scala.collection.mutable.Builder
    def apply[K, V, SM <: SortedMap[K, V]](bldr: Builder[(K, V), SM]): SpecialMap[K, V, SM] = {
      SpecialMap[K, V, SM](bldr.result)
    }
  }
  case class SpecialMap[K, V, SM <: SortedMap[K, V]](wrapedMap: SM)

What kind of syntax can replace "..." in the code snippet above, that can match on the given SortedMap type such that it can retrieve all three type parameters: k, v, and sm?
The enquirer has already tried the following:

*

*Incomplete Solutions:

/*a*/  case '[sm] => // provides sm, but not k or v

/*b*/  case '[SortedMap[k, v]] => // provides k and v but not sm

*Direct Compiler errors:

/*a*/  case '[sm[k, v]] => // sm$given1.Underlying does not take type parameters

/*b*/  case '[_[k, v]] => // ']' expected, but '[' found

/*c*/  case 'sm[k, v] => /* symbol literal 'sm is no longer supported, use a string literal
"sm" or an application Symbol("sm") instead, or enclose in braces '{sm} if you want a
quoted expression. For now, you can also `import language.deprecated.symbolLiterals` to
accept the idiom, but this possibility might no longer be available in the future. */

/*d*/
  import language.deprecated.symbolLiterals
  fieldType match {
    case 'sm[k, v] => // '=>' expected, but '[' found

/*e*/
  type SM[k, v] = fieldType match {  // Not found: type fieldType
    case '[sm] => Type[sm]
    case _ => quotes.reflect.report.errorAndAbort("uh oh")
  }

/*h*/
  case '[sm] =>
   type SM[k1, v1] <: SortedMap[k1, v1] = Type[sm] // cannot combine bound and alias

/*f*/
case '[sm] =>
  type SM = Type[sm]
  fieldType match {
    case '[SM[k, v]] => // SM does not take type parameters

*Subtle Compiler Errors:

// Examples in this snippet lose the association between k, v, sm, and SortedMap[k,v].

// All yield the following error:
// Type argument sm does not conform to upper bound collection.SortedMap[k, v]

/*a*/
  case '[SortedMap[k, v]] =>
    fieldType match {
      case '[sm] if TypeRepr.of[sm].derivesFrom((TypeRepr.of[SortedMap[k, v]]).typeSymbol) =>
        '{SpecialMap.apply[k, v, sm](/***/)} // ... sm does not conform ...

/*b*/
  fieldType match {
    case '[sm] =>
      fieldType match {
      case '[SortedMap[k, v]] if TypeRepr.of[sm].derivesFrom((TypeRepr.of[SortedMap[k, v]]).typeSymbol) =>
        '{SpecialMap.apply[k, v, sm](/***/)} // ... sm does not conform ...

/*c*/
  (fieldType, fieldType) match {
    case ('[sm], '[SortedMap[k, v]]) =>
      '{SpecialMap.apply[k, v, sm](/***/)} // ... sm does not conform ...

/*d*/
  fieldType match {
    case '[sm1] =>
      type SM[k1,v1] = Type[sm1]
      fieldType match {
        case '[SM[k, v]] =>
          '{SpecialMap.apply[k, v, SM[k, v]](/***/)} // ... SM does not conform ...

/*e*/
  fieldType match {
    case '[sm1] =>
    fieldType match {
      case '[SortedMap[k, v]] =>
        type SM[k,v] = Type[sm1]
        '{SpecialMap.apply[k, v, SM[k, v]](/***/)}  // ... SM does not conform ...

Of course, explicitly writing every known concrete class derived from SortedMap works for any specific project, but libraries should accommodate unknown inheritors of the SortedMap trait.
Is there any way to capture all three type parameters along with their interdependent relationships?
Thank you for your consideration.

A: I guess you can't guarantee at the compile time of macro that in
val fieldTypeTree = Inferred(fieldTyepRepr).tpe
val fieldType = fieldTypeTree.asType

(fieldType, fieldTypeTree.baseType(SrtdMapSym).asType) match {
  case ('[sm], '[SortedMap[k, v]]) =>
    '{SpecialMap.apply[k, v, sm](???)}
}

k, v, sm satisfy sm <: SortedMap[k, v].
So if you can't construct the tree via quotation '{SpecialMap.apply[k, v, sm](???)}, you should construct it manually.
Alternatively you can return
'{SpecialMap.apply[k, v, sm & SortedMap[k, v]](???)}.

Also maybe something like the following is possible
val fieldTypeTree = Inferred(fieldTyepRepr).tpe
val fieldType = fieldTypeTree.asType
val parentType = fieldTypeTree.baseType(SrtdMapSym).asType

(fieldType, parentType) match {
  case ('[ft], '[pt]) =>
    '{foo[ft, pt]} match
      case '{
        type k
        type v
        type sm <: SortedMap[`k`, `v`]
        foo[`sm`, SortedMap[`k`, `v`]]
      } =>
        '{SpecialMap.apply[k, v, sm](???)}
  }

// outside def aMacroImpl, otherwise "access to method foo from wrong staging level"
def foo[A, B] = ???

For some reason this still doesn't typecheck: https://scastie.scala-lang.org/DmytroMitin/ZbtQWZFkTma6MlFM72x5Dg/2
Maybe because of bugs:
Type bound is not inferred inside quotation (type variable escapes?)
Pattern matching type variable does not infer bounds
assertion failed: unresolved symbols while pickling quote with type bounds
See also:
https://docs.scala-lang.org/scala3/guides/macros/quotes.html#type-variables-in-quoted-patterns

In some cases we need to define a pattern variable that is referenced several times or has some type bounds. To achieve this, it is possible to create pattern variables at the start of the pattern using type t with a type pattern variable.

fuseMap macro in scala 3
Explicit type conversion in Scala 3 macros
Get information of type in Scala3 macro
Turning inlined varargs into a generic tuple


text:
Q: "Invalid memory address" while testing in Go I have a simple Go function which I want to test:
func root(c echo.Context) error {
    return c.String(http.StatusOK, "This is the root!")
}

My tests look like this:
import (
    "net/http"
    "testing"

    "github.com/labstack/echo"
    "github.com/stretchr/testify/assert"
)

type Context struct {
    echo.Context
}

func TestRoot(t *testing.T) {
    c := new(Context)
    expectedResult := c.String(http.StatusOK, "This is the root!")
    actualResult := c.String(http.StatusOK, "This is the root!")

    assert.Equal(t, expectedResult, actualResult, "they should be equal")
}

Now, when I run the test, I am getting this error:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference

I am fairly new to Go and just want to try to make sense of it. I get it that when I address an object which does not exist, I am getting this error. But every variable assignment I am doing has no change to be nil.

Can somebody point me to a solution? Or tell me how simple unit tests should look like in Go?


text:
Q: TypeScript function argument destructuring with partial types annotation Let's consider example:
function func1(num: number) {
  return num * 2;
}

function func2(by: number, num = func1(1)) {
  return num / by;
}

It works perfectly fine. In func2 I don't have to manually provide a type for num argument since it is provided from func1.
But when I write func2 in form of argument object destructuring I have to manually provide a type for num in func3:
function func3({ by, num = func1(1) }: { by: number, num: number }) {
  return num / by;
}

How to write func3 without retyping type for num? Something like this (code below doesn't work):
function func3({ by, num = func1(1) }: { by: number }) {
  return num / by;
}

A: There is currently no better way to do this unfortunately. Ideas about improving this have been floating around for a while but the compiler team has not found a good one yet. This issue is the latest proposal, @RyanCavanaugh says they are giving it another try, well see what comes of it. For now you have to write the names again in the type annotation


text:
Q: A Remainder and Division Problem I have a question related to remainder and denominator of a division.
abc12 is a five-digit number and xy is a two-digit number. And the division is given as below:
(xy is remainder, 40 is denominator, abc12 is dividend.)

What is the sum of all possible values of xy two-digit numbers?
Thank you.

A: Note that $abc12$ and $40$ are both divisible by $4$, so $xy$ must be as well.  If we call the quotient $k$ we have $40 \cdot k+xy=abc12$.  The ones digit of $40 \cdot k$ must be zero, so $y=2$.  We must also have $x \le 3$, so the only possibilities are $xy=12,32$  Now we need to find $abc$s to show that both of these are possible.  We have  $40012=40 \cdot `1000 +12$ and $40112=40 \cdot 1002+32$.

A: $\dfrac{abc12}{40}=\dfrac{abc\times 100}{40}+\dfrac{12}{40}$
Therefore, $xy=20\left[\text{remainder of }\dfrac{5(abc)}{2}\right]+12$
When abc is even,

$xy= 20 \times 0 + 12 = 12$

When abc is odd,

$xy= 20 \times 1 + 12 = 32$

A: ${\rm mod}\ 40\!:\ \underbrace{1000}_{\large \equiv\ 0}AB\!+\!\underbrace{100}_{\large\equiv\ \color{#0a0}{20}}C\!+\!12\equiv \color{#0a0}{20}\,\color{#c00}C\!+\!12\equiv
\begin{cases} 20(\color{#c00}{2n\!+\!0})\!+\!12\equiv 12,\ \ {\rm for\ even}\ \ \color{#c00}C\\  20(\color{#c00}{2n\!+\!1})\!+\!12\equiv 32,\ \ {\rm for\ \ odd}\ \ \color{#c00}C\end{cases}$


text:
Q: Question on Null space and Dimension
If the null space of a $5\times6$ matrix $A$ is $4$-dimensional, what is the dimension of the row space of $A$?

I think this has to do with the rank nullity theorem, but I'm not sure how exactly you would prove the answer. Thanks


text:
Q: Adding an event listener on load for floating label On page reloads I have floating labels overlapping the input text if the form has been filled out before. To avoid this problem I want to alter the input text's style if there is data in the form.
Here is my code:
https://codepen.io/holly-williford/pen/pONYYM
document.getElementsByClassName("floating").addEventListener("load", hideLabel);

function hideLabel() {
    if(!$('input').val() ) {
        $('floating').addClass('warning');
    } else {

    }
}

Test
<input></input>

warning {
    color: red;
}

A: There are many things from the codepen example that need changes.

*

*HTML

Test
    <input>

*CSS

 .warning { //Notice the '.'
    color: red;
  }

*JS

    window.onload = hideLabel;
    function hideLabel() {
        if(!$('input').val() ) {
              $('.floating').addClass('warning'); // Notice the '.'
        } else {

        }
    }

These modifications should help you get started.
But, you have mentioned jQuery and you don't seem to make the most of it.


text:
Q: Clear the JavaScript sent to Firebug console I want to clear the Firebug console of the JavaScript already sent.
Does something like console.clear() exist and work?

A: If you want to see all the available methods under console:
for(var i in console) {
    console.log(i);
}

A: Just a call to the clear function from the console works. However, I can't seem to clear the console from javascript code, but that seems to make sense (you will lose information).
So in Chrome's console, just type:
clear();

A: console.clear();
works for me

A: You can type clear(); in the Firebug command line. I don't think there's a way to do it from a web page though.

A: _FirebugCommandLine.clear();
Will clear the console

A: console.clear() is part of the Firebug API. I fixed the documentation page:
http://getfirebug.com/wiki/index.php/Console_API#console.clear.28.29
jjb


text:
Q: i18n.exists is not a function while testing via jest / react-testing library I am using react testing library along with Jest. I am not able to mock exists function in test script.
Below is my code.
errorComponent.js
    import { useTranslation } from "react-i18next";

     export default function Error(props) {

       const { t, i18n } = useTranslation();

       return (

         {i18n.exists(props.errorText) ? t(props.errorText) : props.errorText}

       )
     }

myComponent.js
     import { useTranslation } from "react-i18next";

     export default function Error(props) {

       return (

         <Input value="" id="testig-input"/>
         <Error
            errorText={'XYZ'}
          />

       )
     }

myTestFile.test.js
       const temp= document.querySelector(`input[id='testig-input']`);
       fireEvent.change(temp, { target: { value: '' } });

When I try to execute this I am getting error saying that "i18n.exists is not a function". I tried to mock but its not working. Anyone kindly help me to remove this.

A: In your code, you should have an <I18nextProvider> wrapping everything being translated somewhere. When you run the jest test, you need to render the component wrapped in the same way:
render(
  <I18nextProvider i18n={myConfig}>
    <MyComponent />
  </I18nextProvider>
)

Alternatively, can try to mock the exists function, but it is better to more closely mimic how your app is actually run.
import * as i18next from "react-i18next";

jest.spyOn(118next, 'useTranslation').mockReturnValue({
  t: (val) => val,
  i18n: { exists: () => true }
})


text:
Q: Magento2. Homepage Hot sellers I want to get the all products and make changes in these product showing on the homepage

A: This products are shown as widget in home-page-block cms block.
It is Catalog Product list widget, so you can configure Number of Products to Display, template, and wich products to show.

A: You can do an override like this :

app/code/YourNamespace/YourModule/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\CatalogWidget\Block\Product\ProductsList">
        <plugin name="module_widget_override" type="YourNamespace\YourModule\Plugin\Block\Product\MyOverridePlugin" />
    </type>
</config>

app/code/YourNamespace/YourModule/Plugin/Block/Product/MyOverridePlugin.php

<?php

namespace YourNamespace\YourModule\Plugin\Block\Product;

class MyOverridePlugin
{
    die('IT WORKS')
}

If you want to modify the template , open the template path hints LINK . And override the template that is displaying thoses products.
I think this is the template:

vendor/magento/module-catalog-widget/view/frontend/templates/product/widget/content/grid.phtml

Make the logic in this section
<?php if ($showWishlist || $showCompare || $showCart): ?>

                                        <?php if ($showCart): ?>

                                                <?php if ($_item->isSaleable()): ?>
                                                    <?php if ($_item->getTypeInstance()->hasRequiredOptions($_item)): ?>
                                                        <button class="action tocart primary" data-mage-init='{"redirectUrl":{"url":"<?= $block->escapeUrl($block->getAddToCartUrl($_item)) ?>"}}' type="button" title="<?= $block->escapeHtmlAttr(__('Add to Cart')) ?>">
                                                            <?= $block->escapeHtml(__('Add to Cart')) ?>
                                                        </button>
                                                    <?php else: ?>
                                                        <?php
                                                            $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
                                                            $postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()])
                                                        ?>
                                                        <button class="action tocart primary" data-post='<?= /* @noEscape */ $postData ?>' type="button" title="<?= $block->escapeHtmlAttr(__('Add to Cart')) ?>">
                                                            <?= $block->escapeHtml(__('Add to Cart')) ?>
                                                        </button>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <?php if ($_item->getIsSalable()): ?>

<?= $block->escapeHtml(__('In stock')) ?>

                                                    <?php else: ?>

<?= $block->escapeHtml(__('Out of stock')) ?>

                                                    <?php endif; ?>
                                                <?php endif; ?>

                                        <?php endif; ?>


text:
Q: Alarm Action "Terminate EC2 Instance" failed when I start a certain type of instance the userdata-script creates a metric + alarm via Boto.
The metric delivers its data to CloudWatch correctly.
The alarm should terminate the instance as an action if some condition based on the metric matches.
In CloudWatch the alarm seems to be created correctly and it switches the alarm-states as desired.
BUT:
When it comes to execute the action it fails with the following "history" entry:
Alarm updated from

*

*OK to ALARM. Reason: Threshold Crossed: 5 datapoints were greater than the threshold (200.0). The most recent datapoints: 999.0, 999.0.

*arn:aws:automate:eu-west-1:ec2:terminate is in progress.

*Terminate EC2 Instance 'i-xxx' action failed. AWS was not able to validate the provided access credentials.

I've already granted the policy "AdministratorAccess" to the "userdata"-Role which is attached to the instance.
Any hints?
Regards
Tom

A: I believe this is the issue. From the developer guide:

If you are using an IAM role (e.g., an Amazon EC2 instance profile),
  you cannot stop or terminate the instance using alarm actions.
  However, you can still see the alarm state and perform any other
  actions such as Amazon SNS notifications or Auto Scaling policies.

I recently posted in the AWS Forum about this issue myself:
https://forums.aws.amazon.com/message.jspa?messageID=601951

A: I just occured this question and seems I have resolved it.
The CloudWatch Alarm's service-linked IAM role is AWSServiceRoleForCloudWatchEvents.
I find its Trusted entities is events.amazonaws.com. And its policy document in the Trust relationships tag,
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

And my ec2 instance's role policy document in the Trust relationships tag
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

And then add the Trusted entities, events.amazonaws.com content to the ec2 instance's role policy document, as follow:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    },
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

It add an trusted entity of events.amazonaws.com to the role.
Then, the CloudWatch Alarm to stop instance function is OK!


text:
Q: Corrupted PDF When Saving to Database over 50kB I have a webpage where the user can upload a PDF file and send it using AJAX to my Flask application. Here is the ajax code:
var formData = new FormData();
formData.append('attachment', document.getElementById("attachment").files[0]);
$.ajax({
    type: 'POST',
    url: 'process_award_storage',
    contentType: false,
    processData: false,
    data: formData
})

I do not think that this has any problems because I can print out the content and title of file in the python code. Then my flask model is defined as such, using LargeBinary for the PDF attachment:
class AwardStore(db.Model):
    __tablename__ = 'awards_store'
    id = db.Column(db.Integer, primary_key=True)
    ...
    file = db.Column(db.LargeBinary, nullable=True) #I am sure this is the right file type for PDF saving

Lastly, here is how the AJAX file is saved to the database:
     award = AwardStore(name=name, file=request.files['attachment'].read())
     db.session.add(award)
     db.session.commit()

I can see using my MySQL Workbench that it is saved. However, when I try to download the BLOB from there to the Desktop and open it, it says "Failed to load PDF document". The same happens when I use flask's send_file. It seems like I did everything as I saw online, but something is wrong.
Maybe these warnings are related?:
C:\Users\msolonko\Desktop\NICKFI~1\CACHTM~1\APP_DE~1\virt\lib\site-packages\pymysql\cursors.py:170: Warning: (1300, "Invalid utf8 character string: 'C4E5F2'")
  result = self._query(query)
C:\Users\msolonko\Desktop\NICKFI~1\CACHTM~1\APP_DE~1\virt\lib\site-packages\pymysql\cursors.py:170: Warning: (1265, "Data truncated for column 'file' at row 1")
  result = self._query(query)

I tried googling them and did not find anything. I appreciate any assistance.
EDIT:
I noticed that small files are typically uploaded and displayed properly. The issue is with files with sizes > ~50kB. The database I am using the AWS RDS, Is there a setting I can change somewhere to enable greater sizes?

A: The LargeBinary accepts a length field also.
which converts to mysql's BLOB whose default length is 65535 bytes (64kb).
Try increasing the length and set it to
a MEDIUMBLOB for 16777215 bytes (16 MB)
a LONGBLOB for 4294967295 bytes (4 GB).
Hope this will help


text:
Q: adding a row to pandas dataframe with column averages I have a pandas dataframe
 df = pd.DataFrame([[0,1,10,15],[1,5,7,10],[10,15,0,0]], columns=['Apple','Orange','Banana','Pear'], index=['basket1','basket2','basket3'])

I need to generate a dataframe that looks like
Fruit   Apple   Orange   Banana  Pear  mean_basket

basket1   0        1       10     15     6.5

basket2   1        5        7     10     5.75

basket3   10       15       0      0     6.25

mean_fruit 3.66     7       5.66   8.33   6.16

I did df['mean_basket'] = df.mean(axis=1) and generated the last column.
By df.mean(axis=0), I get the mean of each column but I do not know how to add it as a new row to the dataframe. Please help.

A: df = pd.DataFrame([[0,1,10,15],[1,5,7,10],[10,15,0,0]], columns=['Apple','Orange','Banana','Pear'], index=['basket1','basket2','basket3'])
df['mean_basket'] = df.mean(axis=1)
df.loc['mean_fruit'] = df.mean()
df

A: df.append(df.mean().rename('mean_fruit')).assign(mean_basket=lambda df: df.mean(1))

                Apple  Orange     Banana       Pear  mean_basket
basket1      0.000000     1.0  10.000000  15.000000     6.500000
basket2      1.000000     5.0   7.000000  10.000000     5.750000
basket3     10.000000    15.0   0.000000   0.000000     6.250000
mean_fruit   3.666667     7.0   5.666667   8.333333     6.166667

Or using pipe
df.assign(
    mean_basket=df.mean(1)
).pipe(lambda df: df.append(df.mean().rename('mean_fruit')))

                Apple  Orange     Banana       Pear  mean_basket
basket1      0.000000     1.0  10.000000  15.000000     6.500000
basket2      1.000000     5.0   7.000000  10.000000     5.750000
basket3     10.000000    15.0   0.000000   0.000000     6.250000
mean_fruit   3.666667     7.0   5.666667   8.333333     6.166667


text:
Q: How do I develop CUDA application on my ATI, to be later executed on NVIDIA My computer has an ATI graphics card, but I need to code an algorithm I already have in CUDA, to accerelate the process.  Is that even possible?  If yes does anyone have any link or tutorial from setting up my IDE to coding a simple image processing or passing an image.  I also considered OpenCL but I have not found any information how to do anything with it.

A: This answer is more directed toward the part

I also considered OpenCL but I have not found any information how to do anything with it.

Check on this NVIDIA site:
http://developer.nvidia.com/nvidia-gpu-computing-documentation
Scroll down and you find

*

*OpenCL Programming Guide

This is a detailed programming guide for OpenCL developers.

*OpenCL Best Practices Guide

This is a manual to help developers obtain the best performance from OpenCL.

*OpenCL Overview for the CUDA Architecture

This whitepaper summarizes the guidelines for how to choose the best implementations for NVIDIA GPUs.

*OpenCL Implementation Notes

This document describes the "Implementation Defined" behavior for the NVIDIA OpenCL implementation as required by the OpenCL specification Version: 1.0. The implementation defined behavior is referenced below in the order of it's reference in the OpenCL specification and is grouped by the section number for the specification.

On AMD/ATI you have this site for a brief introduction:
http://www.amd.com/us/products/technologies/stream-technology/opencl/pages/opencl-intro.aspx
And for more resources check:
http://www.amd.com/us/products/technologies/stream-technology/Pages/training-resources.aspx
Unless CUDA is a requirement you should consider OpenCL again as you can you use it on both platforms and you state have one and want to develop for the other.

A: You might also want to take a look at these:
http://blogs.nvidia.com/2011/06/cuda-now-available-for-multiple-x86-processors/
http://www.pgroup.com/resources/cuda-x86.htm
I haven't tried it myself, but the prospect of running CUDA code on x86 seems pretty attractive.


text:
Q: stdlib.h alternative in Linux kernel? When developing a kernel module in Linux, using the C standard library isn't allowed.
However, in case I need to use some common functionality like strcat(), where do I need to go to?

A: Whatever is not implemented in the Linux kernel, you have to implement yourself or borrow from another open source kernel module.  However, you'll find that strcat is implemented in the kernel.
See the kernel API documentation.  Specifically the Basic C Library Functions section for your general question, and the String Manipulation section for your specific question about strcat.
You'll want to include linux/string.h.
I don't know why the kernel API documentation doesn't actually show the header file that you have to include to get the function.  But if you're looking for something, you can restrict your search to /include/linux because that is where header files go if they have functions that are shared amongst different parts of the kernel.
Header files outside /include/linux contain definitions only for source files residing in the same directory as the header.  The exception is /arch/.../include, which will contain architecture-specific headers instead of platform independent ones.

A: Sorry @eq - thinking of another function.
Why not
void (char *d, const char *s);
{
   if (*d)
   {
       for (; *d; ++d) {} ;
      --d;
   }
   strcpy(d, s);
}

I could do strcpy if you wish


text:
Q: PHP if then else inside an array Sorry for repeated (no doubt) question, but other answers have slightly confused me.
So I have an array like this:
$testflag = '';

    $test = array(

    'auxiliaryFields' => array(
        array(
            'key'   => 'extra1',
            'label' => 'TEST',
            'value' => 'TEST',
            'textAlignment' => 'PKTextAlignmentLeft'
        )
        if ($testflag != ''){
        ,
        array(
            'key'   => 'extra2',
            'label' => 'TEST2',
            'value' => 'TEST2',
            'textAlignment' => 'PKTextAlignmentLeft'
        )
    }

    ));

    var_dump($test);

Now, I've read that you can't use code inside an array, so my question is how to do the above?  In this example it's just 2 arrays (extra1 & extra2) but I have 4 arrays in total in my actual code.  The condition is basically if session:form:element:not_null then include extra2 - 3 - 4 and so on, if it IS null, do nothing.
Can someone please help?

A: This is similar to mzedeler answer but it work
$testflag = 'test';

$test = array(

'auxiliaryFields' => array(
    array(
        'key'   => 'extra1',
        'label' => 'TEST',
        'value' => 'TEST',
        'textAlignment' => 'PKTextAlignmentLeft'
    )
));

var_dump($test);
if ($testflag != ''){
    $test['auxiliaryFields'][]=array(
        'key'   => 'extra2',
        'label' => 'TEST2',
        'value' => 'TEST2',
        'textAlignment' => 'PKTextAlignmentLeft'
    );
}

var_dump($test);

I've changed $test['auxiliaryFields'][0][] with $test['auxiliaryFields'][] and fixed a sintax error (missing ;)

A: Something like this.
    $testflag = '';

    $test = array(

    'auxiliaryFields' => array(
        array(
            'key'   => 'extra1',
            'label' => 'TEST',
            'value' => 'TEST',
            'textAlignment' => 'PKTextAlignmentLeft'
        )
    ));
    if ($testflag != '') {
        $test['auxillaryFields'][] =
        array(
            'key'   => 'extra2',
            'label' => 'TEST2',
            'value' => 'TEST2',
            'textAlignment' => 'PKTextAlignmentLeft'
        )
    }

A: You can't use a conditional in an array as you've done in your snippet. You can add extra values to an array after the array is declared.
For example
if (something) {
   $test[] = $someArray;  // $test[] is next element, so
                          // add $someArray as next element of $test
}

Your snippet becomes:
$testflag = '';
// set up array here
$test = array(

'auxiliaryFields' => array(
    array(
        'key'   => 'extra1',
        'label' => 'TEST',
        'value' => 'TEST',
        'textAlignment' => 'PKTextAlignmentLeft'
    )
);

// conditionally, add an extra element.
if ($testflag != ''){
    $test[] =
        array(
        'key'   => 'extra2',
        'label' => 'TEST2',
        'value' => 'TEST2',
        'textAlignment' => 'PKTextAlignmentLeft'
    );
}

var_dump($test);


text:
Q: Repopulate radio buttons on failed validation I have a form that pulls data from a database.
Code works fine if it's an input box but I can't get the latest $_POST data for radio buttons.
This works for input text box. I get default values pulled from the DB on first load, and I can get the new input (if any) from the user modifies the input box on a failed validation.
<?php echo form_input('email',set_value('email', $email)); ?>

Here's the code for one of my radio button. It works when I'm pulling data from the DB, but if the form refreshes due to a failed validation, I'm not sure how I can show what the user selected.
<input type="radio" name="gender" value="male" <?php if($gender == "male") echo "checked";  ?> />Male

I played around with set_radio but i ran into the same issue. This works on initial load, but what about on a failed validation? I tried throwing "set_radio" in the second paramter but that didn't work either.
if($gender == "male") {
    echo form_radio('gender', 'male',TRUE)
} else {
   echo form_radio('gender', 'male')
}

A: From the CodeIgniter UserGuide.
<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />

<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />

The first parameter is the name of the radio set, the second is the current radio's value, and the third is an option default if there is no data to populate the field with.

A: After looking at several code examples, I noticed that the set_radio function HAD TO BE in the value parameter of the form_radio function.  Since you can't have an echo within an echo, I created a "hack" by putting an empty string in the value parameter and then appending the set_radio function to it.  Here is my example:
echo form_radio('gender', 'M', ''.set_radio('gender', 'M'), $js)."Male ";
echo form_radio('gender', 'F', ''.set_radio('gender', 'F'), $js)."Female ";

A: There seems to be a bug. Unless you include a validation rule for the radio buttons, they do not get repopulated upon postback.
You can include a rule like this.
 $this->form_validation->set_rules('active', 'active', 'required');

if you had..

   <input type="radio" name="active" id="lesson-active" value="1" <?php echo set_radio('active', '1', TRUE); ?> />
   Active

   <input type="radio" name="active" id="lesson-deactivated" value="2" <?php echo set_radio('active', '2'); ?> />
   Deactivated

A: Looks like I was able to use the same code as I would for a text box.


text:
Q: Pubsub Pull Subcription with GVisor (CloudRun) issue I would like to pull a Google PubSub subscription with Go. It works well locally but when I deploy it on Cloud Run, impossible to pull any message.
Here my code snippet
func (pubSubService *pubSubService) Received() (msgArray []*pubsub.Message, err error) {
    ctx := context.Background()
    cctx, cancel := context.WithCancel(ctx)
    msgArray = []*pubsub.Message{}

    var receivedMessage = make(chan *pubsub.Message)

    go func() {
        for {
            select {
            case msg := <-receivedMessage:
                msgArray = append(msgArray, msg)
            case <-time.After(pubSubService.waitTimeOutInMillis * time.Millisecond):
                cancel()
            }
        }
    }()

    err = pubSubService.client.Subscription(pubSubService.subscriptionName).Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
        receivedMessage <- msg
        msg.Ack()
    })
    if err != nil {
        return
    }

    return
}

Here the log error
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x7,0x6,0x12,0xc00006f204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x5,0x6,0x12,0xc0003c1204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0xa,0x6,0x12,0xc0003bd204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0xc,0x6,0x12,0xc00037d204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x6,0x6,0x12,0xc0002d3204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x8,0x6,0x12,0xc00052b204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x9,0x6,0x12,0xc000391204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0xb,0x6,0x12,0xc00043b204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x6,0x6,0x12,0xc0003b3204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0xc,0x6,0x12,0xc0003d3204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x7,0x6,0x12,0xc000391204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0x5,0x6,0x12,0xc000309204,0x4,0x0)
D  Container Sandbox Limitation: Unsupported syscall setsockopt(0xb,0x6,0x12,0xc0004d3204,0x4,0x0)

The Received call is filter by the GVisor sandbox of Cloud Run
Do you know workarround or ReceiveSetting to set for this issue ?
Thanks in advance.

A: No it's wrong. I found my issue: I over estimated the GCP global network: My timeout which cancel the polling was set to 200ms. With this requirement, my app don't have the time to recover the first message before the cancel. With 2000ms of timeout, it work perfectly !
Go routine are allowed with Cloud run, but they can't survive after the reply of the http request.

A: Pull subscription doesn't work in Cloud Run because the container gets throttled or even terminated out of request scope.
The goroutine is not able to proceed.


text:
Q: How to define an empty parameter for minipage minipage supports  empty values for its optional arguments:
\begin{minipage}[c][][c]{1cm} test \end{minipage}

or
\begin{minipage}[c][\relax][c]{1cm} test \end{minipage}

but it doesn't if that empty values are passed by a macro:
\def\param{}
\begin{minipage}[c][\param][c]{1cm} test \end{minipage}

or
\def\param{\relax}
\begin{minipage}[c][\param][c]{1cm} test \end{minipage}

How can I properly define the macro, so that minipage takes an empty value?

A: The internal code for minipage uses the optional arguments when processing \endminipage. At a certain point, \@iiiparbox is called, which does \ifx\relax#2, where #2 is the second optional argument (or \relax if the optional argument is empty). Since no expansion is performed by \ifx, your code compares
\ifx\relax\param

which returns false, because \param is a macro expanding to \relax, not the same as \relax (assuming you gave \def\param{\relax}; or it expands to nothing, which again is not the same as being empty when the argument is absorbed if you give \def\param{}.
By the way, \def\param\relax is incorrect syntax; in the two lines in the second example you're defining \param with parameter text \relax\begin, expanding to minipage. But the intended \def\param{\relax} (that I assumed in the answer) will not work, as explained.


text:
Q: Swift ios unwind to root ViewController tab from anywhere I have a tab based app. And I wonder if its possible to unwind the user from anywhere to the root of the current tab.
My app is built like this: TabController -> (tabs) -> navigationController -> vc etc..
So lets say that I press on tab 4 in my app. Now I dig through two viewcontrollers and end up in a modal presented VC. Now I want to go back straight to the root of the tab:
tab 4 -> navigationController -> rootVC -> pushVC -> pushVC -> modalVc
So I eg from modalVc to rootVC
I know that I can do something like this, BUT I want to go to the rootVC from any VC within tab4, and using that technique would force me to create a unwind segue on all of my child VCs in tab 4
I am using notifications and when a user press on the notification I want to take the user to the rootVC from anywhere.
And using something like:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "accountVc") as? AccountViewController
                      navInTab.pushViewController(destinationViewController!, animated: false)

Does not work for eg: vc -> vc -> modalVc
since it will mess up the navigationstack

A: You can pop to the root of a navigation stack, or pop to the nth element in the stack, or replace the stack of view controllers with a different stack.
You can use popToRootViewController on the navigationController to go back to the very root of a navigation stack. Or suppose you want to go back to the first VC in the stack for example, you would do something like
let controllerStack = self.navigationController?.viewControllers
_ = self.navigationController?.popToViewController((controllerStack?[0])!, animated: true)

Or you can replace the navigation stack of view controllers with a new stack of controllers i.e.
NSMutableArray *controllerStack = [NSMutableArray arrayWithArray:navigationController.viewControllers];
// Replace the source controller with the destination controller, wherever the source may be
[controllerStack replaceObjectAtIndex:[controllerStack indexOfObject:sourceViewController] withObject:destinationController];

// Assign the updated stack with animation
[navigationController setViewControllers:controllerStack animated:YES];


text:
Q: What are the Item restrictions during VS races? In Mario Kart Wii, certain items have restrictions for when or under what condition they may be gotten. By this, I do not mean the items based on placement system.
Some Items can be pulled only after a certain time limit. For example, the Shock can be used only once in 30 seconds. I know there are other items that have similar use restrictions, but what are these items, and what restriction do they have?

A: I'm not sure about other items with time restrictions. But I do know that some items are restricted to only one existing in a race at a time.
For example, only 1 blue shell can exist at any one time.
So if someone gets a blue shell from an item box, they could hold onto it the whole race, and no one would ever get a blue shell.
I believe Bullet Bill follows this rule too.
There's a good chance that there's a "cooldown" for bloopers/POW blocks too, as you never really see two of them at the same time, and they also hit multiple players at once.


text:
Q: SSL_ERROR_BAD_CERT_DOMAIN after installing certificate I use letsencrypt-nginx-proxy-companion Docker image for generate my all subdomaine with SSL certificate.
For my first subdomain it work nice, but for my seconde, i've this error on my browser :
SSL_ERROR_BAD_CERT_DOMAIN

secondSubDomain.my-site.com uses an invalid security certificate. The certificate is only valid for firstSubDomaine.my-site.com.

I don't undetstand why, because i see all .chain.pem and .crt by sub-domain on the certs folder :/
My docker-compose file for my secondSubDomain :
version: "3"

services:
  jackett:
    image: linuxserver/jackett
    container_name: jackett
    restart: always
    environment:
      - PGID=1000
      - PUID=1000
      - TZ=Europe/London
      - VIRTUAL_HOST=jackett.${SITE_URL}
      - VIRTUAL_PORT=9117
      - LETSENCRYPT_HOST=jackett.${SITE_URL}
      - LETSENCRYPT_EMAIL=${MAILER_DEFAUT_SENDER_ADDRESS}
    volumes:
      - ${MOUNT_POINT}/jackett/config:/config
      - ${MOUNT_POINT}/jackett/downloads:/downloads
    ports:
      - "9117:9117"
    expose:
      - 9117

networks:
    default:
        external:
            name: nginx-proxy

Anyone can help me ?
Thank you community !


text:
Q: Is this a good centralized DVCS workflow? I'm leaning toward using Mercurial, coming from Subversion, and I'd like to maintain a centralized workflow like I had with Subversion. Here is what I am thinking:
stable (clone on server)
    default (branch)
    development (clone on server)
        default (branch)
        bugs (branch)
            developer1 (clone on local machine)
            developer2 (clone on local machine)
            developer3 (clone on local machine)
        feature1 (branch)
            developer3 (clone on local machine)
        feature2 (branch)
            developer1 (clone on local machine)
            developer2 (clone on local machine)

As far as branches vs. clones is concerned, does this workflow make sense? Do I have things straight?
Also, the 'stable' clone IS the release. Does it make sense for the 'default' branch to be the release and what all other branches are ultimately merged into?

A: In Mercurial, branches (created with hg branch inside the same repository) are currently irreversible. Once introduced, you can only remove them from your branch namespace by doing a history rewrite. That's why I would only create real branches if either the project lifetime is low (only a few feature branches) or branches are generic enough to remain current for many years (like "stable", "bugfix" etc.). As far as I know, branches are (as with everything else) created locally without your control, so if anyone decides to use a branch, that branch will also show up in your main repository after a pull/push.
The effect is that - in your structure - after a pull from development into stable you would also get feature1 and feature2 branches merged into stable, being quite useless. Pulling stable into development because you fixed bugs on a stable version will also merge the branch bugs into development. You can try that by creating a stable repository, clone it to development, branch to feature1 in development and pull development into stable (commit some changes between these steps): the branch name will appear with an inactive head in stable although you merged it:

stable $ hg branches
default                        4:1c3cd0d1a523
feature2                       3:82879465c5f3
feature1                       2:5d7480426f21 (inactive)
bugs                           1:116860d2d85e (inactive)

I remember that Git is able to delete branches but Mercurial has some development going on to catch up on that topic; I'm not sure this is still up-to-date, so please correct me if I'm wrong.
[Edit] According to Pruning Dead Branches in the Mercurial wiki there are 4 ways to "remove" a branch. The only way to really permanently remove a branch name and not just to close (deactivate) it is by replacing the repository with a cleaned history. [/Edit]
From what I have heard and seen, it's more common to create clones instead of a branches when using Mercurial. I remember having had the same thoughts as you when I switched from SVN to Mercurial last year. The usual approach is different from centralized version control because branching can happen at any time without central control over it, so clones are the preferred way to "branch" to not pollute the branch namespace and to keep developments seperated and flexible (you will always retrieve the full repository if you pull/clone including all branches and if you just want to branch to test something you would have to choose a unique branch name that's permanent and thus will show up for everyone in your project). Although that approach seems like a waste of disk space and you need to keep track of where your branches are (usually inside some project folder on your user account and inside your IDE), it seems to be a much more flexible and practical way of handling branches. (It reads more difficult than when you actually use it yourself.)
Having had a number of smaller projects using Mercurial, this is what worked for our company so far (with only a few active developers per project):
On the server:
projectname-main
development is being pushed to and pulled from there; this is the "authoritative" development "branch" to keep a team's repositories in sync
projectname-stable
if a version gets released/deployed this is where -main gets pushed to; only bugfixes are done in -stable and then pulled back to -main: Following the advice from the Mercurial Guide by Bryan O'Sullivan, bugfixes to versions considered more stable (e.g. previous releases) can usually be pulled back into development branch but changes in the development branch can contain newer, unstable features that should not be pulled into a maintenance branch unless a release (or similar) happens.
Locally on developer machines:
projectname-main is cloned once, being worked on and synchronized by doing a pull (+merge) and push back to the server regularly.
If there's a feature "branch" needed we clone -main (either locally or from server) and name the clone "projectname-featuredescription". For backup purpose or centralized sharing we also create a clone on serverside and push there. If the feature is ready for -main, we pull -featuredescription into our local -main, merge the changes, pull -main from server, merge again and push -main back to the server. If changes happen to -main while we work on -featuredescription we can easily pull from -main and merge the changes (without pushing back to -main yet because we don't want the feature to be there yet).
The downside compared with real branches is that you won't be able to easily recognize where changesets came from after they are merged with one of their parents. But that hasn't been a problem for us yet (commit messages were useful enough or the separation of feature branches was uninteresting once they were merged with their parent repositories).
Thinking of bigger projects I came up with the following scheme that should work (but which I didn't use yet) similar to a centralized version control. It relies on restricted write access to the server side "authoritative" repositories, so only privileged developers (project lead) are allowed to merge and push there. Additionally, there's a CI server as a gatekeeper to another repository -main-tested which is a subset of -main containing only CI approved changesets with a slight delay.
On server:
projectname-main
development; only a few people have write access, changes going to main need to be pulled by them; they are in control of what feature branches are merged
projectname-main-tested
development; noone should write here unless something went wrong, because tested means a Continuous Integration system succeeded in building -main and pushed that revision into -main-tested, so code in here is verified and should not break compilation or tests
projectname-stable
projectname-stable-tested
same strategy for a stable "branch"; as before, we push -main to -stable on releases and work on bugfixes, -stable-tested is CI approved
And of course there need to be multiple repositories somewhere where teams/developers can actually push their daily work to since -main is now for authoritative changes only (of course they can work entirely locally but they have to sync somewhere if they don't like to peer with each other using hg serve or setup their own servers or care for backup).
Another option to reduce commits and repositories/branches would be to use the mq extension to working with a patch queue. However, I find using clones or branches easier, at least for small projects.

A: What you are doing here is establishing a workflow of merges that should be followed repository (branch) after repository.
Regarding that workflow, I would take the bug branch/repo outside development, because it is usually a branch made after the stable (i.e. released into production) branch that you isolate some bug fixes
stable (clone on server)
    default (branch)
    bugs (branch)
        developer1 (clone on local machine)
        developer2 (clone on local machine)
        developer3 (clone on local machine)
    development (clone on server)
        default (branch)
        feature1 (branch)
            developer3 (clone on local machine)
        feature2 (branch)
            developer1 (clone on local machine)
            developer2 (clone on local machine)

, and not all bug fixes will end up in the development branch, since some of those fixes are tailored only for the current release, while the current development may have already made them obsolete.

Does it make sense for the 'default' branch to be the release and what all other branches are ultimately merged into?

I would also use the first "default" branch (right beneath the stable one) as a consolidation branch, because not every features will end up in that consolidation branch: some of those currently developed features are too complex to be ready in time for the next release.

A: Much may depend on development workflow in your team. In the last (small) team I worked in (we used svn though) - separate bugs branch finally became redundant, the bugs were fixed in the branch they belong. Also we didn't use a separate stable branch but rather stabilized the development branch for the release.


text:
Q: Add printer VBS Script SWbemObjectEx Access denied The script runs fine when run as admin on the local computer, but when deployed via GPO as a startup script gets 'access denied' from SWbemObjectEx.put_. Here's the whole script:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

On Error Resume Next
''--- in case the driver is already there
REM *** Installs printer driver needed for Universal PS 64 Bit
Set objDriver = objWMIService.Get("Win32_PrinterDriver")
objDriver.Name = "HP Universal Printing PS"
objDriver.FilePath = "\\share$\Drivers\Printers\HP\HP-Universal\x64\"
objDriver.InfName = "\\share$\Drivers\Printers\HP\HP-Universal\x64\hpcu155v.inf"
objDriver.SupportedPlatform = "Windows NT x64"
objDriver.Version = "3"
errResult = objDriver.AddPrinterDriver(objDriver)

rem *** Installs a TCP/IP printer local port on a computer
Set objNewPort = objWMIService.Get _
 ("Win32_TCPIPPrinterPort").SpawnInstance_
objNewPort.Name = "IP_172.17.87.226"
objNewPort.Protocol = 1
objNewPort.HostAddress = "172.17.87.226"
objNewPort.PortNumber = "9100"
objNewPort.SNMPCommunity = "public"
objNewPort.SNMPEnabled = False
objNewPort.Put_

rem *** installs printer
Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_
objPrinter.DriverName = "HP Universal Printing PS"
objPrinter.PortName = "IP_172.17.87.226"
objPrinter.DeviceID = "HP LaserJet P2055dn in TPCS-400"
objPrinter.Shared = False
objPrinter.Location = "TPCS-400"
objPrinter.Put_

I used a second version of the script to debug by adding liberal entries like so:
writeLineToLog("addPrinterDriver errResult=" & errResult)
If Err.Number <> 0 Then
    writeLineToLog("Error: " & Err.Number)
    'writeLineToLog("Error (Hex): " & Hex(Err.Number))
    writeLineToLog("Source: " &  Err.Source)
    writeLineToLog("Description: " &  Err.Description)
    Err.Clear
End If

and another to determine the current user, here's the output of the debug:
starting script at 2/16/2017 2:41:29 PM
addPrinterDriver errResult=0
after Installs a TCP/IP printer local port on a computer
The current user is SYSTEM
after Set objPrinter
after objPrinter.DriverName =
after objPrinter.PortName =
after objPrinter.DeviceID =
after objPrinter.Shared =
after objPrinter.Location=
after objPrinter.Put_
after Installs printer
Error: -2147217405
Source: SWbemObjectEx
Description: Access denied

The error is coming when the last put_ is tried.

A: Is this a user or machine GPO Policy? I would suspect if it is user that the actual user might not have permissions to add the printer.
You could try to follow this guide from MSDN's blog to give the user's access. Though I would personally recommend you deploy printers through the GPO built in functions, which you could find a guide for here.


text:
Q: Linux server backup with PHP? I manage a VPS of my client. He wanted a backup solution includes some folders and mysql databases. OS is Ubuntu, web server is apache. I don't want my client to mess with ssh or ftp.
I think i can save database backup files and trigger PHP's exec function from a wab page to zip folders and database backup files, then give a link to download this zip file.
This is technically possible but i wonder if there is a better solution except automatically copying backup files to another server. Because creating backups anytime is required in my situation.

A: There are lots of possibilities, here is a very simple one we use every day:

*

*create a backup script (e.g. in bash) with the usual suspects as mysqldump, tar and date

*make sure, this backup script locks against double runs

*create a cron job, that runs every minute, checks if a flagfile exists, and if yes starts the backup script and then clears the flagfile

*if you want, create more cron jobs (e.g. a daily one), that do nothing but set the flagfile

*create a trivial PHP script, that just touches the flagfile to trigger an adhoc backup

*You can download the finished backup package, once the flagfile is cleared (again check via a trivial PHP script)


text:
Q: How to format this association fetching sequelize I have an association many to many with two tables, products and orders. In my pivot table i save the id, quantity and price of the product. When I fetch the product i need the name of this product, but to get the name I need to get in the product table. The response of my fetching return like this
{
    "id": 111,
    "name": "Matheus",
    "phonenumber": "69993750103",
    "reference": null,
    "value_subtotal": "10.000",
    "value_delivery": "5.000",
    "value_total": "15.000",
    "status": "pending",
    "products": [
        {
            "name": "Açai 350ml",
            "OrdersProducts": {
                "quantity": 2,
                "price": "0.000"
            }
        },
        {
            "name": "acai 350ml",
            "OrdersProducts": {
                "quantity": 3,
                "price": "0.000"
            }
        }
    ]
}

but i need the json in this format
{
    "id": 111,
    "name": "Matheus",
    "street": "Rua olavo bilac",
    "phonenumber": "69993750103",
    "number": "3511",
    "reference": null,
    "note": "Retirar o morango",
    "value_subtotal": "10.000",
    "value_delivery": "5.000",
    "value_total": "15.000",
    "status": "pending",
    "createdAt": "2021-10-20T18:26:25.000Z",
    "updatedAt": "2021-10-20T18:26:25.000Z",
    "products": [
        {
            "name": "Açai 350ml",
            // here the difference, i want create a single object in the return, with all data i need of the product
            "quantity": 2,
            "price": "0.000"
            }
        },
        {
            "name": "acai 350ml",
            "quantity": 3,
            "price": "0.000"

        }
    ]
}

My controller
 async getOrder(req, res) {
        const { id } = req.params;

        const order = await Orders.findByPk(id, {include: [{
            association: 'products',
            attributes: ['name'],
            through: {
                attributes:['quantity', 'price'],

            },
            raw: true,
        }]})
        if (!order) return res.status(404).send({ message: 'order ${`id`}' })
        return res.json(order);
    },

A: Maybe you can implement the query without the association but using model.
 async getOrder(req, res) {
    const { id } = req.params;

    const order = await Orders.findByPk(id, {include: [{
        model: Product,
        attributes: ['name'],
        include: [{
            association: "OrdersProducts",
            attributes:['quantity', 'price'],
            raw: true,
        }],
    }]})
    if (!order) return res.status(404).send({ message: 'order ${`id`}' })
    return res.json(order);
},

You will still get order.quantity and order.price as a name at product as properties.

A: var a = {
  "id": 111,
  "name": "Matheus",
  "phonenumber": "69993750103",
  "reference": null,
  "value_subtotal": "10.000",
  "value_delivery": "5.000",
  "value_total": "15.000",
  "status": "pending",
  "products": [{
      "name": "Açai 350ml",
      "OrdersProducts": {
        "quantity": 2,
        "price": "0.000"
      }
    },
    {
      "name": "acai 350ml",
      "OrdersProducts": {
        "quantity": 3,
        "price": "0.000"
      }
    }
  ]
};

var orders = [];
orders.push(a);

var updatedOrders = orders.map(function(order) {
  order.products.forEach(function(product) {
    product.price = product.OrdersProducts.price;
    product.quantity = product.OrdersProducts.quantity;
    delete product.OrdersProducts;
  });
  return order;
});
console.log(updatedOrders);

A: If you have control over the order and/or product object, you can add custom toJSON method. You can format the json output away you want.
https://futurestud.io/tutorials/create-a-custom-tojson-function-in-node-js-and-javascript
If you do not have control of the object, a function could be made to format the order.
const order = {
"id": 111,
"name": "Matheus",
"phonenumber": "69993750103",
"reference": null,
"value_subtotal": "10.000",
"value_delivery": "5.000",
"value_total": "15.000",
"status": "pending",
"products": [
    {
        "name": "Açai 350ml",
        "OrdersProducts": {
            "quantity": 2,
            "price": "0.000"
        }
    },
    {
        "name": "acai 350ml",
        "OrdersProducts": {
            "quantity": 3,
            "price": "0.000"
        }
    }
  ]

};
 order.products = order.products.map(({OrdersProducts, ...other}) => ({...other, ...OrdersProducts}));

I prefer custom toJSON methods. This, of course, depends on the access to the object structure.


text:
Q: Is an `enum` definition inside a class shared between class instances, or copied for each instance? class MyClass
{
    public:
        enum ErrorCodes
        {
            ERR_SUCCESS     = 1,
            ERR_READ        = 2,
            ERR_WRITE       = 3,
            // ...
            ERR_ALLOCATE    = 99,
            ERR_DELETE      = 100
        };

        ErrorCodes DoSomething();
};

MyClass::ErrorCodes MyClass::DoSomething()
{
    // ...
    return ErrorCodes::ERR_SUCCESS;
}

In my example code there is a very long enum definition which has 100 variables in it. Assuming that each variable holds 4 bytes of memory, the enum will be using 400 bytes of memory. What will happen once I start creating objects of this class? Will each object consume extra 400 bytes of memory because of this enum, or will the enum be shared between all of the objects of this class, so that a only fixed 400 bytes will be used regardless the number of class instances initialized?
If a 400-byte memory is to be used for each instance, what alternative approach can I use in this case?

A: An enum declaration doesn't use any runtime memory. It's just a convenient way to use symbolic names for constants.


text:
Q: List WordPress certain category's post url Is there a way to list all the posts urls from a certain category in WordPress, without a plugin?
I am not familiar with PHP, but I was thinking if some how, I could use a page template where a method would call all this category posts url(ex:lets call the category "blog").

A: Review WP_Query and the WordPress loop. Something like this ought to work if I'm understanding your inquiry correctly (wrap in php tags):
$the_query = new WP_Query( array( 'category_name' => 'blog' ) );

if ( $the_query->have_posts() ) {
 echo '
';
 while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo '
' . get_permalink() . '
';
 }
 echo '
';
 /* Restore original Post Data */
 wp_reset_postdata();
} else {
 // no posts found
}

A: You can use get_posts (https://codex.wordpress.org/Template_Tags/get_posts).
Consider this a slimmed down version of WP_Query which will return an array of the posts you want.
$categoryPosts = get_posts(array(
    // Note: The category parameter needs to be the ID of the category, and not the category name.
    'category' => 1,
    // Note: The category_name parameter needs to be a string, in this case, the category name.
    'category_name' => 'Category Name',
));

Then you can loop through the posts:
foreach($categoryPosts as $categoryPost) {
    // Your logic
}

$categoryPost will contain the following by default (more fields if you have custom fields), these fields will obviously be populated, but this is what you'll have available in an array:
WP_Post Object
(
    [ID] =>
    [post_author] =>
    [post_date] =>
    [post_date_gmt] =>
    [post_content] =>
    [post_title] =>
    [post_excerpt] =>
    [post_status] =>
    [comment_status] =>
    [ping_status] =>
    [post_password] =>
    [post_name] =>
    [to_ping] =>
    [pinged] =>
    [post_modified] =>
    [post_modified_gmt] =>
    [post_content_filtered] =>
    [post_parent] =>
    [guid] =>
    [menu_order] =>
    [post_type] =>
    [post_mime_type] =>
    [comment_count] =>
    [filter] =>
)


text:
Q: Powershell script to run a .reg file on remote computers I have tried creating a batch file using PsExec to update registry settings on remote computers without success so I am now trying to use Powershell. I have compiled the following script by using Google and playing about with scripts available on different forums.
 $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
 $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

 $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

 if ($myWindowsPrincipal.IsInRole($adminRole))
    {

    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
    $Host.UI.RawUI.BackgroundColor = "Darkred"
    clear-host
    }
 else
    {

    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

    $newProcess.Arguments = $myInvocation.MyCommand.Definition;

    $newProcess.Verb = "runas";

    [System.Diagnostics.Process]::Start($newProcess);

    exit
    }

winrm quickconfig

    $servers = Get-Content c:\temp\servers.txt

    $HostedRegFile = "temp\OfficeDocumentfix.reg"

    foreach ($server in $servers)

    {

    $newfile = "\\$servers\c`$\Downloads\RegistryFiles\"

    New-Item -ErrorAction SilentlyContinue -ItemType directory -Path \\$servers\C$\Downloads\RegistryFiles\

    Copy-Item $HostedRegFile -Destination $newfile

    Invoke-Command -ComputerName $server -ScriptBlock {

    Start-Process -filepath "C:\windows\regedit.exe" -argumentlist "/s C:\Downloads\RegistryFiles\test.reg"

 Write-Host -NoNewLine "Press any key to continue..."
 $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

$returncode = $?+":"+$lastexitcode;

$codearr = $returncode.split(":");

write-host $codearr[0];

write-host $codearr[1];

#echo Registry_updated_successfully

#:Failed
#echo Registry_update_failed

 Write-Host -NoNewLine "Press any key to continue..."
 $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
 }

 }

Now for my Problem, running the script, I get the following error

WinRM already is set up to receive requests on this machine.
WinRM already is set up for remote management on this machine.
Copy-item : Cannot find path 'C:\OfficeDocumentfix.reg' because it does not exist.

But the path is correct, is there something blatantly obviously wrong with the script I am using, this is my 2nd push into Powershell so any help would be appreciated

A:
WinRM already is set up to receive requests on this machine.
WinRM already is set up for remote management on this machine.

delete this winrm quickconfig out of your script. it wants to configure your WinRM service but it's already set up, so there's no need for this. WinRM lets you access Remote Computer via its Service, it's needed for e.g invoke-command {}.

Copy-item : Cannot find path 'C:\OfficeDocumentfix.reg' because it
  does not exist.

the reason for this is, that your $newfile variable uses $servers instead of $server as it should (because it's inside the foreach() block) so $servers is $null. that's the cause of the error.
if the Registry File you're using writes to HKCU:, you don't need to elevate the script, if it's writing to HKLM: you have to. Only Admins can write to HKLM. The elevation is the whole part from the beginning up to winrm quickconfig.
this should give you the following end-product (I left the elevation in there):
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

if ($myWindowsPrincipal.IsInRole($adminRole))
{
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
    $Host.UI.RawUI.BackgroundColor = "Darkred"
    clear-host
}
else
{
    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
    $newProcess.Arguments = $myInvocation.MyCommand.Definition;
    $newProcess.Verb = "runas";
    [System.Diagnostics.Process]::Start($newProcess);
    exit
}

$servers = Get-Content c:\temp\servers.txt

$HostedRegFile = "C:\temp\CyclopsOfficeDocumentfix.reg"
foreach ($server in $servers)
{
    $newfile = "\\$server\c`$\Downloads\RegistryFiles\"
    New-Item -ErrorAction SilentlyContinue -ItemType directory -Path \\$server\C$\Downloads\RegistryFiles\
    Copy-Item $HostedRegFile -Destination $newfile
    Invoke-Command -ComputerName $server -ScriptBlock {
        Start-Process -filepath "C:\windows\regedit.exe" -argumentlist "/s C:\Downloads\RegistryFiles\test.reg"
        Write-Host -NoNewLine "Press any key to continue..."
    }
}

please do also take a look at this line:
Start-Process -filepath "C:\windows\regedit.exe" -argumentlist "/s C:\Downloads\RegistryFiles\test.reg"

it's not dynamic yet. it will always read in test.reg instead of your desired reg-file.
instead of start-process you could also simply use regedit /s $regfile /f PowerShell can execute batch-like commands (but that's detail. if it works like this, leave it like it is).

A: I prefer not to mess with double hop and other authentication issues and pass contents of registry file as paramater to Invoke-Command. This provides certain advantages over making remote server trying to reach out to some file share somewhere trying to pull file and can be run even from computers accross domains.
$regFile = @"
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters]
"MaxUserPort"=dword:00005000
"TcpTimedWaitDelay"=dword:0000001e
"@

Invoke-Command -ComputerName comp -ScriptBlock {param($regFile) $regFile | out-file $env:temp\a.reg;
    reg.exe import $env:temp\a.reg } -ArgumentList $regFile


text:
Q: Symbolic Computations in boost libraries Does Boost library support symbolic computations and integration  ?
If yes, can any one gives an example.
In fact, i had tried many symbolic libraries, like Vienna Math and symbolicc++
but i am facing problems in configuration, so returned to Boost.

A: No. You can find a full list of boost math libraries here: http://www.boost.org/doc/libs/?view=category_Math
If you're having trouble using C++, why not try SymPy (Which you can try online through http://www.sagemath.org/). Or mathematica/maple/matlab if you have access t them.


text:
Q: How to import CSV file in SQL server 2008? I am trying to import a CSV file in SQL Server 2008. BULK INSERT is a way to go but it is applicable for CSV from SQL Server 2014 onwards.
What would be an alternative way to achieve this goal?
Any thoughts/ideas much appreciated.

A: Following link
https://support.discountasp.net/kb/a1179/how-to-import-a-csv-file-into-a-database-using-sql-server-management-studio.aspx

If you problem then next link follow
I hope solve your problem
https://host4asp.net/import-csv-file-using-sql-server-management-studio/

A: SQL Server has always supported bulk inserting from CSV files, you just have to specify field/row terminators.
file.csv contains:
foo,bar,1
blat,splunge,2

Then we do this:
CREATE TABLE #foo(a varchar(32), b varchar(32), c int);

BULK INSERT #foo FROM 'c:\temp\file.csv'
WITH (ROWTERMINATOR = '\n', FIELDTERMINATOR = ',');

SELECT * FROM #foo;

Results:
a        b        c
-------- -------- ----
foo      bar      1
blat     splunge  2


text:
Q: Not able to run Azure functions in VS code in mac? I am trying to follow this tutorial to run azure function app using C# using vscode.
But when I click the run button, it shows "You must have the Azure Functions Core Tools installed to debug your local functions." But I have actually installed it in my mac. When I click the install button, it shows errors like follows:
/bin/bash: func: command not foundThe terminal process "/bin/bash '-c', 'func host start'" failed to launch (exit code: 127).

And on the right bottom there is a small window showing:

Error exists after running preLaunchTask "host start". View task output for more information.
But when I use the command func host start in my local terminal, it can run smoothly.

A: We have tried the same but on Windows(OS) , Below are the workaround to resolve the above issue.

*

*Created a new Azure function with HTTP Trigger using .net 6

*Before debugging we have started the Azure storage Emulator/Azurite on local.

Or Alternatively, We can add "AzureWebJobsStorage": "UseDevelopmentStorage=true", in our localsettings.json and tried to debug by using .net Function.

OUTPUT DETAILS FOR REFERENCE:-

NOTE:- To run function locally based on the given MICROSOFT DOCUMENTATION:-

Click on  Ctrl -  (macOS) the HttpExample function and choose Execute
Function Now

Or, we can add a breakpoint over our function.cs file and type start debug as shown below :-

For more information regarding VS CODE on macos configuration Please refer this SO THREAD discussions .


text:
Q: IOS login required for certain tabs with storyboard My question is based on the following question, but my case is reversed.
Example for login screen modally based on storyboard
I would like to have a few tabs private for users only so required login, my storyboard is below:

Below is my code in custom tabBarController
@interface PNTabBarController ()

@end

@implementation PNTabBarController

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    NSUInteger indexOfTab = [tabBar.items indexOfObject:item];
    NSLog(@"%lu", (unsigned long)indexOfTab);
    if (indexOfTab == 2 || indexOfTab == 3) {
        PFUser *currentUser = [PFUser currentUser];
        NSLog(@"%@", currentUser.username);
        if(currentUser == nil){
            PNLoginViewController *obj = [[PNLoginViewController alloc]init];
            [self presentViewController:obj animated:YES completion:NULL];
        }
        else{
            NSLog(@"%@", currentUser.username);
        }
    }
}

But what happens is a dark screen when I click the 2 or 3 tab. What should be the correct way to achieve this?


text:
Q: Quarternionic Analysis What is/are the current understanding/opinions about Quarternionic Analysis as a generalization of Complex Analysis with respect to a "Quarternionic Residue Calculus" (if such a thing exists)? i.e. does a "quarternionic residue calculus" exist, and if not what are the opinions that this might be useful, if indeed possible?
For example, residue calculus is great if we can find a "nice" contour to work with, but sometimes this does not seem possible. I'm just wondering if a Quarternionic Analysis would allow for 4-dimensional "contours" (i.e. surfaces) in the "Quarternion-plane" (i.e. 4-dimensional space) that might allow the evaluation of definite integrals which seem otherwise unsolvable by the residue calculus of complex analysis.

A: A while back, when asking myself the same question, I found this website to be very informative. The wiki article was also useful, if only for its bibilography.
You might also have better luck if you search for "hypercomplex analysis." In googlebooks I found Generalized Analytic Automorphic Forms in Hypercomplex Spaces By Rolf S. Krausshar. On page 21 it states Theorem 1.23 (Residue theorem) for certain finite dimensional differentiable manifolds, and on page 22 it says:
Also the residue theorem can be generalized to the more general context dealing with manifolds of singularities. See [61,63] for the quaternionic case...
I would give you the two references but I can't see the bibliography. If I were in your position I'd definitely find this book :)
I did not get very deep into the subject: I just satisfied my curiosity about whether or not people have been thinking about analyticity, differentiation, integration and all other things from real and complex analysis in the context of the quaternions, and it appears that they have.


text:
Q: RSelenium: hangs in navigate to direct pdf download Using RSelenium via Docker Toolbox for Windows with selenium/standalone-firefox-debug container - all working fine:
docker run -d -v //c/test/://home/seluser/Downloads -p 4445:4444 -p 5901:5900 selenium/standalone-firefox-debug
Have setup firefox profile to download pdf directly:
fprof <- makeFirefoxProfile(list(browser.startup.homepage = "about:blank"
                                 , startup.homepage_override_url = "about:blank"
                                 , startup.homepage_welcome_url = "about:blank"
                                 , startup.homepage_welcome_url.additional = "about:blank"
                                 , browser.download.dir = "/home/seluser/Downloads"
                                 , browser.download.folderList = 2L
                                 , browser.download.manager.showWhenStarting = FALSE
                                 , browser.download.manager.focusWhenStarting = FALSE
                                 , browser.download.manager.closeWhenDone = TRUE
                                 , browser.helperApps.neverAsk.saveToDisk = "application/pdf, application/octet-stream"
                                 , pdfjs.disabled = TRUE
                                 , plugin.scan.plid.all = FALSE
                                 , plugin.scan.Acrobat = 99L))

Using the following code, when I navigate directly to the pdf, it downloads to the specified directory fine but then it hangs at that point, not allowing any proceeding code to execute.
library(RSelenium)

remDr <- remoteDriver(remoteServerAddr = "*docker-ip*", port = 4445L, extraCapabilities = fprof)
remDr$open()
remDr$navigate("http://www.equibase.com/premium/eqbPDFChartPlus.cfm?RACE=A&BorP=P&TID=BEL&CTRY=USA&DT=09/12/2015&DAY=D&STYLE=EQB")

I have to manually stop the R code and the error that displays is:
Error in checkError(res) :
Undefined error in httr call. httr output: Operation was aborted by an application callback

If I VNC into the container and look at what is displayed in the browser, the file has downloaded but there is nothing in the address bar.
screenshot
Any ideas? I am assuming that it is something to do with the httr/rselenium packages not receiving some sort of 'loaded' signal from the browser, but this extends beyond my troubleshooting ability. This method had worked previously using the .jar file selenium-standalone-server and RSelenium.
sessionInfo() & remDr$open() output below:
> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RSelenium_1.7.1

loaded via a namespace (and not attached):
 [1] httr_1.2.1     R6_2.2.0       assertthat_0.1 tools_3.3.2    wdman_0.2.2    binman_0.1.0
 [7] curl_2.3       Rcpp_0.12.9    jsonlite_1.2   caTools_1.17.1 openssl_0.9.6  bitops_1.0-6
[13] semver_0.2.0   XML_3.98-1.5

> remDr$open()
[1] "Connecting to remote server"
$rotatable
[1] FALSE

$raisesAccessibilityExceptions
[1] FALSE

$firefoxOptions
$firefoxOptions$args
list()

$firefoxOptions$profile
[1] "UEsDBBQACAgIAEwPW0oAAAAAAAAAAAAAAAAIAAAAcHJlZnMuanOlkU9LAzEQxe+C36HsSaFmwVv1tNBjbwoey2wy242dZsJM0v36JqJYimWV3vLn/R4z72VF2UbB4a7phadyM5pAUo5m5ANG2GGzXDTQc05PPUHYN/fPtzf5BzuXb/mIIt7hNgv9l52QbDlfiRpwzifPAeZcvnd2PAVicMZ5qUhbbVtFqtp2/fWrs/jA5FA2XlNxeZxTHyCUyUviI09vI4aXupMPu8IOQIp/5Qe2Wa8xsMSK1WDNofadJF9iR6SI0sWoJmBputO9UTjiK6+97j/jjpG8hZp/G92wXJw+sE2YHjQJwuE8zSJ+19KAQk/ofh8jUt75YNRCMMXVGSC6sO2ptLPCPdRSVqsq+wBQSwcII+hBcQsBAAD3AgAAUEsDBBQACAgIAEwPW0oAAAAAAAAAAAAAAAAHAAAAdXNlci5qc51WTW/bMAy971cMOW3AKqTretlOXdcBA4Z1aFDsKMgSbauRJU0fcfPvR/mjSRNHbndKbJMS+fj4yOjBUeugfLconGnxiXhWQvdf6oo0TLXMAQHNCgVi8eFtyZSH91/exJ2nYAFtrHEhudTAVKj7Z4JGG8ln/DWE1rg1qUOwxNbS19uz9Nky788U6CrU6Pjx8vK52xiwAybwR0AAHkB8l86HK4yFK0C34OJhuKbBvB4pr51pgHrupA3URU2DbJLLxXL6osAKTxAOfauvlfEwnc1oLUyrlWEC79KsSsDWpv1Tg14hWgmpaXeLQdng02W0MYKpGexhE4xRnoBzxnGjvVH7cB+n72WljUbUGmgKcKvu0edz8eC9RKtgkAsOfETcSgyUcsd8nfdVUq+JsaApPAZwmqlUzFczqExlvYt6+rIWCuHkBp8Z54DljBoz90gHysEFP4nEU6Wkt4ptQdycL1e/DDInlfbTtDG+Erf6j9RYX3++JBIvMvd3P9FjwQoTw+dCMb1... <truncated>

$appBuildId
[1] "20170125094131"

$version
[1] ""

$platform
[1] "LINUX"

$proxy
named list()

$command_id
[1] 1

$nativeEvents
[1] TRUE

$specificationLevel
[1] 0

$acceptSslCerts
[1] FALSE

$processId
[1] 3012

$webdriver.remote.sessionid
[1] "6263b5ab-9375-425e-aa00-8fc632dc492e"

$browserVersion
[1] "51.0.1"

$platformVersion
[1] "4.4.47-boot2docker"

$XULappId
[1] "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"

$browserName
[1] "firefox"

$takesScreenshot
[1] TRUE

$javascriptEnabled
[1] TRUE

$takesElementScreenshot
[1] TRUE

$platformName
[1] "linux"

$cssSelectorsEnabled
[1] TRUE

$firefox_profile
[1] "UEsDBBQAAgAIAJRZW0oj6EFxCwEAAPcCAAAIAAAAcHJlZnMuanOlkU9LAzEQxe+C36HsSaFmwVv1tNBjbwoey2wy242dZsJM0v36JqJYimWV3vLn/R4z72VF2UbB4a7phadyM5pAUo5m5ANG2GGzXDTQc05PPUHYN/fPtzf5BzuXb/mIIt7hNgv9l52QbDlfiRpwzifPAeZcvnd2PAVicMZ5qUhbbVtFqtp2/fWrs/jA5FA2XlNxeZxTHyCUyUviI09vI4aXupMPu8IOQIp/5Qe2Wa8xsMSK1WDNofadJF9iR6SI0sWoJmBputO9UTjiK6+97j/jjpG8hZp/G92wXJw+sE2YHjQJwuE8zSJ+19KAQk/ofh8jUt75YNRCMMXVGSC6sO2ptLPCPdRSVqsq+wBQSwECHgAUAAIACACUWVtKI+hBcQsBAAD3AgAACAAAAAAAAAABACAAAAAAAAAAcHJlZnMuanNQSwUGAAAAAAEAAQA2AAAAMQEAAAAA"

$id
[1] "6263b5ab-9375-425e-aa00-8fc632dc492e"

A: I had the same problems using the most recent version of firefox (51.0.1).
This was on a windows machine and the issue seemed to be the pdfjs.disabled flag. The issue was not present in older versions of firefox. The Docker image tagged 2.53.1 runs firefox 47 for example. If possible run an older version using (on a linux box):
docker run -d -p 4445:4444 -p 5901:5900 -v /home/john/test:/home/seluser/Downloads selenium/standalone-firefox-debug:2.53.1

Now running your code we see:
fprof <- makeFirefoxProfile(list(browser.startup.homepage = "about:blank"
                                 , startup.homepage_override_url = "about:blank"
                                 , startup.homepage_welcome_url = "about:blank"
                                 , startup.homepage_welcome_url.additional = "about:blank"
                                 , browser.download.dir = "/home/seluser/Downloads"
                                 , browser.download.folderList = 2L
                                 , browser.download.manager.showWhenStarting = FALSE
                                 , browser.download.manager.focusWhenStarting = FALSE
                                 , browser.download.manager.closeWhenDone = TRUE
                                 , browser.helperApps.neverAsk.saveToDisk = "application/pdf, application/octet-stream"
                                 , pdfjs.disabled = TRUE
                                 , plugin.scan.plid.all = FALSE
                                 , plugin.scan.Acrobat = 99L))
library(RSelenium)

remDr <- remoteDriver(port = 4445L, extraCapabilities = fprof)
remDr$open()
remDr$navigate("http://www.equibase.com/premium/eqbPDFChartPlus.cfm?RACE=A&BorP=P&TID=BEL&CTRY=USA&DT=09/12/2015&DAY=D&STYLE=EQB")

> list.files("/home/john/test/")
[1] "eqbPDFChartPlus.cfm"

The pdf would need to be renamed (its being named as a colfusion .cfm file)
As to what is happening with more recent versions of firefox you would need to refer that to most likely the geckodriver project. Users with clients other than RSelenium have also had recent issues Can't download PDF with selenium webdriver + firefox


text:
Q: Import driftyco's premuim ionicons into ionic2 application GitHub Link: github.com
I have found Driftyco's ionicons repository, And I would like to use it.
I have download it and import the files ionicons.css and folder fonts into my folder /src/assets, And insert the css file inside /src/index.html.
I have also change the fonts dir in the css file to the correct location.
When I write this in my code <i class="icon ion-home"></i> nothing happen.
It's seem that's not recognized it.
Please help :)


text:
Q: How can I put a HTML code in Outlook 2010? How can I put a HTML code in outlook 2010?
The code is:

Hello

How can I put that in the message using Outlook 2010?

A: Might need to find a different email client/editor if you want to send HTML tags in your email:  http://office.microsoft.com/en-us/outlook-help/i-can-t-use-html-tags-in-html-e-mail-messages-HA010199144.aspx

Microsoft Office Outlook 2007 uses an
  e-mail message editor based on
  Microsoft Office Word 2007. Office
  Outlook 2007 offers a WYSIWYG (what
  you see is what you get) editing
  environment. The message that you
  compose is converted to HTML format
  for sending.
Office Outlook 2007 is not designed
  for you to directly enter or view HTML
  tags when composing an e-mail message.

A: You need to install HTML Code Editor for Outlook, which is Outlook add-in to allow you edit native HTML directly on Outlook.
http://outlookhtmleditor.codeplex.com/
You can download a installer on download tab. It'll allow you to import HTML file or edit HTML source code of your e-mail.


text:
Q: Showing a dialogue after file has been uploaded (Ajax/PHP/Javascript) So I am using Javascript with AJAX to send form data to a PHP file. Once it's done uploading the file to the server, I want a dialogue box to appear to say it's successful, then it reloads. I have that dialogue box done, but it will appear even if there's an error. I though creating a flag would solve this, but it doesn't. I need to wait for the progress to be 100% complete, so I put the code in the progress function. Here's my code:
function uploadImage(){
var done = false;
     var xr = new XMLHttpRequest();
        xr.upload.addEventListener("progress", progressHandler, false);
        xr.addEventListener("error", errorHandler, false);
        xr.addEventListener("abort", abortHandler, false);
        xr.open("POST", "php/uploadImage.php", true);

        xr.onreadystatechange = function(){
            if(xr.readyState == 4 && xr.status == 200){
                var response = xr.responseText;
                if(response=="success"){
                    done=true;
                }else{
                    _("errorMessage").innerHTML = response;
                }
            }
        }

        xr.send(formdata);

        function progressHandler(event){
            var percent = (event.loaded / event.total) * 100;
            _("imageUploadBar").style.width = Math.round(percent) + "%";

            if((percent == 100) && (done)){
                completeHandler();
            }
        }

        function completeHandler(){
            bootbox.dialog({
                message: "Image upload is completed.",
                title: "Upload Success",
                buttons: {
                    success: {
                        label: "Continue",
                        className: "btn btn-success",
                        callback: function() {
                            location.reload();
                        }
                    }

                }
            });
        }
}

So you can see that if the upload file return success, set done to be true, and if percent is 100, then fire, but this will not fire the completeHandler() function. Any ideas why or how to get around this?

A: I believe this will generally fire from onreadystatechange, but adding a 2nd variable should take care of your issue.
var done = false;
var uploaded = false;
var xr = new XMLHttpRequest();
xr.upload.addEventListener("progress", progressHandler, false);
xr.addEventListener("error", errorHandler, false);
xr.addEventListener("abort", abortHandler, false);
xr.open("POST", "php/uploadImage.php", true);

xr.onreadystatechange = function(){
    if(xr.readyState == 4 && xr.status == 200){
        var response = xr.responseText;
        if(response=="success"){
            done=true;
            if(uploaded && done){
                completeHandler();
            }
        }else{
            _("errorMessage").innerHTML = response;
        }
    }
}

xr.send(formdata);

function progressHandler(event){
    var percent = (event.loaded / event.total) * 100;
    _("imageUploadBar").style.width = Math.round(percent) + "%";

    if(percent == 100) uploaded = true;

    if(uploaded && done){
        completeHandler();
    }
}

function completeHandler(){
    bootbox.dialog({
        message: "Image upload is completed.",
        title: "Upload Success",
        buttons: {
            success: {
                label: "Continue",
                className: "btn btn-success",
                callback: function() {
                    location.reload();
                }
            }

        }
    });
}