text:
Q: how to create a form generator from json object using js
how to make text at the same line of another With JSON object for example: TEXT:Input text, and a submit button that if i write a value inside the input text it automatically write the values for the other input text how can i do it that was really hard for me to figure it out and i did a research about it but i didnt find anything so can you help.

const objs = [{ "Object1": { "ID": 1, "type": "input", "color": "red", "Text": "DARKDRAGON", "width": "150px", "height": "40px", "top": "15px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } }, "Object2": { "ID": 2, "type": "textarea", "color": "cyan", "Text": "SPEEDYTIGER", "width": "150px", "height": "40px", "top": "70px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } }, "Object3": { "ID": 3, "type": "input", "color": "blue", "Text": "AMyesteriousAdults", "width": "200px", "height": "40px", "top": "130px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } }, "Object4": { "ID": 4, "type": "button", "color": "darkorange", "Text": "AMyesteriousDarkSpeed", "width": "200px", "height": "40px", "top": "190px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } } }]

Object.keys(objs[0]).forEach(key => {

  const formItem = objs[0][key];
  const elmn = document.createElement(formItem.type);
  if (formItem.type === "button") elmn.innerHTML = formItem.Text;
  else elmn.value = formItem.Text;
  Object.assign(elmn.style, {
    position: 'absolute',
    color: formItem.color,
    width: formItem.width,
    height: formItem.height,
    top: formItem.top,
    left: formItem.left,
    fontFamily: formItem.Font.fontName,
    fontSize: formItem.Font.font,
  });

  document.getElementById('ColorArea').appendChild(elmn);
});

how to make text at the same line of another With JSON object for example: TEXT:Input text, and a submit button that if i write a value inside the input text it automatically write the values for the other input text how can i do it that was really hard for me to figure it out and i did a research about it but i didnt find anything so can you help.

A: Like this?
https://jsfiddle.net/mplungjan/otbgvzp8/

const objs = [{ "Object1": { "ID": 1, "type": "input", "color": "red", "Text": "DARKDRAGON", "width": "150px", "height": "40px", "top": "15px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } }, "Object2": { "ID": 2, "type": "textarea", "color": "cyan", "Text": "SPEEDYTIGER", "width": "150px", "height": "40px", "top": "70px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } }, "Object3": { "ID": 3, "type": "input", "color": "blue", "Text": "AMyesteriousAdults", "width": "200px", "height": "40px", "top": "130px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } }, "Object4": { "ID": 4, "type": "button", "color": "darkorange", "Text": "AMyesteriousDarkSpeed", "width": "200px", "height": "40px", "top": "190px", "left": "5px", "Font": { "fontName": "tahoma", "font": "17px" } } }];

const breakFlex = document.createElement("p");
breakFlex.style.flexBasis = "100%";
breakFlex.style.height= 0;

Object.keys(objs[0]).forEach(key => {

  const formItem = objs[0][key];
  const elmn = document.createElement(formItem.type);
  if (formItem.type === "button")
    elmn.innerHTML = formItem.Text;
  else
    elmn.placeholder = formItem.Text;
  Object.assign(elmn.style, {
    color: formItem.color,
    width: formItem.width,
    height: formItem.height,
    top: formItem.top,
    left: formItem.left,
    fontFamily: formItem.Font.fontName,
    fontSize: formItem.Font.font,
    flex: '1 0 45%',
  });
  if (formItem.type !== "button") {
    const label = document.createElement("label");
    label.innerHTML = formItem.Text + "
";
    label.style.fontSize="smaller";
    label.appendChild(elmn);
    document.getElementById('ColorArea').appendChild(label);
  } else document.getElementById('ColorArea').appendChild(elmn);
  document.getElementById('ColorArea').appendChild(breakFlex.cloneNode());
});

A: Ok here is an example, I have modified your JSON object so you can add more styles and types... i don't know if this is what you want...

var inputs = [
  {
    "ID": "inp1",
    "Element": "input",
    "Type": "text",
    "Text": "your name",
    "Styles": {
      "font-family": "tahoma",
      "font-size": "17px"
    }
  },
  {
    "ID": "inp5",
    "Element": "input",
    "Type": "number",
    "Text": "your age",
    "Styles": {
      "font-family": "tahoma",
      "font-size": "17px",
      "color": "yellow",
      "background": "blue"
    }
  },
  {
    "ID": "inp16",
    "Element": "input",
    "Type": "password",
    "Text": "put your password",
    "Styles": {
      "font-family": "tahoma",
      "font-size": "17px",
      "color": "blue",
      "background": "yellow"
    }
  }
];

function createForm(someInputs) {
  var newForm = document.createElement("form");
  someInputs.forEach(function(input) {
    var styles = "";
    Object.keys(input.Styles).forEach(function(key) {
      styles += `${key}: ${input.Styles[key]};`;
    });
    newForm.innerHTML += `<${input.Element} type="${input.Type}" id="${input.Id}" placeholder="${input.Text}" style="${styles}"><br>`;
  });
  document.body.appendChild(newForm);
}

createForm(inputs);


text:
Q: Unable to scroll in appium IOS Unable to scroll in appium IOS till bottom of the page with below code:
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap scrollObject = new HashMap();
scrollObject.put("direction", "up");
scrollObject.put("xpath", "//XCUIElementTypeStaticText[@name=\"NAME\"]");
js.executeScript("mobile: swipe", scrollObject);

A: I can scroll with the following code:
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("direction", "down");
js.executeScript("mobile: scroll", scrollObject);

Check if this works for you!
Edit/Update:
Use the following code to scroll till you find some element:
JavascriptExecutor js = (JavascriptExecutor) driver;
String elementID = driver.findElementByAccessibilityId("Steppers").getId();
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("element", elementID);
scrollObject.put("toVisible", "not an empty string");
js.executeScript("mobile:scroll", scrollObject);

Or you can Swipe-up using the following code:
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("direction", "up");
js.executeScript("mobile:swipe", scrollObject);

A: Able to scroll to down using the below code
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("direction", "down");
js.executeScript("mobile: scroll", scrollObject);

Scroll to up using
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("direction", "up");
js.executeScript("mobile: scroll", scrollObject);

Scrolldown till element found

    public static boolean isElementPresent(By locator, int timeout) {
        try {
            waitForElementToLoad(locator, timeout, driver);
            logger.debug("Element found in page " + pageName);
            return true;
        } catch (Exception e) {
            logger.warn("Could not find element: in page " + pageName);
            return false;

        }
    }

    public static WebElement waitForWebElementToLoad(By byLocator,int maxtimeWaitInSec, WebDriver driver) {
        if (driver == null) {
            return null;
        }
        FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(maxtimeWaitInSec, TimeUnit.SECONDS)
                .pollingEvery(500, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class)
                .ignoring(StaleElementReferenceException.class);
        //return wait.until(ExpectedConditions.presenceOfElementLocated(byLocator));
        return wait.until(ExpectedConditions.visibilityOfElementLocated(byLocator));
    }

    public void scrollDownUntilElementFound(By element) {
        int scrollLimit = 0;
        while ((!isElementPresent(element, 20)) && scrollLimit < 25) {
            scrollLimit++;
            swipe(driver.`enter code here`manage().window().getSize().getWidth() / 2, driver.manage().window().getSize().getHeight() / 2,
                    0, -(driver.manage().window().getSize().getHeight()));
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve Data data once time Firebase instead of onSnapshot I'm trying to retrieve data once time instead to using onSnapshot.
    import { onSnapshot, collection  } from 'firebase/firestore';

function App() {
  const [books , setbooks] = useState([]);
  console.log(books);

     useEffect(() => {
       onSnapshot(collection(db,'books'),(snapshot)=>{
         setbooks(snapshot.docs.map((doc) =>({...doc.data(), id: doc.id})));
       })

      },[]);

A: The equivalent while getting the data once would be:
useEffect(() => {
  getDocs(collection(db,'books')).then((snapshot)=>{
    setbooks(snapshot.docs.map((doc) =>({...doc.data(), id: doc.id})));
  })
},[]);


text:
Q: How to add test files to a linting script I currently have this command in my package.json:
  "lint-staged": {
    "{src}/**/*.{js,jsx,ts,tsx}": [
      "prettier-eslint --write"
    ]
  }

How can I add testing files to this? Currently SampleComponent.test.tsx does not get this command invoked on it, but SampleComponent.tsx does. Thanks!


text:
Q: Can Azure function communicate with Azure Application Gateway? I have two regions with virtual machines deployed.

*

*West Europe

*Cental US

Data Flow

*

*User types www.somethingdotcom in browser.

*Request goes to Azure front door

*Azure front door sends a request to a nearby location (Azure function-deployed in both regions)

*Azure function talks to master data from db or cache to GET load balancer address (private IP).

*Now question is, can azure function redirect request to target application gateway?

I want to redirect the requests to right VM based on mapping specified in  Cache
Is this architecture help? I suspect on communication between Azure function and Application Gateway.

A: The diagram below does not show any network related detail around the VMs e.g. the vNet/subnet configuration, etc.

The details of an App Gateway are described here.
List of policies supported by APIM are here.
Also, unless you have a specific reason to stay in a VM, and if you are just deploying an API or a website, moving to an App Service will reduce the amount of work you would need to do to expose the HTTP endpoints.


text:
Q: ArcGIS Web AppBuilder browser privacy error I am trying to launch ArcGIS Web App Builder for the very first time in Windows 10.

*

*Download and unzip the latest 2.2.1 package.

*Run  startup.bat.

*Get the Device name under This PC > Properties > Device name.

*Paste https://[yourmachinename]:3344/webappbuilder/ in the browser (Chrome) and press enter. This returns an error:

Privacy error Your connection is not private
How can I fix this?

A: Use localhost instead of yourmachinename and tell chrome to ignore localhost certificate issues.
From stackoverflow.com:

In Chrome, put in chrome://flags/#allow-insecure-localhost in the
address bar.
Enable the option that says "Allow invalid certificates for resources
loaded from localhost".
Restart Chrome, and it should allow the site.

As to whether you should be concerned, from security.stackexchange.com:

It's most likely fine.
There are a few situations in which you want to
communicate with localhost using HTTPS - such as running a local
webserver for web development purposes or some other service that
offers a web interface.
The way to do it "properly" is to generate a self-signed certificate,
set up your web server to use that certificate, and then manually
import that certificate as a trusted certificate. This is a tedious
process, and in order to remove this friction, browsers give you the
option of pretending like https://localhost is sending some trusted
certificate, even though it's not.
So is this secure? That depends on your threat model. For day-to-day
browsing activities, you'll likely be fine. It's difficult for an
attacker even in your local network to impersonate localhost, since
it's written directly in your hosts file, which on most setups has
higher priority than DNS - which means even with a compromised DNS
server, connections to localhost still would not be redirected to the
attacker.
So why is this not the default if it's most likely secure? Because
it's not the "expected" behavior of a browser. The expected behavior
is that upon connecting to a host using HTTPS, the certificate is
validated and the connection is refused if the certificate is invalid.
You as end-user have to make a conscious decision to change this
behavior and allow this exception.
So when would this be insecure? When would it actually pose a threat?
To be honest, I struggle to think of an example that isn't completely
contrived. Strange hostname resolution configurations in which
localhost would be resolved via DNS and spoofed to be some host other
than 127.0.0.1 would come to mind, but that is a very unlikely
scenario, and one in which the user has to go out of their way to
configure their system to be vulnerable. However, I don't want to say
"it is perfectly fine in every possible setup", since there is always
a chance I am missing something.


text:
Q: S3 Cross account setup I have two accounts in AWS like Account A and Account B. In Account A whenever I upload objects in S3 bucket it should load automatically into Account B, S3 bucket. Can anyone suggest me how to write Lambda function using python for this and which IAM role we can use for this.?

A: It appears that your requirement is:

*

*Create an AWS Lambda function in Account-A

*The Lambda function should be able to create Amazon S3 objects in a bucket (Bucket-B) owned by Account-B
The simplest setup for this would be:

*

*Create an IAM Role for the Lambda function

*The role should have permission to PutObject in Bucket-B (or even any bucket), such as:

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "s3:PutObject"
         ],
         "Resource":"arn:aws:s3:::bucket-b/*"
      }
   ]
}

*

*On Bucket-B (in Account-B), add a Bucket Policy that permits the above IAM Role to write to the bucket:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"PublicRead",
      "Effect":"Allow",
      "Principal": "arn:aws:iam::<ACCOUNT-B>:role/lambda-role",
      "Action":["s3:PutObject"],
      "Resource":["arn:aws:s3:::bucket-b/*"]
    }
  ]
}

*

*When writing objects to Bucket-B, make sure the Lambda function sets ACL='bucket-owner-full-control' so that ownership is transferred to Account-B
The above method does not require assuming a role in Account-B, because the bucket policy on Bucket-B permits access via the IAM Role from Account-A.


text:
Q: Loading multiple .mat files containing the same variable name and changing the variable names simultaneously? So I have a directory that has many .mat files:
apples.mat, oranges.mat, bananas.mat, grapes.mat, apricots.mat, pears.mat, pineapple.mat
All of these .mat files has a variable name "calories" assigned a value. How do I load all of these .mat files simultaneously in MATLAB and change the variables for each one from calories to calories_(fruit name) so that I can have all the variable values in the workspace to play with?
For example, I want to load apples.mat and change its variable name from calories to calories_apple, then load oranges.mat and change is variable name from calories_orange, etc. without doing it all manually.
I know it's something along the lines of creating a string with the different fruit names, and the indexing along the string to load a file and change its variable from variable to variable_%s with the %s indicating the fruit content generated along the loop. It's a big mess for me, however, I don't think I'm structuring it right. Would anyone care to help me out?

A: I would load each .mat file in sequence and put each of the corresponding calories as a separate field being all combined into a single struct for you to access.  Given the directory of where these .mat files appear, do something like this:
%// Declare empty structure
s = struct()
folder = '...'; %// Place directory here

%// Get all MAT files in directory
f = dir(fullfile(folder, '*.mat'));

%// For each MAT file...
for idx = 1 : numel(f)

    %// Get absolute path to MAT file - i.e. folder/file.mat
    name = fullfile(folder, f(idx).name);

    %// Load this MAT file into the workspace and get the calories variable
    load(name, 'calories');

    %// Get the name of the fruit, are all of the characters except the last 4 (i.e. .mat)
    fruit_name = f(idx).name(1:end-4);

    %// Place corresponding calories of the fruit in the structure
    s.(['calories_' fruit_name]) = calories;
end

You can then access each of the calories like so using dot notation:
c = s.calories_apple;
d = s.calories_orange;

...
...

... and so on.

A: I am assuming that you do not mean to include the parenthesis in calories_(fruit name). I am also assuming there are no other .mat files in your current directory. This should do the trick:
theFiles = dir('*.mat');
for k = 1:length(theFiles)
    load(theFiles(k).name, 'calories');
    eval(['calories_' theFiles(k).name(1:length(theFiles(k).name)-4) ' =  calories;'])
    clear calories
end

Let me know if this helps or not.
EDIT
As, rayryeng points out. The use of eval is, apparently, a bad practice. So, if you are willing to change the way you are thinking about the problem, I suggest you use a structure. In which case, rayryeng's response would be an acceptable answer, even though it does not directly answers your original question.


text:
Q: Jmeter http requests get 400 response code in some random thread I wrote an test plan by using JMeter. it's structured like this:
Thread Group

*

*HTTP Cache Manager

*HTTP Cookie Manager

*CSV Data Set Config

*CSV Data Set Config

*Index Page

*

*a few Http requests

*Random Order Controller

*

*a few Http requests

*login page

*

*a few Http requests

*Random Order Controller

*a few Http requests

*Throughput Controller

*a few Http requests

*Simple Controller

*

*a few Http requests

*View Results Tree

I run 50 threads, however, some random http request fails with "Response code:400" in a thread, but it's successful for in other threads.
So I'm don't know how to investigate on this, as it works fine sometimes but it fails once or twice.
Can anyone give me some suggestions? I will really appreciate with your help.

A: you're possibly over hitting it with 50 threads (wild guess) Gateway Timeout perhaps .
Look at http://w3.org/Protocols/rfc2616/rfc2616-sec10.html
Note to implementors: some deployed proxies are known to return 400 or 500 when DNS lookups time out
if decreasing number of threads eliminates issue than it's not a test issue it's elsewhere.
Resolution details from the user1488025 :
We found the bug in mod_jk. Basically the default configuration of mod_jk doesn't work under high load, it will become slow, unresponsive, causes http error and half closed connections over time.


text:
Q: How to Fetch All Rows Of Gridview When Paging is Enabled?? How to Fetch All The rows of gridview when paging is enabled?.
it is allowing to fetch only current fetch rows not entire gridview rows.

A: We disable paging temporarily and will re-bind the grid so that now we have access to all records in the datasource not just current page records.
Once gridview is binded with all records, you can iterate through gridview rows.
Once we are done with our task, we re-enable paging and rebind the grid.
Here the way to tackle with your condition:
protected void Page_Load(object sender, EventArgs e)
{
    GridView2.AllowPaging = false;
    GridView2.DataBind();

    // You can select some checkboxex on gridview over here..

    GridView2.AllowPaging = true;
    GridView2.DataBind();
}

A: Use Following Code And make GridView paging disable
GridView1.AllowPaging = false;
            GridView1.DataBind();
on Page Load or Some Other event where You Want To show All Your Gridview Rows

A: Before the function of getting the Data from grid just write
yourGridName.AllowPaging=false;

and after getting the Data write
yourGridName.AllowPaging=true;

If your function is GetDataFromGrid() then you should go like this
protected void Page_Load(object sender, EventArgs e)
{
yourGridName.AllowPaging=false;
GetDataFromGrid()
yourGridName.AllowPaging=true;
}

A: You cant display all rows when paging is enabled.But u can make Allowpaging=false; in codebehind in pageload or in some event..
protected void Page_Load(object sender, EventArgs e)
{
Gridviewname.AllowPaging=false;
}

or
Protected Void some event(object sender,Eventargs e)
{
Gridviewname.AllowPaging=false;
}

A: Better way is to put a hidden field on the top of the page(outside of gridview) and on click of checkboxes, you should put the related id or some value in comma separated format in hidden field. On submit of the form, you can split the hidden field value string with comma as delimiter and there you go.

A: You can use the Commands Below which I'm using it in my projects. Its logic is so simple, you go through all pages and in every page you go through all rows. You can also get your current page before doing this and after looping all you can get back there ;)
//Get Current Page Index so You can get back here after commands
                int a = GridView1.PageIndex;
    //Loop through All Pages
                for (int i = 0; i < GridView1.PageCount; i++)
                {
    //Set Page Index
                    GridView1.SetPageIndex(i);
    //After Setting Page Index Loop through its Rows
                    foreach (GridViewRow row in GridView1.Rows)
                    {
                        //Do Your Commands Here
                    }
                }
    //Getting Back to the First State
                GridView1.SetPageIndex(a);

A: Use following code to get value of e.CommandArgument. I will solve your issue surely!
  protected void GridViewID_RowCommand(object sender, GridViewCommandEventArgs e)
  {
         if (e.CommandName == "GetDetail")
         {
            int index = Convert.ToInt32(e.CommandArgument) % GridViewID.PageSize; // !Important

            GridViewRow row = GridViewID.Rows[index];
         }
 }


text:
Q: [].__proto__ === Array.prototype // === [Symbol(Symbol.unscopables): Object]? Defining a utility function to inspect objects' prototype chains (in Chrome), I get this for arrays.

So it would appear that
[].__proto__ === Array.prototype  // === [Symbol(Symbol.unscopables): Object]

I understand the first equality. I have no idea what the third term is, though I have heard that ES6 will have Symbols.
Is this thing the same as Array.prototype? Why does it print that way?
Edit: chrome://version information:
Google Chrome   40.0.2214.111 (Official Build)
Revision    6f7d3278c39ba2de437c55ae7e380c6b3641e94e-refs/branch-heads/2214@{#480}
OS  Linux
Blink   537.36 (@189455)
JavaScript  V8 3.30.33.16

A: Comment on 2014-04-14
It seems Chrome's console.log print all Symbol-type-keys, here is an example:
var o = {};
o[Symbol.iterator] = function () {};
o[Symbol.unscopables] = {};
var s = Symbol('s');
o[s] = 3;
console.log(o);

which prints:

Object {Symbol(Symbol.unscopables): Object, Symbol(Symbol.iterator): function, Symbol(s): 3}

I don't why chrome behaves this way, is it for debugging or something else?
Fotunately it does not affect the toString() result so all code is safe.

It seems console.log would especially print the Symbol.unscopable key in console, we can have a plain object to perform like this:
var o = {};
o[Symbol.unscopables] = {};
console.log(o);

which outputs:

Object {Symbol(Symbol.unscopables): Object}

The Symbol.unscopables symbol is a special symbol defined in ES6 as @@unscopables which is used for excluding some properties when this object works in a with environment, the official explanation is:

An object valued property whose own property names are property names that are excluded from the with environment bindings of the associated object.

A simple example:
var o = {x: 1, y: 2};
o[Symbol.unscopables] = {
    y: true
};

console.log(o.x); // 1
console.log(o.y); // 2

with(o) {
    console.log(x); // 1
    console.log(y); // ReferenceError: y is not defined
}

You can use Array.prototype[Symbol.unscopables] to find all keys which cannot be used in with environment
However still, the output of a Array.prototype is not exactly the same as a plain object with Symbol.unscopables key, it outputs [Symbol(Symbol.unscopables): Object], which is a format more like an array
I can't exactly explain why, this may be related to the Symbol.toStringTag which controls how an object should be formatted to string, but Chrome currently does not export this symbol so it's hard to test


text:
Q: Why is my PDO query using LIKE & LIMIT not working? I am making a search box feature that has this query:
$query="SELECT * FROM article WHERE title LIKE ? OR description LIKE ?";

Then in a foreach loop, I make this array:
$params[]= "%".$keyword."%";
$params[]= "%".$keyword."%";

Then I execute:
$stmt=$cxn->prepare($query);
$stmt->execute($params);

This WORKS, but...
If, after the foreach loop, I want to add " LIMIT ?,?", I do this:
$query.=" LIMIT ?, ?";
$params[]=$row_number;
$params[]=$items_per_page;

Then I execute the script, and it throws this Fatal Error:
PHP Fatal error:  Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
 check the manual that corresponds to your MySQL server version for the right syntax
 to use near ''0', '2'' at line 1' in ..../index.php:247
  Stack trace:
  #0 .../index.php(247): PDOStatement->execute(Array)
 #1 {main}
 thrown in ..../index.php on line 247

I tried to do add apostrophes around the keywords: $params= "'%".$keyword."%'";
But this didn't work.
Also, I tried the exact same query inside PHPMyAdmin and it worked.
Does anyone know why this is throwing an error?
Thanks a lot in advance.

A: Update:
$query="SELECT * FROM article WHERE title LIKE ? OR description LIKE ?";
$query.=" LIMIT ?, ?";
$stmt=$cxn->prepare($query);
$stmt->bindValue(1, "%".$keyword."%");
$stmt->bindValue(2, "%".$keyword."%");
$stmt->bindValue(3, $row_number, PDO::PARAM_INT);
$stmt->bindValue(4, $items_per_page, PDO::PARAM_INT);

$stmt->execute();

A: The reason LIKE isn't working, is because when you use bind parameters with LIKE it's treating '%value%' as a string.
You're going to have to use:
$query="SELECT * FROM article WHERE title LIKE CONCAT('%',?,'%') OR description LIKE CONCAT('%',?,'%')";

A: I think you need to convert the variable you have passed in your limit clause. see this ...to use near ''0', '2'' there are single quotes on the values in the LIMIT clause
try
$query.=" LIMIT ?, ?";
$params[] = intval($row_number);
$params[] = intval($items_per_page);


text:
Q: useMediaQuery to detect multiple breakpoints I'm trying to detect multiple breakpoints on my application so that the columns generated on a Grid is dynamic. I'm able to achieve this but the code seems rather repetitive. Is there a way I can simplify my code further?
    const isMdUp = useMediaQuery(({ breakpoints }) => breakpoints.up('md'));
    const isSmUp = useMediaQuery(({ breakpoints }) => breakpoints.up('sm'));
    const isMdDown = useMediaQuery(({ breakpoints }) => breakpoints.down('md'));

    let imageListCol = 1;

    if (isMdUp) {
        imageListCol = 3;
    } else if (isSmUp && isMdDown) {
        imageListCol = 2;
    }

    return (
        <ImageList cols={imageListCol} gap={20}>
            ...
        </ImageList>
    )

A: Yes, you can remove one of them:
const isMdUp = useMediaQuery(({ breakpoints }) => breakpoints.up('md'));
const isSmUp = useMediaQuery(({ breakpoints }) => breakpoints.up('sm'));

// removing the isMdDown
// const isMdDown = useMediaQuery(({ breakpoints }) => breakpoints.down('md'));

let imageListCol = 1;

if (isMdUp) {
    imageListCol = 3;
} else if (isSmUp && !isMdUp) { // and we are going to use the opposite of isMdUp
    imageListCol = 2;
}

return (
    <ImageList cols={imageListCol} gap={20}>
        ...
    </ImageList>
)


text:
Q: Reparametrisation of closed not closed I would like an example of a closed curve and a reparametrisation of the same curve that is not closed.
Closed in the sense that it is periodic. i.e there exists $r\in \mathbb{R}-0$ such that $\gamma$ is not constant and $\gamma (t+r)=\gamma (t)$ for all $t$ in the considered domain.

A: Take a circle.  You know the periodic parametrization with $sin$ and $cos$.  Now just make it so that the parametrization winds around the circle faster and faster, so that there can't be a period.
E.g. Take the parameterization: $t \mapsto (\sin(e^t), \cos(e^t))$.

A: The mapping ${\Bbb{R}}\longrightarrow{\Bbb{R}}^2$ given by
$$t\longmapsto\left(\begin{array}{c}\dfrac{2t}{1+t^2}\\\\\dfrac{1-t^2}{1+t^2}\end{array}\right),$$
re-parameterize the circle of radius one centered at the origin minus the point $\left(\begin{array}{c}0\\-1\end{array}\right)$.


text:
Q: How to group a list of symbols or numbers into a # symbol I am trying to create a glossary of terms ordered alphabetically like this example:
 -A-
 Alpha
 ATM

 -B-
 Beta
 ...

I have no problem to group terms by letter but I wonder how I can manage symbol and digits in order to group them through a # symbol
-#-
52 weeks low
@test

I figured out to add a column in my Term table where I specify the first letter (in the symbol case I would select a "#" in a select box for example) but I would be pleased to know if there is a better way to achieve this without adding another field.
As info, here is my controller:
@terms = Term.all.group_by{|t| t.name[0]}

and my view:
<% @terms.keys.sort.each do |first_letter| %>
  <%= first_letter %>
  <% @terms[first_letter].each do |term| %>
    <%= term.name %>
  <% end %>
<% end %>

Thanks for your help!

A: You can do it like this, might be a performance hit, but gets the job done:
@terms = Term.all.group_by{|t| t.name[0].capitalize.match(/[A-Z]/) ? t.name[0].capitalize : "#" }


text:
Q: Is there an ant equivalent to make generic rules? Is there an Apache Ant equivalent to make rules of the form:
%.object: %.source
    ${TRANSFORMER} $< -o $@

This is a pattern that I find myself using frequently and really miss from make.  It would be even better if there is an equivalent that can detect changes to the source files similar to the way make does.


text:
Q: Possible to make regular expression with sub-query I am trying to write a regular expression for a bit of javascript code that takes a user's input of a mobile number and in one regular expression, performs the following checks:

*

*Starts with 07

*Contains only numbers, whitespace or dashes

*Contains exactly 11 numbers

Is this possible to do in just one regular expression and if so, how please?

A: I don't think it is possible with one regex, but it is possible by testing for two conditions:
if(/^07[\d\- ]+$/.test(str) && str.replace(/[^\d]/g, "").length === 11) {
   //string matches conditions
}

Explanation of the regex:

*

*^: Anchor that means "match start of string".

*07: Match the string 07. Together with the above, it means that the string must start with 07.

*[: Beginning of a character class i.e., a set of characters that we want to allow

*\d: Match a digit (equivalent to 0-9).

*\-:

*" ": Match whitespace (markdown doesn't let me show a single space as code)

*]: End of character class.

*+: One or more of the previous.

*$: Anchor that means "match end of string". Together with the ^, this basically means that this regex must apply to the entire string.

So here we check to see that the string matches the general format (starts with 07 and contains only digits, dashes or spaces) and we also make sure that we have 11 numbers in total inside the string. We do this by getting of anything that is not a digit and then checking to see that the length of the string is equal to 11.

A: Since @Vivin throws out the challenge :
 /^07([-\s]*\d){9}[-\s]*$/

*

*^07 : begin with digits 07

*( : start group

*[-\s]* : any number of - or whitespace

*\d : exactly one digit

*){9} : exactly 9 copies of this group (11 digits including 07)

*[-\s]* : optional trailing spaces or -

*$ : end of string

Of course a more useful way might be as follows
 if ((telNo = telNo.replace (/[-\s]+/g, '')).match (/^07\d{9}$/)) {
    ....
 }

which has the advantage (?) of leaving just the digits in telNo

A: Thank you all for trying, but after a good while trying different ideas, I finally found a working "single" regular expression:
07((?:\s|-)*\d(?:\s|-)*){9}

This make sure that it starts with 07, only contains digits, whitespace or dashes, and only 11 of them (9 plus the first 2) are numbers.
Sorry to have wasted your time.
Explanation:
()   - include in capture
(?:) - do not include in capture
\s   - whitespace
|    - or
-    - dash
*    - zero or more
\d   - digits only
{9}  - exactly nine of what is captured


text:
Q: Documentation or meaning of the pending_renewal_info attribute in an In-App Purchase receipt? Has anyone encountered the pending_renewal_info attribute while validating a receipt for an In-App Purchase or can anyone point to documentation regarding this field?
I have looked at the Apple documentation for Receipt Validation but do not see any references to this field which our system encountered for the first time today and flagged as being an unknown field. I am looking for any information to understand what it means and what action I should take.

A: It is documented at
https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html#//apple_ref/doc/uid/TP40010573-CH104-SW4
This hints whether a subscription is still pending for auto-renewal.
More details about these in WWDC 2017 Lecture 305 - Advanced StoreKit

A: It is documented at responseBody.Pending_renewal_info.
The most important info it contains IMO is grace_period_expires_date_ms which can be used to determine whether the subscription is in the grace period and is_in_billing_retry_period which determines whether Apple is trying to renew the subscription or not.
Discussion section:

In the JSON file, pending_renewal_info is an array in which each element contains the pending renewal information for each auto-renewable subscription identified by the product_id. A pending renewal may refer to a renewal that is scheduled in the future or a renewal that failed in the past for some reason. It is only returned for app receipts that contain auto-renewable subscriptions.
You can use this value to get critical information about any pending renewal transactions for an auto-renewable subscription.

Refer Engineering Subscriptions video from WWDC 2019 for more information.


text:
Q: Want to find exact 5 strings sentences I want to search a string which contains a maximum of 5 words.
I.e.it should match:
abc def ghi jkl mno
but not
abc def ghi jkl mno pqr
as it has more than 5 words.
I have written this regex:
(([A-Za-z]+)( [A-Za-z]+){1,4})

but it also matches on abc def ghi jkl mno.

A: In order to match only strings containing 5 words or less, i.e. not any five words in a row, you also need to add anchoring to the beginning and end of the string:
^((?:\w+ ?){1,5})$

Example
https://regex101.com/r/pN9nQ0/1


text:
Q: Setting Job name for Spring batch job I have a requirement to run the same job multiple times in a day. For example: the job name is myHourlyJob. This job needs to run every hour and there is a validation that I need to do to check that for a day all 24 jobs ran successfully. My requirement is to add dynamic param in the jobname so I can identify each job based on the name.
For example :

*

*the job running on 1st Jan at 9am, the job name should be : myHourlyJob_20220109_9.

*the job running on 1st Jan at 2pm, the job name should be : myHourlyJob_20220109_14.

In general job name = myHourlyJob_YYYYMMDD_jobRunHour
It is possible to define the job name in Spring batch?

A: I believe the job name should not be changed, it is the same the job so it should have the same name. What you are describing is exactly the concept of job instance in Spring Batch, one instance for each hour in your case. It is the same job, it does the same thing over and over again, why should it have 24 names a day?
I suggest you keep a single name for your job, and launch a different instance every hour. In your case, the run time (the hour of the day) should be passed as an identifying job parameter and you will have 24 job instances for the same job per day. Please refer to the reference documentation for more details about these concepts.


text:
Q: No response on stdout runtime error ~ HackerRank problem Below is the code for my if-statement, which is supposed to print out the String "Weird" or "Not Weird" depending on the value of n.
public class Solution {
    public static String weirdOrNotWeird(){

    int n;
    String ans = "";

    // if n is odd or n is even & 5 < n < 21 print Weird
    if((n % 2 == 1) || ((n % 2 == 0) && (n > 5 && n < 21))){
        ans = "Weird";

    // otherwise print Not Weird
    } else {
        ans = "Not Weird";
    }
    System.out.println(ans);
    return ans;
    }
}

When I compile, I get a runtime error that says "no response on stdout", and so doesn't give me an output.
private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int n = scanner.nextInt();
    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

    scanner.close();
}

This is the rest of the code from the problem, but I don't have any errors in this part.
UPDATE: I didn't define int n as a parameter in my weirdOrNotWeird() function, and I didn't call my weirdOrNotWeird() function in my main method.  After I did those things my code worked.

A: Define your method with one parameter and pass n as parameter in this method.
 public static String weirdOrNotWeird(int n) {
        String ans = "";
        // if n is odd or n is even & 5 < n < 21 print Weird
        if ((n % 2 == 1) || ((n % 2 == 0) && (n > 5 && n < 21))) {
            ans = "Weird";
            // otherwise print Not Weird
        } else {
            ans = "Not Weird";
        }
        return ans;
    }

And call you method after scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); passing n as parameter like following:
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(weirdOrNotWeird(n));
scanner.close();


text:
Q: Object X pos is drastically changing after screen shake ends I'm using the code below to move my player, named balloon, left and right on the x axis by calculating the difference between where you first touched (or clicked) and where you're currently touching, using ScreenToWorldPoint.
void Update()
{
    if (gameStarted)
        if (Input.GetMouseButtonDown(0))
        {
            firstTouch = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            startPos = balloon.position;
        }

        if (Input.GetMouseButton(0))
            CheckTouchPosition();
    }
}

void CheckTouchPosition()
{
    Vector2 currentTouch = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    float horizontalDif = currentTouch.x - firstTouch.x;
    balloon.position = new Vector2(startPos.x + horizontalDif * 1.2f, balloon.position.y);
}

This works normally except after I run into an obstacle and call my trigger shake function, which performs a typical screen shake.  After the screen shake ends the player is translated across the X axis, from what I can tell in the inspector roughly doubling its X position.
public class ScreenShake : MonoBehaviour {

Vector3 initialPosition;
float shakeDuration;

public bool shaking;

[SerializeField] float shakeMagnitude = 0.5f;
[SerializeField] float dampingSpeed = 1.0f;

void Update()
{
    if (shakeDuration > 0)
    {
        shaking = true;
        transform.localPosition = initialPosition + Random.insideUnitSphere * shakeMagnitude;
        shakeDuration -= Time.unscaledDeltaTime * dampingSpeed;
    }
    else
    {
        shakeDuration = 0f;
        transform.localPosition = initialPosition;
        shaking = false;
    }
}

public void TriggerShake(float duration, Vector3 position)
{
    shakeDuration = duration;
    initialPosition = position;
}

}
I can't figure out why the balloon's X is changing after the screen shake, but it doesn't happen if I don't call that function. I think maybe it has to do with ScreenToWorldPoint being messed up because I'm changing the position of the camera?
EDIT: I forgot to add that the weird repositioning of the balloon ONLY occurs if youre currently holding touching the screen (or holding down the mouse button) when the screen shake occurs.  Otherwise everything happens normally.


text:
Q: Displaying images in new line using HTML/CSS I'm trying to display 2 images in a line below a line of text, but they show up in the same line. I tried using the "clear: both" property and "display: block" property in the CSS style for the images. What am I missing?
I included a screenshot of what it looks like as well as the relevant section of the HTML code and the complete CSS stylesheet. The "media" class is what I am using for the images. They are showing on the same line as the  section under the "Contacts" div.
screenshot of website here

body {
  background-color: #63a4ff;
  background-image: linear-gradient(315deg, #63a4ff 0%, #83eaf1 74%);
}

.fadeline {
  background-color: white;
  margin: 25px 20%;
  width: 60%;
  height: 1px;
}

.fadeline.white {
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.75), rgba(255, 255, 255, 0));
}

.fadeline.black {
  background: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0));
}

.row {
  background-color: white;
  margin: 0% 15% 0% 15%;
  padding-bottom: 15%;
  padding-top: 50px;
  color: #586E95;
}

.header {
  text-align: center;
  padding-left: 40%;
}

#about {
  text-align: center;
}

p {
  margin: 0 auto;
  display: block;
  clear: both;
}

.example {
  margin: 0 auto;
  background-color: white;
  border: 1px solid black;
  border-radius: 10%;
  outline: none;
  width: 20%;
}

a,
a:hover {
  text-decoration: none;
  display: block;
}

img {
  max-height: 90%;
  max-width: 90%;
}

.media {
  height: 55px;
  width: 55px;
  display: block;
  margin: 0 auto;
}

Contact

 Want to connect? Reach out with Facebook or LinkedIn.

A: It looks like they're not below the text because they're in the same div with the row class.
Put them in a div below the row and it should work

A: Add a class to both images. For example
Class="img-1"
And
Class="img-2"
Make their position relative then push one of the images to the right. It may take some fiddling to get the locations correct

A: If you place both images in one div with the class .media then set that div to display: flex that should work.
Check out the example code below by clicking the Run code snippet

body {
  background-color: #63a4ff;
  background-image: linear-gradient(315deg, #63a4ff 0%, #83eaf1 74%);
}

.row {
  display: flex;
  flex-direction: column;
  background-color: white;
  margin: 0 15%;
  padding: 50px 0;
  color: #586E95;
}

.text-center {
  text-align: center;
}

.heading {
  text-align: center;
}

.fadeline {
  background-color: white;
  margin: 25px 20%;
  width: 60%;
  height: 1px;
}

.fadeline.white {
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.75), rgba(255, 255, 255, 0));
}

.fadeline.black {
  background: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0));
}

.media {
  display: flex;
  justify-content: center;
  width: 100%;
}

a img {
  width: 40px;
  margin: 0 10px;
}

Contact

 Want to connect? Reach out with Facebook or LinkedIn.


text:
Q: Citation with chapter in Listing caption \documentclass{article}
\usepackage{listings}
\usepackage{biblatex}
\usepackage{filecontents}

\addbibresource{\jobname.bib}

\begin{filecontents}{\jobname.bib}
@book{foo}
\end{filecontents}

\begin{document}
This is normal text. Text taken from~\cite[Chapter~x]{foo}.

\begin{lstlisting}[caption={This is the caption. Code taken from~\cite[Chapter~x]{foo}}]
clear all;
\end{lstlisting}

\end{document}

This is the actual result:

Why does it show the actual name of the reference (foo) in the caption and how can I remove that part?
The caption should simply be This is the caption. Code taken from [1, Chapter x].

A: You can get the desired output if you change your curly braces a bit. The MWE below shows two possible solutions.
\documentclass{article}
\usepackage{listings}
\usepackage{biblatex}

\addbibresource{biblatex-examples.bib}

\begin{document}
This is normal text. Text taken from~\cite[Chapter~x]{sigfridsson}.

\begin{lstlisting}[caption=This is the caption. Code taken from~{\cite[Chapter~x]{sigfridsson}}]
clear all;
\end{lstlisting}

\begin{lstlisting}[caption={{{{This is the caption. Code taken from~\cite[Chapter~x]{sigfridsson}}}}}]
clear all;
\end{lstlisting}

\end{document}

First of all, we need at least one pair of curly braces to 'hide' the square brackets for the optional argument of \cite inside the square brackets for the optional lstlisting. If we don't hide the brackets, the optional argument is not parsed correctly. (See ] inside an optional argument)
Unfortunately, the straightforward idea of just using one pair of curly braces for the entire caption does not work reliably. That is because the optional argument of lstlisting is parsed as a key-value option list. There are different key-value implementation in the LaTeX world (A big list of every keyval package), the one used here (the well-known keyval) strips up to two layers of outer braces from the argument during processing. I haven't traced what exactly happens on the listings side, but it is possible that additional processing steps strip additional outer layer of braces and do not take measures to stop square brackets from breaking in optional arguments.
So one solution is to brace not the entire caption, but only the bit that needs it. This works with comparably few braces, because they braces are not stripped during processing (as they are not outer braces). Another solution is to us as many outer braces as necessary to make sure not all of them are stripped away. Trial and error suggests four pairs of braces are needed here (on general you can't tell how many pairs of braces are needed in advance without tracing the code).


text:
Q: Are comments a good place for someone to keep cut-and-pasting grammar advice? Today I've seen a user on Stackoverflow put a comment on a lot of users posts saying:

Please don't forget to add a '?' to questions! Some people do a search in the page for '?' and if none exists in the 'question' go directly to the next (actual) question in line.

The user posting this has nearly 100k reputation and I guess we frequent the same tags as I've seen the identical comment in at least 5 or 6 posts today.
Personally I find these comments annoying as they contribute nothing actually meaningful to the discussion or the question. If I click to read a comment I don't want to see pedantic comments on grammar every time, so on the 5th one I queried it.
How can I inform a user that the value he's entered has been contrained to the JSpinner lower bound?
To which the response started hostile and moved on to insulting so there was clearly no point trying to discuss it further.
So:

*

*Is it really true that a significant portion of people just do a search for a "?" on opening a question? Is that actually good advice?

*Is it correct behaviour for someone to be repeatedly posting grammar quibbles in questions?

A: I will not delete my original answer, I'll let it stay on the public record so people who agreed with my original answer can vote this one down.  OTOH I've decided that it is not worth using that comment any longer.
As I have been reminded on this thread by @SamIAm, the OP does get explicitly notified when their question is edited.  I'd completely forgotten about that.
Thinking for a while that I might just move the comment to the edit reason (which I typically leave blank, on the basis that it is easy to see in the revisions what has been changed — that plus expedience), I've also rejected that for two reasons.

*

*The 'little comment app.' that I wrote specifically for my copy/paste comments (I have a lot of them) is only set up to provide a single comment area, and I could not be bothered changing it.  The technical comments are far more important and useful.

*It might be seen that I am trying to 'hide' such advice in the edit comments out of general view to avoid criticism.  If I'm going to write something, I'd prefer it to be in public view where it can be flagged or critiqued.

If I'm editing, I do think it is worth adding a '?' to questions. But I'll just make the edit & move on without further comment.

I truly thought I was helping the questioner as well as the general community, but that confidence is now much weaker.  So I'll write no more on the '?'.
I still have a few comments in the app. that relate to what people consider grammar as opposed to being purely technical.  I'll review those over the next couple of days.  Probably most of them will go, possibly all of them.

A: For the record, this is the comment that started our discussion.

Please don't forget to add a '?' to questions!  Some people do a search in the page for '?' and if none exists in the 'question' go directly to the next (actual) question in line.

I feel it is:

*

*Polite.

*Factual.

*Possibly helpful to the person who wants information.

I make many minor edits without comment.  I would hope that when someone sees their own question edited, they might ask why, or review the edits for tips.  Realistically though, I doubt that happens often, which is why I specifically comment on it.
On some questions where I make the comment (and admittedly that was one of them), it is obvious what the question could be when you actually read it carefully, but on many others, it is not.
E.G. 'My code does not work' might imply a question of:

*

*Why doesn't it work?

*What do I need to do to fix it?

*Is this the right approach, or should I try something completely different?

*Can you fix my code for me?

*Am I misunderstanding the problem statement, and actually getting the correct result?

*...

For those, I cannot see that inferring a question is the best approach, since that leads to people answering the wrong question, and irritated rebukes from the person who asked.
So my point is, in most cases, it's a judgement call I'm not willing to make.  On others, my review of the post is simply skimming over the text to:

*

*Remove the major tag from the title

*Turn the title into a statement, while copy/pasting the question into the body (a question earlier today had another poster criticizing the OP for not asking a question, when it was actually in the title)

*Correct spelling

*Add a space after a full stop.

*Correct the capitalization at the start of sentences, proper names, classes etc.

*Break 'walls of text' into readable paragraphs.

*Correcting SHOUTING.

*..

When I'm doing it, it is like 'in one eye, out the other'.  By the time I've finished editing, the post reads and looks much cleaner, but I couldn't say I actually have a grasp of what the person is asking or an overall idea of what the post is about.
But as I'm going, I alt/tab to a little comment app., type the 3 or 4 letters I need to select that comment, and add it to the list of comments to provide the user for future.  This usually does not cause a great problem.
OTOH you took exception to it.   The way I see it, your beef is:

*

*Not helpful to the question or the OP.

*Not productive in the wider scheme of things.

I will continue to edit & comment much as I have in the past, but will try to recognize those statements that 'all but lacking a ?', are a question.  Don't count on me noticing them though.
Unless the powers that be decide that my behavior is intolerable and ban me, I'll tend to continue to make that comment, and do so prolifically.

A: Anybody who has watched my moderation for any length of time knows that I am a stickler for proper grammar spelling and punctuation.  Using adequate English demonstrates two things: literary competence and respect for your fellow netizens.
Nevertheless, I am going to weigh in that insisting on a question mark in a title (in the absence of any other spelling or grammatical problems) is absolutely pointless.  Despite the commenter's premise, it has no effect on searches, and the larger problem is that many titles are incomprehensible.  I would much prefer that folks focus on writing a clear title that will highlight the subject matter correctly, regardless of whether it has a question mark or not.

A: This is a stupid thing for either one of you to waste any time or thought on.
Obviously Andrew observed a common problem with titles and was driven to try and correct it, albeit in a fairly unproductive fashion. You observed a problem with comments, and also attempted to correct it... in a similarly unproductive fashion.
In much less time than it took you to have your little comment discussion, I edited the title to make it more descriptive of the actual question and include a question mark and added a comment recommending this to the both of you.
I strongly recommend you follow this example in the future.
For a discussion of how comments can be used to augment edits, see: "That's not what the comments are for"

A: Nobody over 2000 reputation needs to leave a comment correcting an OP's grammar.
If you see a clear problem then you can go in and edit the problem yourself, and when you do this, the OP will be notified that you've edited their post, and they will be able to see the edit that you've made.
For most people, looking over your edits should be enough to tell them that they made some grammar mistakes that you don't think should be there.
There isn't any need to add clutter to the comments.


text:
Q: How to pass url in axios.get(apiendpoint)? How to pass the apiurl in axios.get()?
I am getting data from asp.net model displayed in html page.
My sql table comprise of title= "first title" , and apiurl = "/api/abc".
If I specify with static data it works. Example:
axios.get('/api/abc')

and then all chartjs code will display my chart perfectly.
My View has got data from model. code as follows:
@foreach (var a in model)
{
<myvuecomponent title = "@a.title" apiurl = "@a.apiurl"><myvuecomponent>
}

How do I pass data dynamically in javascript file?
My component is displaying correct title. But I need help on passing the apiurl in --> axios.get(apiurl)
I am getting 404 axios error.


text:
Q: How do i use rxjava to make a retrofit request in a repository and pass it to a ViewModel using LiveData? I'm trying to make an Android app that uses Google's architecture components. I'm making a request to the TasteDive API using retrofit and rxjava in a Repository class. The problem that I'm facing is that I can't find a way to pass the outcome of the retrofit request to the ViewModel using LiveData. What I'm currently doing is I have a sealed class called Outcome that keeps track of the state of the request and in this sealed class i have a data class that holds the data of a successful request. However, since rxjava's observable is a callback, I can't figure out a way to assign the outcome of the request to LiveData and pass it to the ViewModel. When I try to assign the outcome to LiveData, it returns null, unsurprisingly, since the observable is a callback. Can any of you help me figure out a way to store the outcome of the retrofit request into LiveData in order to pass it to the ViewModel? I have looked all over the internet for a solution to this and have not found anything helpful. Here's my repository class:
class GetSimilarDataRepository {
    private var mAdapter: TasteDiveAdapter? = null
    private lateinit var mResultsList: ArrayList<Result>

    private var observable: Observable<Response<TasteDive>>? = null

    private var liveData = MutableLiveData<Outcome<List<Result>>>()

    fun getSimilarData(map: LinkedHashMap<String, String>): LiveData<Outcome<List<Result>>> {
        mAdapter?.clear()

        val builder = Retrofit.Builder()
                .baseUrl("https://www.tastedive.com/api/")
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())

        val retrofit = builder.build()

        val client = retrofit.create(TasteDiveClient::class.java)

        observable = client.getSimilarData(map)

        observable?.filter { it.code() == 200 }
                ?.map { Observable.just(it.body()) }
                ?.subscribeOn(Schedulers.io())
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.doOnNext {
                    liveData.value = Outcome.loading(true)
                }?.doOnError {
                    liveData.value = Outcome.failure(it)
                }?.subscribeBy (
                        onError = {
                            liveData.value = Outcome.failure(it)
                        },

                        onNext = {
                            it.subscribe {
                                var similar = it?.Similar
                                var results = similar?.Results
                                if(results!!.isEmpty()) {
                                    liveData.value = Outcome.failure(Throwable("No results for that request"))
                                } else {
                                    mResultsList = ArrayList(results)
                                    liveData.value = Outcome.success(mResultsList)
                                }
                            }
                        },

                        onComplete = { Log.v("onComplete", "onComplete")}
                )

        observable?.filter{ it.code() == 403 }
                ?.map { Observable.just(it.body()) }
                ?.subscribeBy(
                        onNext = {
                            liveData.value = Outcome.failure(Throwable("403 Response Code"))
                        },
                        onError = { Log.v("onError403", "onError403") },
                        onComplete = { Log.v("onComplete403", "onComplete403") }
                )

        observable?.filter{ it.code() == 404 }
                ?.map { Observable.just(it.body()) }
                ?.subscribeBy(
                        onNext = {
                            liveData.value = Outcome.failure(Throwable("404 Response Code"))
                        },
                        onError = { Log.v("onError404", "onError404") },
                        onComplete = { Log.v("onComplete404", "onComplete404") }
                )

        observable?.filter{ it.code() == 400 }
                ?.map { Observable.just(it.body()) }
                ?.subscribeBy(
                        onNext = {
                            liveData.value = Outcome.failure(Throwable("400 Response Code"))
                        },
                        onError = { Log.v("onError400", "onError400") },
                        onComplete = { Log.v("onComplete400", "onComplete400") }
                )

        observable?.filter{ it.code() == 500 }
                ?.map { Observable.just(it.body()) }
                ?.subscribeBy(
                        onNext = {
                            liveData.value = Outcome.failure(Throwable("500 Response Code"))
                        },
                        onError = { Log.v("onError500", "onError500") },
                        onComplete = { Log.v("onComplete500", "onComplete500") }
                )
        return liveData
    }
}

The request is working, because mResultsList is giving me the correct results, but LiveData is returning null.
Here is the sealed class Outcome:
sealed class Outcome<T> {
    data class Progress<T>(var loading: Boolean) : Outcome<T>()
    data class Success<T>(var data: T) : Outcome<T>()
    data class Failure<T>(val e: Throwable) : Outcome<T>()

    companion object {
        fun <T> loading(isLoading: Boolean): Outcome<T> = Progress(isLoading)

        fun <T> success(data: T): Outcome<T> = Success(data)

        fun <T> failure(e: Throwable): Outcome<T> = Failure(e)
    }
}

Thanks for your time.

A: The issue is with the need for a Lifecycle Owner used for observations of LiveData in the Repository.
First, you don't want to do all networking actions inside the ViewModel. I think you have the right idea with the Repository, but you have to remember that the Repository will have to communicate only with the ViewModel.  Best case, you would want the function getSimilarData(...) do some something like this:
Repository{
    val repositoryItems = BehaviorSubject.create<Outcome<List<Result>>>()

    fun observeRepositoryItems(): Observable<Outcome<List<Result>>> {
        return repositoryItems
    }

    fun getSimilarData(map: LinkedHashMap<String, String>){
        // Pseudo code for actually items

        // Result goes into repositoryItems.onNext(...)
    }
}

However, you will have the issue of observing the status from the ViewModel as it itself is not a Lifecycle implementation, so it cannot easily observe the LiveData from the Repository.
My suggestion would be something like this:
Repository{
    val repositoryItems = BehaviorSubject.create<Outcome<List<Result>>>()

    fun observeRepositoryItems(): Observable<Outcome<List<Result>>> {
        return repositoryItems
    }

    fun getSimilarData(map: LinkedHashMap<String, String>){
        // Pseudo code for actually items

        // Result goes into repositoryItems.onNext(...)
    }
}

ViewModel{
    val items: MutableLiveData<Outcome<List<Result>>>

    init{
        repository.observeRepositoryItems()
            .subscribe( items -> items.postValue(items ))
    }

    fun getData(){
        repository.getSimilarData(someMap)
    }
}

Fragment{
    viewModel.items.observe() // <-- Here you observe items loaded
}

Note that you will have to dispose the subscription in the ViewModel onCleared.
Note that all of this is pseudo code and it should be done a lot cleaner than this.


text:
Q: Authentication failure in Heroku CLI after password change After a password change on heroku's website, I can't access the heroku api.
When I do heroku login, I get Authentication successful, even though it shouldn't because the password has changed. It doesn't even ask for my email or password, like it should!
If I try heroku apps (or any other application related command), I get Authentication failure.
If I try heroku status, it works.
I don't have any plugins installed.
Logs:
$ heroku version
heroku-gem/3.6.0 (i686-linux) ruby/2.1.0
$ heroku logout
Local credentials cleared.
$ heroku login
Authentication successful.
$ heroku apps
Authentication failure
$ heroku plugins
You have no installed plugins.

I'll appreciate any help or ideas I can get. I already opened a ticket and waiting for the Heroku Support to get back to me.
Thanks

A:
Are you using the heroku-accounts plugin? If so, try uninstalling it.

You may not need to uninstall it...
Make sure you are not in a project directory (or you may run into the "account not found" loop).
cd

List your accounts.
heroku accounts

On each account where the password was changed
heroku accounts:remove ACCOUNT
heroku accounts:add ACCOUNT

(I did not need to do anything with the ~/.ssh/config.)
Reset your default account, if needed.
heroku accounts:default ACCOUNT

If you changed the account name or git config --unset heroku.account.
cd /path/to/your/project
git config --add heroku.account ACCOUNT

I didn't want to give up on the heroku-accounts plugin.  :)

A: heroku accounts:remove personal or whatever account name you have
git config --unset heroku.account
heroku accounts:add personal then login

A: In my case, I had multiple heroku accounts managed by heroku-accounts gem and authentication started failing after I changed one of my account's password.
Steps I followed to make things normal again:

*

*Removed the account (that's failing to authenticate) from heroku accounts:
heroku accounts:remove account_name

*Opened up a new terminal and then added the account again that I just deleted:
heroku accounts:add account_name --auto
Here you have to use your new credentials.
That's it. Problem solved.

A:
After a password change on heroku's website, I can't access the heroku api.

Are you using the heroku-accounts plugin?  If so, try uninstalling it.
heroku plugins:uninstall heroku-accounts
rm -r ~/.heroku/accounts
heroku logout
heroku login

*

*https://github.com/ddollar/heroku-accounts/issues/56

A: Apparently, changing the password for heroku regenerates a new API key, and I had the wrong HEROKU_API_KEY configured. (It regenerates a new one after password change).
I'm posting here the response from the great Heroku's support team, which gave me these suggestions:

*

*Is there a ~/.netrc file on your computer? If there is, can you please check if the file contains something Heroku related things? Please remove if there is, and try login again.

*Is there an HEROKU_API_KEY environment variable defined on your machine? If yes, could you remove it and login try again?

*Is there a ~/.heroku/credentials file (with or without an extension) on your machine? If yes, could you remove it and try login again?

*Finally, if none of those work, could try the following command: GEM_HOME='' BUNDLE_GEMFILE='' GEM_PATH='' RUBYOPT='' heroku login and see how it goes?

A: Try deleting ~/.netrc (this is where the Heroku CLI tool saves the auth tokens) and starting over.


text:
Q: Error while updating business network in CLI tutorial I am following along the Getting Started with Fabric Command Line and have run into a error I don't understand how to resolve.  Any ideas?
In the section entitled "Update the deployed business network" an exception is thrown.  The terminal output is below.  The command used:
composer network update --archiveFile digitalproperty-network@0.0.7.bna  --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d

Note that the id is different from the tutorial as the 0.0.7 id was reported during the previous step while creating.  The output continued...
Deploying business network from archive digitalproperty-network@0.0.7.bna
Business network definition:
    Identifier: digitalproperty-network@0.0.7
    Description: Digital Property Network
events.js:160
      throw er; // Unhandled 'error' event
      ^
Error
    at ClientDuplexStream._emitStatusIfDone (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:189:19)
    at ClientDuplexStream._readsDone (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:158:8)
    at readCallback (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:217:12)

I've struggled to get the versions to match the tutorials - they seem inconsistent.  Notably, the node (v6.9.5) and nodejs (v6.10.1) versions differ even though node is a symbolic link to nodejs and I notice 6.9.5 is in the stack trace.  I'm not sure that difference is relevant to the problem.
Other version information:

*

*Ubuntu 14.04.5

*Docker version 17.03.1-ce, build c6d412e (manually installed as auto
install was down level)

*docker-compose version 1.12.0-rc2, build 08dc2a4

A: I've seen exactly that error when Hyperledger Fabric isn't running. If docker ps doesn't show anything, run npm run startHLF in the sample-applications/packages/getting-started directory before trying again.


text:
Q: Vertical Menu with submenus flying out when mouse is hovered I am trying to create a vertical menu with fly outs .That is a vertical menu with sub-menus.What is wrong with the following code?

        <title>Untitled Document</title>

                    Home

                    Blog

                        Blog 1

                        Blog 2

                    Websites

                        Websites 1

                        Websites 2

                    Photos

http://jsfiddle.net/9bHkj/1/

A: You might have to revisit how you are constructing the menu. For instance:

                Blog

                    Blog 1

                    Blog 2

is supposed to be a Blog menu with two sub menus Blog 1 and Blog 2. But then
 for the sub menu is supposed to be within the
 of the menu and not separately:

      Blog

            Blog 1

            Blog 2

Once you do this, for the other submenus as well, you have the  flying sub menus. You can now work out the location, colors etc.

A: you wrote this twice:
#navmenu li {
    /* make the list elements a containing block for the nested lists */
    position: relative;
}

Your nested lists ul are not contained by li elements. So this will not work either:
#navmenu ul li:hover ul {
    display:block;
}

nesting your ul in li elements may solve your problem.


text:
Q: Post request returns undefined on the server side So, I have this POST request I made
$("#pacotes").on('click', ".produto", function () {
    console.log(this.id);
    $.post("http://localhost:3000/pacote?idPacote=" + this.id);
});

The log returns a number on the client side, as it should.
The post then goes through my route and arrives here
exports.Pacote = function (req, res) {
    console.log("gato");
    var pacote = req.idPacote;
    console.log(pacote);
    connection.connection();
    global.connection.query('SELECT * FROM Pacote WHERE idPacotes = ? LIMIT 1', [pacote], function (err, result) {
    if (result.length > 0) {
         if (result) {
              var object = JSON.parse(JSON.stringify(result));
              var packObject = object[0];
              if (result.length > 0) {
              if (result) {
                   res.render('home', { title: 'pacote', layout: 'pacote', data: packObject  });
              }
         }
     } else if (err) {
      console.log(err);
     }
   };
   });
}

The first log is just a flag to see if it is reaching the point, which it is
But the second log should return a number, yet it is returning undefined
I'm not very experienced in this subject, but this has always worked for me.
I don't understand where I went differently as my login function is nearly the same thing and returns actual values as expected. Maybe because of bodyparser, but I dont know.
It just bothers me that the id returns properly on the client side but as undefined on the server side
I also tried the same thing but with GET and the results didnt change

A: You are passing "idPacote" in query string. You will get the the query string parameters in "req.query" if you are using Express with NodeJS. Try this
var pacote = req.query.idPacote;

instead of
var pacote = req.idPacote;

A: The var pacote = req.idPacote; should be replaced with (provided that you send it as GET parameter):
var pacote = req.params.idPacote;

A side note: you should be using connection pooling in order to improve performance in your app, for example:
var mysql = require("mysql");
//Database connection parameters
var config = {
    connectionLimit: 10000,
    host: "127.0.0.1",
    user: "user",
    password: "password",
    database: "database",
    charset: "utf8_general_ci",
    connectTimeout: 4000
};
//Pool
var pool  = mysql.createPool(config);
function connection(){
    //Assign connection pool for further reuse
    this.init = function () {
        this.pool = pool;
    };
    //Get connection
    this.acquire = function(callback){
        this.pool.getConnection(function(error, con){
            if (error) {
                if (this.pool)
                    //Close all connections in pool
                    this.pool.end(function(err){});
                console.log("\x1b[31m" + error, "\x1b[0m");
            }
            else {
                callback(error, con);
            }
        });
    };
}

Read more here.


text:
Q: C# IEnumerable implementation I don't think I understand IEnumerable and have done several google search.
I'm supposed to make an Container of some objects, where the class Container should handle the updating of the collection the Container represent (add, remove).
the collection Container should be and instance of IEnumerable<element>.
namespace ....
{
    public class Container : Ienumerable<Elements>
    {
        List<Elements> _elm = new List<Elements>();
        List<Elements> _add = new List<Elements>();
        List<Elements> _rem = new List<Elements>();

        public voic PendAdd(Element elm)
        {
            _add.Add(elm);
        }

        public voic Pendrem(Element elm)
        {
            _rem.remove(elm);
        }

         ...

        public IEnumerator<Element> GetEnumerator()
        {
            return _elm.GetEnumerator();
        }

    }
}

My problem is that IEnumerable<Elements> is an abstract type and if i make _elm this type i can't handle the state of the Container even if i make it
IEnumerable<Element> _elm = new List<Element> ();

VS complains about the error:

'Container' does not implement interface member
  'IEnumerable.GetEnumerator()'. 'Container.GetEnumerator()' cannot
  implement 'IEnumerable.GetEnumerator()' because it does not have the
  matching return of 'IEnumerator'.

I know that there are several answers about IEnumerable but they do not help me.

A: You are missing the IEnumerable.GetEnumerator(): IEnumerable<T> inherits from IEnumerable. so in your class you need two distinct GetEnumerator() with two distinct return types.
public class Container : IEnumerable<Element>
{
    List<Element> _elm = new List<Element>();
    List<Element> _add = new List<Element>();
    List<Element> _rem = new List<Element>();

    public void PendAdd(Element elm)
    {
        _add.Add(elm);
    }

    public void Pendrem(Element elm)
    {
        _rem.Remove(elm);
    }

    public IEnumerator<Element> GetEnumerator()
    {
        return _elm.GetEnumerator();
    }

    // This is called "explicit interface implementation", see
    // https://msdn.microsoft.com/en-us/library/ms173157.aspx
    IEnumerator IEnumerable.GetEnumerator()
    {
        // will call the "other" GetEnumerator()
        return GetEnumerator();
    }
}

The next time you have to implement an interface, I suggest you right click on the interface in Visual Studio and select the Implement Interface to get the skeleton of all the methods you need.


text:
Q: alternative directory for files if not exists lets say i make a request to http://www.mysite.com/files/picture.jpg so my picture.jpg is supposed to be in htdocs/files/picture.jpg
how do i configure if picture.jpg does not exist in htdocs/files then look it up inside htdocs/files/alt?
the filename varies, but the alternate directory name (alt) is fixed (which reside inside the original directory)
is this achievable using apache config?

A: You should use an Apache module called mod_rewrite to achieve this.
http://httpd.apache.org/docs/current/en/rewrite/
Apache's mod_rewrite module provides a way to modify incoming URL requests dynamically, based on regular expression rules.
The RewriteCond directive from mod_rewrite has the -f flag which allows you to test if a file exists.
To enable this module you should just have to run the following and restart Apache :
# a2enmod rewrite
# service apache2 restart

Then, you will have to define a Rewrite rule in your VHost config file.
The Rewrite rules will be something like this :
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/files/(.+)$ /files/alt/$1 [L]


text:
Q: Sample Java code to connect to AWS S3 using VPC endpoint I am new to AWS, and was looking for a java sample for connecting to AWS s3 using vpc endpoint. I tried below snippet from my local machine, but it is not working. if i use same creds and login using SFTP client(WinSCP), i am able to login.
I want to use S3 to stream files from it, so that i can do file processing faster in my code. Also this code won't be running in EC2 instance.
AWSCredentials credentials = new BasicAWSCredentials("*****", "*******");
    ClientConfiguration clientConfig = new ClientConfiguration().withRequestTimeout(50000);
    clientConfig.setUseTcpKeepAlive(true);
    AmazonS3 s3client = AmazonS3ClientBuilder
            .standard()
            .withCredentials(new AWSStaticCredentialsProvider(credentials))
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("vpce-************-*******.server.transfer.us-west-2.vpce.amazonaws.com", Regions.US_WEST_2.toString()))
            .withPathStyleAccessEnabled(true)
            .withClientConfiguration(clientConfig)
            .build();

People in my team are just replacing legacy sftp connection details, with new S3 VPC endpoint, and using legacy code to upload files. But I don't think we are fully utilizing s3 features by doing that.
Expert help would be appreciated here.

A: There are multiple problems with the information presented in your question.
vpce-************-*******.server.transfer.us-west-2.vpce.amazonaws.com is not an Amazon S3 VPC endpoint.  It's a VPC endpoint for a service called AWS Transer for SFTP which provides a managed SFTP gateway that connects to an Amazon S3 bucket.
An S3 VPC Endpoint is different, requires no client configuration, and has no special endpoint hostname -- these are transparent and used automatically when created and correctly configured inside a VPC.  And they provide a REST interface, not SFTP.
In both cases, VPC endpoints can only be used from inside a VPC, so you wouldn't be able to access an AWS Transer for SFTP endpoint from outside of EC2 in any event.
But that's not, strictly speaking, why it isn't working.  The code you have would also not work inside a VPC, and the root of the problem is that AmazonS3 s3client = AmazonS3ClientBuilder builds an S3 REST client, not an SFTP client.  This client can't be used with an AWS Transfer for SFTP endpoint, either Internet-facing or inside a VPC, since such an endpoint is not what AwsClientBuilder.EndpointConfiguration() is designed to be used with.  The endpoints for use with the SDK are found here. For us-west-2, the endpoint for ipv4 connectivity is https://s3.us-west-2.amazonaws.com and for ipv4/ipv6 is https://s3.dualstack.us-west-2.amazonaws.com.


text:
Q: Array of composite type as stored procedure input I am creating a stored procedure using plpgsql by passing a type array and do a loop inside the procedure so that I can insert each info type
CREATE TYPE info AS(
    name  varchar,
    email_add  varchar,
    contact_no  varchar
);

CREATE OR REPLACE FUNCTION insert_info(
    info_array  info[]
) RETURNS varchar AS $$
    DECLARE
        info_element  info;
    BEGIN
        FOREACH info_element IN ARRAY info_array
        LOOP
            INSERT INTO info_table(
                name,
                email_add,
                contact_no
            ) VALUES(
                info_element.name,
                info_element.email_add,
                info_element.contact_no
            );
        END LOOP;
        RETURN 'OK';
    END;
$$ LANGUAGE plpgsql;

The problem is I don't know how to use the function with the array input. I did some experiments (with just some stupid inputs):
SELECT insert_info(
    ARRAY[('Arjay','myEmail@email.com','1234567')]
);

But PostgreSQL says that it is a record[] and I still haven't tested the Loop part ...
I have found a similar problem in this link:
Declare variable of composite type in PostgreSQL using %TYPE
but it did not use arrays. If this is just a duplicate question maybe you guys can point me in the right direction!

A: The call would be (with two array elements):
SELECT insert_info('{"(Arjay,myEmail@email.com,1234567)"
                    ,"(Bjay,my2Email@email.com,2234567)"}'::info[]);

Or with ARRAY constructor:
SELECT insert_info((ARRAY['(Arjay,myEmail@email.com,1234567)'
                         ,'(Bjay,my2Email@email.com,2234567)'])::info[]);

Or:
SELECT insert_info( ARRAY['(Arjay,myEmail@email.com,1234567)'::info
                         ,'(Bjay,my2Email@email.com,2234567)']);

But the whole operation can be more efficient with plain SQL using unnest():
INSERT INTO info(name, email_add,contact_no)
SELECT * FROM unnest('{"(Arjay,myEmail@email.com,1234567)"
                     , "(Bjay,my2Email@email.com,2234567)"}'::info[]);

You can wrap it into an SQL function if you need it as function call ...
CREATE OR REPLACE FUNCTION insert_info(info_array info[])
  RETURNS void
  LANGUAGE sql AS
$func$
INSERT INTO info(name, email_add,contact_no)
SELECT * FROM unnest($1)
$func$;

Same call.
Your original function would return after the first array element, btw.


text:
Q: When I define a function inside another function, I get a 'bad placement define' error Here is my code:
 (require 'hash-table)

 (define (hash-table-get htable key)
    ((hash-inquirer equal?) htable key))

 (define (hash-table-add! htable key val)
    ((hash-associator equal?) htable key val))

 (define (hash-table-remove! htable key)
    ((hash-remover equal?) htable key))

 (define (find-max-chain)
      (define table (make-hash-table 1000)) ; works
      .
      .
      .          ; proven working code

      (define (get-chain number) (let ((chain (hash-table-get table number))) chain))

      .
      .
      .        ; more code

    max-entry)
   (find-max-chain)

The problem is the (define (get-chain number)  [...] )) part. When I define it and table outside of (find-max-chain) in the global context, It suceeds when I run it. But when I define (get-chain) inside of (find-max-chain) where I need it, when I execute (find-max-chain) I get this error from SCM:
;ERROR: "problem14-new.scm": bad placement define
; in expression: (define (get-chain! number) (let ((chain (hash-table-ge ...
; in scope:
;   (update-max! table max-chain max-entry . #@define)
;   ()  procedure find-max-chain
; defined by load: "problem14-new.scm"

;STACK TRACE
1; (#@define ((update-max! (#@lambda (entry chain) (cond ((> chai ...
2; (#@find-max-chain)
3; (#@define ((hss (#@has-suffix? #@file (#@scheme-file-suffix))) ...

Why is this?

A: Inside a function, defines are only allowed at the beginning of a function (or function-like body), where in any case they are equivalent to a letrec. See this section from R5RS.

A: I'm not very familar with SCM and its error messages, but my first guess would be that you're running afoul of the letrec vs letrec* issue. R5RS says (roughly) that it must be possible to evaluate every right-hand side in a letrec form without touching any of the letrec bound variables; and the same restriction holds for internal definitions. (IIRC, R6RS added a letrec* form that allows such references.)
For example, the following is illegal:
(let ()
  (define x 1)
  (define y (+ 1 x))
  y)

because evaluating the y rhs requires the value of x. In contrast, this is okay:
(let ()
  (define x 1)
  (define f (lambda () (+ 1 x)))
  (f))

That is, it's not a question of scoping, it's a question of when a variable is "ready to use."


text:
Q: Div with a transparent background inside div with a repeating background I have a #div1 with 100% height and #div2 inside #div1. #div2 located at the top of #div1 with semi-transparent background. But, because the #div1 have a repeating background, translucent under the #div2 is the background of #div1. I want to "move" the background of #div1 from the top of the height of #div2
see image
CSS:
#div1 {
    border: none;
    width: 812px;
    height: 100%;
    background-image: url(http://i.imgur.com/tcPWRzF.png);
    background-repeat: repeat-y;
    margin: 0 auto;
}
#div2 {
    background-image: url(http://i.imgur.com/DnDnz22.png);
    background-color: transparent;
    background-position: center;
    width: 812px;
    height: 488px;
}

HTML:

A: Give div1 a little window to show through by giving it padding-top. http://codepen.io/amishstripclub/pen/VKdjmr
#div1 {
    padding-top: 488px;
}

A: For some reason that image in div1 isn't repeating. I don't know if this will work for you, but you can play around with it.
<!DOCTYPE html>

<title>page title</title>

A: try flexbox alternative for block level alignment

#div1 {
    border: none;
    width: 812px;
    min-height:1200px;
    height: 100%;
    background-image: url(http://i.imgur.com/tcPWRzF.png);
    background-repeat: repeat-y;
    margin: 0 auto;
     display: flex;               /* establish flex container */
    align-items: center;
}
#div2 {
    background-image: url(http://i.imgur.com/DnDnz22.png);
    background-color: transparent;
    background-position: center;
    width: 812px;
    height: 488px;
}

PC : Michael_B


text:
Q: Symfony enviar opciones a otro formulario anidado public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $respuestas = $options['respuesta'];

    if($respuestas == 0){
        $builder
        ->add('email', EmailType::class, array(
            'required'=>true,
            'attr'=> array('class'=> 'form-control', 'maxlength'=>250 )
        ))
        ->add('persona', PersonaType::class )

    ;
    }

Tengo el formulario persona que esta anidado a usuario
->add('persona', Persona1Type::class ) quiero mandarle array $options pero al momento de querer
->add('persona', Persona1Type::class, [], array($options['numpais']) )

no recibe nada el formulario


text:
Q: Why standard containers use function templates instead of non-template Koenig operators This question is inspired by Issue with std::reference_wrapper. Let' say, for example, operator< for std::vector. It's defined as a function template as
template< class T, class Alloc >
bool operator<( const vector<T,Alloc>& lhs,
                const vector<T,Alloc>& rhs );

As a result, implicit conversion of function argument to the type of the corresponding function parameter is denied (basically because of its template nature). This greatly reduces the usefulness and convenience of std::reference_wrapper. For example, you cannot use std::sort on std::vector<std::reference_wrapper<std::vector<int>>>.
On the other hand, all the problems are solved only if operator< is defined as a non-template Koenig operator like
template <...>
class vector ... {
  friend bool operator<(const vector& a, const vector& b) {...}
};

I'm wondering why the standard library has adopted the former approach instead of this?

A: Consider this code (A.h):
template <class T>
class A {
  public:
  T m_x;

  friend bool operator<(const A & lhs, const A & rhs) {
    return lhs.m_x < rhs.m_x;
  }
};

And main.cpp:
#include "A.h"

namespace buddy {
bool operator<(const A<double> & lhs, const A<double> &rhs) {
    return lhs.m_x > rhs.m_x;
};
}
using namespace buddy;
int main(int argc, char ** argv) {

  A<double> a1;
  A<double> a2;

  a1 < a2;

  return 0;
}

This code does not compile:
main.cpp:14:5: error: ambiguous overload for 'operator<' (operand types are 'A' and 'A')
  a1 < a2;
The reason of course is that both of the operator<'s are exact matches. On the other hand, if we change the first operator< to (defined outside the class):
template <class T>
bool operator<(const A<T> & lhs, const A<T> & rhs) {
  return lhs.m_x < rhs.m_x;
}

The compiler stops complaining: it's now a competition between an exact match, and a function template, so the exact match is used.
If operator< was defined in the fashion that you're suggesting, there would be no reasonable way for users of std::vector to redefine the behavior of operator<, short of specializing std::vector themselves, which is a lot more work.
In conclusion, the standard writers elected to make it easier to overload operator<, than to provide an operator< that might be more useful in certain situations. I think they made the right choice.


text:
Q: How to achieve cross isolate concurrency in flutter? I have a use case where I am using multiple flutter engines (my flutter app is embeded in Android), each engine has it's own app instance.
I am sharing common data across engines with Hive.
But one problem is, I want to achieve concurrency as multiple writes (which are async, so in case many engines try to write once) can lead to issues.
I tried exploring 'synchronized' package but it doesn't support mutex for multiple isolates.


text:
Q: The degree of a minimal polynomial Is there in general any way of finding the degree of the factors in the minimal polynomial of an operator without using brute force computation?
The exercise in question is shown below. It's only this part of (iii) that's bothering me. This is not a homework assignment.

My professor solved this problem for another exercise using the method shown below. I've been trying to understand if this is usable in general and if so how. I tried to adapt the method to this exercise but I didn't arrive at any contradiction.

A: Suppose $\lambda$ is an eigenvalue of an $n\times n$ matrix $A$ over $\mathbb C$ and let
$$
  d_i(\lambda)=\dim\ker(A-\lambda I)^i
$$
(with $d_0(\lambda)=0$). It's clear that the sequence $d_i(\lambda)$ is nondecreasing. Less obvious is that the successive differences $(d_{i+1}(\lambda)-d_i(\lambda))$ are nonincreasing (this is "(ii) of the previous exercise" in your notes). Since $d_i(\lambda)$ is bounded by $n$, this means $d_i(\lambda)$ is strictly increasing for a while, and then stabilises at some $d(\lambda)$. In fact $d(\lambda)$ is the dimension of the generalized $\lambda$-eigenspace of $A$, and the characteristic polynomial of $A$ is
$$
  \chi_A(x)=\prod_{\lambda\in\Lambda}(x-\lambda)^{d(\lambda)}
$$
where $\Lambda$ is the set of eigenvalues. Let $i(\lambda)$ be the index at which the sequence $d_i(\lambda)$ stabilises,
$$
  i(\lambda)=\min\{i\mid d_i(\lambda)=d(\lambda)\}.
$$
The minimal polynomial of $A$ is
$$
  \prod_{\lambda\in\Lambda}(x-\lambda)^{i(\lambda)}.
$$

In the example from your notes, you have $d_1(3)=d(3)=1$ so $i(3)=1$. Also $d_1(2)=2$ and $d(2)=3$. This leaves only one possibility for the sequence $d_i(2)$, namely:
$$
  (d_0(2),d_1(2),d_2(2),d_3(2),\ldots)=(0,2,3,3,\ldots).
$$
Note that the sequence can't be $0,2,2,3,\ldots$ because the successive differences must be nonincreasing. Thus $i(2)=2$. This same reasoning should apply to your exercise.

In general $d_1(\lambda)$ and $d(\lambda)$ may not be sufficient to determine $i(\lambda)$. It's possible to compute $\ker(A-\lambda I)^i$ for successive value of $i$ until the dimension stops increasing.

A: Here's another approach, not sure if compatible with what you've learned so far. If not maybe you can look back later.
You will need Cayley-Hamilton theorem and maybe something more. Background: The minimal polynomial divides the characteristic polynomial.
Cayley-Hamilton theorem is the result that every matrix fulfils it's own characteristic polynomial. Then the factors of the minimal polynomial is a subset of the factors in the characteristic polynomial. In fact it is the minimal degree polynomial ( therefore the name, I'd guess ) that fulfills the equation.
Knowing this we can calculate the vectorization of the first few $A^k$ and then solve an equation system where we equal it to the vectorization of the unit matrix. The lowest possible such $k$ that gives 0 error will have the coefficients of our minimal polynomial!
In GNU Octave or matlab this would do:
c = [vec(A),vec(A^2)]\vec(eye(4)); % first try, we know that it needs to be
%  degree >= 2 because otherwise A would be 0 or a multiple of I, which it isn't.

Subsequent trials would correspond to successively adding a new column $\text{vec}(A^k)$ until
 sum(abs([vec(A),vec(A^2)]*c-vec(eye(4))))

or some other error measure becomes sufficiently small with regard to our numerical precision.
Note that we don't need to find any eigenvalues or multiply together stuff or factor anything. Just a few matrix multiplications followed by linear regression.


text:
Q: Aggregate same user events into two different windows I am trying to write a simple pipeline with Apache Beam. Let's say I am taking in user requests that look something like:
(country, user_id, score, timestamp)
I just want to sum up the total score for all users per country, accumulated per minute and 10 minutes. However, there is a caveat that I want to take the latest score per user, per bucket. Meaning, if I have two records:
('USA', 1, 10, 62)
('USA', 1, 4, 64)

and assuming they map to the same minute bucket, I would like to keep the second record (the later one with score of 4).
How do I do this efficiently? Right now, I am taking the user event stream and piping it to two separate branches- one that computes this aggregate per minute and one that computes it per 10 minutes. Clearly, a lot of computation is being doubled here. Ideally, we would be able to re-use the calculations per 1 minute window to add up to the 10 minute window but I can't quite figure out how to do that.
Thanks!

A: It's probably not that big a deal to pipe the elements to two different branches, but yes you can probably do this in a way that avoids duplicating the aggregations.
Assuming that your 10 minute and 1 minute windows can evenly convert to each other (Fixed-time Windows should work fine for this), you can do the following:
Assign 1 min. windows -> Aggregate -> Assign 10 min. windows -> Aggregate
After the first aggregation (likely some type of Combine), the resulting elements should have the latest timestamp from the combined elements (this can be modified by changing the TimestampCombiner). This means that as long as the windows line up evenly when you convert from one to the other, the second aggregation should be aggregating all the same data as your original approach.
For the second part of your question, to keep the latest timestamped element of a window and drop the other elements, you'll want to implement a custom CombineFn that keeps the most recent element. Now in order to actually read the timestamps of the elements from a CombineFn you'll first need to use Reify.timestamps to attach the timestamps to the element. And you'll probably want your CombineFn to output your original element type without the timestamp. So altogether it'll look like this (PCollections in square brackets so you can see the types):
[ElementT] -> Reify.timestamps -> [TimestampedValue<ElementT>] -> Combine -> [ElementT]


text:
Q: postgres detect repeating patterns of zeros Is there a way to detect subseries of zeros of length at least 3 within a time series in Postgres?
year    value
--------------
  1       0
  2       0
  3       0
  4       33
  5       72
  6       0
  7       0
  8       0
  9       0
  10      25
  11      0
  12      56
  13      37

So in this example I'd like to return years 1-3 and 6-9, but not year 11.

A: This one will do it:
WITH d(y,v) AS (VALUES
    (1,0),(2,0),(3,0),(4,33),(5,72),
    (6,0),(7,0),(8,0),(9,0),(10,25),
    (11,0),(12,56),(13,37)
)
SELECT grp, numrange(min(y),max(y),'[]') as ys, count(*) as len
  FROM (
    /* group identifiers via running total */
    SELECT y, v, g, sum(g) OVER (ORDER BY y) grp
      FROM (
        /* group boundaries */
        SELECT y, v, CASE WHEN
                     v IS DISTINCT FROM lag(v) OVER (ORDER BY y) THEN 1
                     END g
          FROM d) s
     WHERE v=0) s
 GROUP BY grp
HAVING count(*) >= 3;


text:
Q: How can thread function call using thread identifier using POSIX threads? I'm new to posix threads. I'm working on a project in which one component upon initialization creates all posix threads. The other component has to request pool manager if there is any thread free. If free, pool manager returns thread handler and the other component handover its data to that thread handler. I've two questions:

*

*Upon initialization, creation of threads means pthread_create() function is called. So, thread executes its routine mentioned in pthread_create() and exit. How can pool manager identify free thread?

*If thread waiting in its routine for its data, then how can other component handover its data to thread using thread handler.

A: Usually you use mutexes and condition variables and some shared memory structure.
For example, you would create an array, a mutex and a condition variable.  Then your worker thread in the pool would:

*

*lock the mutex

*do a wait on the condition variable (mutex gets released automatically for you)

*once wait returns it means cond var got signaled (and mutex is locked again for you)

*remove the piece of work from the array

*unlock the mutex (or go back to (2)

In the client thread which wants to submit jobs to the pool:

*

*lock the mutex

*add work to the array

*signal the condition variable

There are lots of tutorials about this, e.g.
https://computing.llnl.gov/tutorials/pthreads/#ConVarCreation