text: Q: How to convert GenericRecord to a json string corresponding to the schema given in Avro I have a requirement where i need to store the data in json format in AWS S3, we are currently hitting an enpoint which gives List[GenericRecord], and that needs to be stored in Json format, can any one share a sample code for achieving this. I am unable to deserialize GenericRecord to Json string, and even ObjectMapper writeValueAsString method is also not working on it


text:
Q: How to get rid of endl from each Boost.Log line output? I am new to Boost.Log in my c++ program. I create a logger called "simlog" and then I use following line to output my log text:
BOOST_LOG( simlog ) << "some log info";
I don't want the default endl be appended to each of statement like this. I'd rather control whether to add a endl or not myself. How do I do that with Boost.Log? Is there a format setting to turn it on/off?

A: It cannot be done with the out-of-the-box features of Boost.Log. However, you can define a custom sink backend, implement do_consume method and output log message there without trailing \n.
For more information on custom sink backends look here: Writing your own sinks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Activity's onStart() and onResume() methods called twice when start activity from lock screen I create a notification with PendingIntent
Intent intent = new Intent(context, SimpleActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, notifId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Starting the SimpleActivity by clicking on this notification on locked screen causes the next activity's lifecycle: onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onStart() -> onResume() or sometimes onCreate() -> onStart() -> onResume() -> onPause() -> onResume(). But when I start SimpleActivity by clicking on notification from unlocked screen then it works fine.
I found some solution in this comment. But it doesn't works for case when activity has a fragments. I found that in some devices in such case fragments may replicate theirs activity's lifecycle so onStart() also called twice in fragments too.
Is this a normal behavior? And is there a way to avoid this so Activity's lifecycle will look like this onCreate() -> onStart() -> onResume()?


text:
Q: Backing Up and Restoring - Microsoft Store Apps - Windows 10 I pay for internet by the GB now which has really got me into making separate partitions/backups for everything. Last time I started using the Microsoft store, I set it to download new apps to a separate partition, but now when I try to restore it says "This drive has apps from another device. To use this drive, the other apps must first be deleted. (And presumably "re-downloaded")". Does anybody have a way to backup Microsoft Store Apps? I only really use it for games, but those tend to be 10+GB's and I hate re-downloading/installing games each time I reformat Windows (which has been happening a lot latley as I test out Hypervisors).
Is there a way to install Microsoft Store Apps to a separate partition/drive and then re-attach them to a new Windows installation so that it doesn't need to re-download entire game. I'd be fine if it deleted things like "metadata/saves" but kept the core program so that the setup/download was small.


text:
Q: Got 'IndexSizeError' with IE 11/Edge on large images with Openseadragon I am using Openseadragon to display large images, and with some of them I got "SCRIPT5022: IndexSizeError" error message with IE 11 and Edge.
It work with small image (1024 x 656 pixels), but fails with any larger image (2981 x 4123 for example). Any other browser works fine in all cases.
I am using 'legacy-image-pyramid' type source.
My Openseadragon configuration :
viewer = OpenSeadragon({
id:                   'openseadragon',
toolbar:              'viewer-toolbar',
maxZoomLevel:         5,
minZoomLevel:         0,
preload:              true,
sequenceMode:         false,
tileSources:          SOURCE,
crossOriginPolicy:    'Anonymous',
// buttons
zoomInButton:         'zoom-in',
zoomOutButton:        'zoom-out',
showRotationControl:  true,
rotateLeftButton:     'rotate-left',
rotateRightButton:    'rotate-right',
homeButton:           'home',
showFullPageControl:  false,
rotateleftButton:     'rotate-left',
rotaterightButton:    'rotate-right',
// gestures
gestureSettingsMouse:   {
  clickToZoom:        false,
  dblClickToZoom:     true,
  pinchToZoom:        true,
  pinchRotate:        true
},
gestureSettingsTouch: { pinchRotate: true }
});

Source code of larges images (fail) :
var SOURCE = [
    {
      type: 'legacy-image-pyramid',
      levels: [{
        url: 'https://rgw.atolcd.com/swift/v1/sillon_container_test/entrepot/B574636101_Prev36_18930411_0001.jpg',
        height: 4123,
        width: 2981
      }]
    }
];

Source code of smaller image (work) :
var SOURCE = [
    {
      type: 'legacy-image-pyramid',
      levels: [{
        url: 'https://rgw.atolcd.com/swift/v1/sillon_container_test/entrepot/carte1.jpg',
        height: 656,
        width: 1024
      }]
    },
  ];

I found this issue ( https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/16192680/ and IndexSizeError on drawImage on IE and Edge with IE11/Edge (get fixed in recent version of Edge apparently) if drawImage parameters are wrong, but OpenSeadragon's values are good. (and works with small images, so it should work with any image ?).
I tried another source type (image tile source), but same error.
It works if I disable canvas and use img instead (with useCanvas: false in Options), but this is not a solution for me (it breaks my viewer implementation).


text:
Q: MVC 5 get value of CheckBox Checked in controller with Ajax.BeginForm I use MVC 5 and I try to get the value of the checkbox checked in the controller but so far it always return null.
Here is my code:
In View
@using (Ajax.BeginForm("Delete",
                        "User",
                        new AjaxOptions
                        {
                            HttpMethod = "POST",
                            InsertionMode = InsertionMode.Replace,
                            UpdateTargetId = "table",
                            OnSuccess = "Success",
                            OnFailure = "Fail"
                        }))
{
        Add
        <button type="submit">Delete</button>

    @{Html.RenderPartial("_UserTable", Model);

}

My Partial View

            Name
            Email

        @foreach (var item in Model)
        {

                   <input type="checkbox" namespace="userCheck" value="@Html.DisplayFor(modelItem => item.UserName)"/>

                    @Html.DisplayFor(modelItem => item.UserName)

                    @Html.DisplayFor(modelItem => item.Email)

        }

And My Controller
public ActionResult
           Delete(string[] userCheck)
        {
            for (int ix = 0; ix < userCheck.Length; ix++)
            {
                // do something with userCheck[ix]
            }
            return Index();
        }

My button works and go to the Delete Action but userCheck is always null.
How can I get the value of the multiple checkbox?
Thanks


text:
Q: How to convert json file to List using scala I have the following json input
sample.json
[{"level": 1, "firstFile": "one", "secondFile": "first"},
 {"level": 1, "firstFile": "two", "secondFile": "sec"},
 {"level": 2, "firstFile": "three", "secondFile": "third"}]

i want my result should be:
val first= List(List("one","two"),List("three"))
val second= List(List("first","sec"),List("third"))

build.sbt:
name := "Test"
version := "1.0"
scalaVersion := "2.11.0"

libraryDependencies ++= Seq("org.apache.spark" % "spark-sql_2.11" % "2.0.0" % "provided")
libraryDependencies += "com.typesafe" % "config" % "1.2.0"
libraryDependencies ++= Seq("org.slf4j" % "slf4j-api" % "1.7.5",
                            "org.clapper" %% "grizzled-slf4j" % "1.3.1")
libraryDependencies += "ch.qos.logback" % "logback-core" % "1.2.3"
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.3" % "test"
libraryDependencies += "com.databricks" % "spark-avro_2.11" % "4.0.0"
libraryDependencies += "io.circe" %% "circe-config" % "0.4.1"
retrieveManaged := true

A: Usually you convert JSON to case classes using a library like Jackson or Circe.
val json = """[{"level": 1, "firstFile": "one", "secondFile": "first"},
             | {"level": 1, "firstFile": "one", "secondFile": "first"},
             | {"level": 2, "firstFile": "two", "secondFile": "sec"},
             | {"level": 2, "firstFile": "two", "secondFile": "sec"}]""".stripMargin

case class My2FileThing(level: Int, firstFile: String, secondFile: String)

val parsed: List[My2FileThing] = {
  // TODO parse json using some library; there are many available

  List(
    My2FileThing(1, "one", "first"),
    My2FileThing(1, "one", "first"),
    My2FileThing(2, "two", "sec"),
    My2FileThing(2, "two", "sec")
  )
}

The json you provided is a one dimensional List containing four of these items, as above.
To transform that data into the two Lists you asked for, you can do this, I guess. You have not told us the logic behind your transformation.
val firstLineChandraWants: List[List[String]] =
  parsed.map(_.firstFile).groupBy(identity).values.toList
val secondLineChandraWants: List[List[String]] =
  parsed.map(_.secondFile).groupBy(identity).values.toList

A: Use some library for converting the Json String to a Scala object/type.
For more info: How to convert JSON to a type in Scala
Example using Lift:
import net.liftweb.json._
implicit val formats = DefaultFormats // Brings in default date formats etc.
val json = """
[{"level": 1, "firstFile": "one", "secondFile": "first"},
 {"level": 1, "firstFile": "two", "secondFile": "sec"},
 {"level": 2, "firstFile": "three", "secondFile": "third"}]
"""
case class ListSubType(level: Int, firstFile: String, secondFile: String)

val parsed: List[ListSubType] =  parse(json).extract[List[ListSubType]]
val desired: List[List[String]] = parsed.map(a => List(a.firstFile, a.secondFile))

// will produce: List(List("one", "first"), List("two", "sec"), List("three", "third"))

I know you asked different elements(of root list) in different variables, but it's better to use index or iterate over list than using different variables. Practically length of list is indefinite, so how are you gonna assign different items to different variables.
Example=>
/**
* Using index
*/
val first:Option[String] = desired.get(0) // will return Option[String]
val second:Option[String] = desired.get(1) // will return Option[String]

for (items <- desired) {
   println(items)
}

Use this link to get import code for your desired build tool/package manger.
https://search.maven.org/#artifactdetails%7Cnet.liftweb%7Clift-json%7C2.0%7Cjar


text:
Q: .NET: Connecting to MySQL issues I have a .NET app which uses a MySQL database.
The problem is that if I want to run it, the local computer requires the MySQL Connector to be installed.
How could I make this easier ?
Can I "embed" everything and provide in one pack with my app ?
Should I create an installer that does install the connector if missing and automatically creates the data source ?
Which is the best way to go ?
Thanks.

A: I think MySql connector comes with a DLL which just needs to be copied in youir BIN folder to let it go.
Just add the DLL with Setup project and it will copy the DLL while installing your app.


text:
Q: R: ggplot2: change strip.text from "y" axis to "x" axis in faceted plot? For better visualization, I need to move the strip text of the facets to be on top of each facet.
Now they are on the right side, but I need them on top.

This is my code:
tvs.rangos <- ggplot(tvs , aes(rangos))
tvs.rangos + geom_histogram(aes(fill = marca), width = .7) + labs(title = "Marcas de TV por rangos de precios",
                                                                x = "rango de precios", y = "cantidad de tvs")  +
        facet_grid(ecommerce ~ .) +
        scale_fill_brewer(palette="Set3") +
        theme(axis.text.x = element_text(colour="grey10",size=16,hjust=.5,vjust=.5,face="bold"),
              axis.text.y = element_text(colour="grey10",size=18,,hjust=1,vjust=0,face="plain"),
              axis.title.x = element_text(colour="grey40",size=12,angle=0,hjust=.5,vjust=0,face="plain"),
              axis.title.y = element_text(colour="grey40",size=12,angle=90,hjust=.5,vjust=.5,face="plain"),
              plot.title = element_text(size = 16,vjust=2),
              legend.title = element_text(colour="grey40", size=16, face="bold"),
              legend.text = element_text(colour="grey10", size=16, face="bold"),
              strip.text.y = element_text(size = 20, angle = 0))

I've found this topic:
ggplot2: Using gtable to move strip labels to top of panel for facet_grid
But, I'm looking for a simplier approach, if any.

A: if you are looking for alternative, why not simply use facet_wrap(). The text will be on top of each facet. I don't have access to your dataset but here is a simple example
ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width)) + geom_point() + facet_wrap(~Species, nrow=3)


text:
Q: Event handler for close buttom on wordpress gallery I have gallery on wordpress site http://thevastcreative.com/bluebird/update_theme/farm-school/
I need add event handler to close button.
I need close gallery window, when i click on this button.
I use jquery function
but it doesn't work.
Please tell me how correct write event handler for it.
Thanks

A: You are facing scope issue, just don't wrap function inside ready handler callback, which is creating private scope:
{and btw, no need to rebind a new click event on same element, in your code, you are calling myclose function from inline onclick attribute}
function myclose() {
    $("#image_gallery").dialog("close");
}


text:
Q: Get Role Instant Status with Azure Powershell How do I get the Status of a Role Instance in Azure Powershell? I'm using the following command but it's not showing me the Status of the Role
Get-AzureRole -ServiceName serviceNameHere

This is the output:
RoleName             : Role Name
InstanceCount        : 1
DeploymentID         : ***deployment id*******
OSVersion            : ***OSVersion*******
ServiceName          : ***service name*******
OperationDescription : Get-AzureRole
OperationId          : ***operation id*******
OperationStatus      : Succeeded

Anyone can help? Thanks!

A: Figured it out. I used :
Get-AzureRole -ServiceName "serviceNameHere" -Slot "Production" -InstanceDetails | Format-Table -Auto "InstanceName", "InstanceSize", "InstanceStatus"

If anyone runs into this anytime soon.


text:
Q: How to rewrite my url I have my web  page and i want to hide all the contents inside, so the user will not see the page names. it's a php web page hosted on a linux server here is part of the code of my .htaccess file
 Options +FollowSymlinks
 RewriteEngine on
 RewriteRule ''$ Something.php[L]

for example from www.somedomain.com/Something.php i want to look like www.somedomain.com only

A: There are multiple ways. For example, if you want to use a front controller pattern:
# RewriteRule ''$ Something.php[L]
RewriteRule ^(.*)/$ index.php/$1 [L]


text:
Q: How can I strip the version from the output directory of maven-dependency-plugin:unpack? I need to unpack an artifact, and I need to use it's unpacked location in several places (in multiple files).  I don't want to have to update all the copies of that location every time I change versions.  Is there a way I can strip the version from the output directory?  It doesn't look like stripVersion is supported with the unpack mojo.

A: Does the plugin you are using to create the artifact provide a xyzName property?  For example the jar-plugin provides the finalName and the war-plugin has the warName.
If so you can set the property to some fixed value.

A: Try this:
<properties>
    <extracted-artifact-location>${project.build.directory}/extracted-artifact</extracted-artifact-location>
</properties>
...
<build>
    <plugins>
        <plugin>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.3</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId><fixme></groupId>
                                <artifactId><fixme></artifactId>
                                <version><fixme></version>
                                <outputDirectory>${extracted-artifact-location}</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


text:
Q: twin.macro jest test (tw is not defined) When testing react component using jest that is styled with tw.div`` pattern i get an error "Cannot read properties of undefined (reading 'div')". I'm using vite + react + typscript + tailwind + twin.macro
// MyCustomComponent.tsx

import tw from 'twin.macro';

const Container = tw.div`relative w-full`;

export const MyCustomComponent = () => {
  return (
    <Container>
      ...
    </Container>)
}

// MyCustomComponent.test.tsx

import React from 'react';
import { render } from '@testing-library/react';
import { MyCustomComponent } from '../MyCustomComponent';

describe('MyCustomComponent...', () => {
  it('should render', () => {
    render(< MyCustomComponent />);
    ...
  });
});

I tried with this solution but didn't work for me.


text:
Q: When I send someone a file, are the details (Date created / Date modified / Owner / Computer) sent as well (by default)? I have created a file asd.asd:

I want to know when I email this file directly to other people, what kind of information (Date created / Date modified / Owner / Computer) will be exposed.
I am aware that I can "Remove properties and personal information". This question is: even if I do not specifically remove properties and personal information, will they be visible to the second party that downloaded my file?
Also, is there any difference in the details if instead of emailing the file directly, I zipped it up first and email it.
You can download the file at http://qweop.com/asd.zip
(I'm not talking about .txt files, but rather files in general)

A: When emailing a file, only the contents and filename will be seen, and the filename even can be faked by the email program. Since .txt files don't retain any personal information within them that wasn't typed in by the user, the other side will see nothing you don't intend them to if the file is attached directly. When placed in an archive, it is possible for the archive program itself to provide additional metadata about the file within the archive.

A: As mentioned in Ignacio's answer, email only contains the contents of the file. But archives are different. This is the result of unzip -ql asd.zip (which lists the file contents).
  Length      Date    Time    Name
---------  ---------- -----   ----
       23  2011-07-12 14:10   asd.txt
---------                     -------
       23                     1 file

The time I guess matches with the modified date.

A: Both of the previous answers are wrong, at least regarding to Date created and Date modified, see this example extracted from a real email message source:
--_017_HE1 ...id removed... p_
Content-Type: application/json; name="options.json"
Content-Description: options.json
Content-Disposition: attachment; filename="options.json"; size=123;
        creation-date="Thu, 28 Nov 2019 12:25:05 GMT";
        modification-date="Thu, 28 Nov 2019 13:49:47 GMT"
Content-ID: <F629B ...id removed... AA57@eurprd07.prod.outlook.com>
Content-Transfer-Encoding: base64

eyJqdW ... rest of base64 file contents removed

It depends on the email client, especially the one used to send the message (it has to add the creation-date and modification-date fields) and also the one used to read the message (it has to read those fields and display them or use them in some way). Many clients don't store this field, but at least one does (Microsoft Outlook).
Of course the sending client may fake the dates or the system date could be wrong, but it's usually quite reliable.


text:
Q: Get notified only when Platform Balance Updates in Stripe - WebHook I need to get notified when the Balance Updates in my Stripe Platform Account. I currently use the below WebHook.
switch (event.type) {
    case 'balance.available':
        const paymentIntent = event.data.object;
        console.log(paymentIntent);
        transfer("acct_1Jc63wPhWrt3Vrlk");
        console.log('End');
        break;
}

Question
I am working with few Connected Express Accounts and I still get notified when the Balance Updates in Connected Accounts as well.
Exact Issue: I transfer money from my Platform Acc to Connected Express Acc. I do get 2 notifications at the moment

1st Notification: Deduction from Platform Acc Balance

2nd Notification: Addition to Connected Acc Balance

I want to skip the 2nd Notification and get only notified when an update happens to the Platform Acc balance.
Is there a way to achieve this?
Thank you

A: There are 2 types of webhook endpoints at Stripe: Account webhooks and Connect webhooks.
Account webhooks send you any events that happen on your Stripe account.
Connect webhooks send you events for any events that happen on Connect accounts.
You should register an Account webhook endpoint and remove your Connect webhook endpoint in that case (or disable the balance.available event on your Connect webhook endpoint).


text:
Q: vtiger customer portal php 5.4 patch When i migrate to php version in my server . the vtiger customer portal not working current version of php is version 5.3.2 . in this version vtiger 6 working fine .
Is that any patch available for download for vtiger customer portal php 5.4 patch .
i an add .htaccess file like that in customer portal
  # Use PHP 5.3
AddHandler application/x-httpd-php-5.3 .php

But the index.php file open in browser what is in that file.

A: AFAIK there is no current vTiger v6.0 patch for PHP5.4.x. There is however a (3rd party) patch for vTiger v5.4.0 which will allow it to run on PHP5.4+. Have a look here: https://forums.vtiger.com/viewtopic.php?f=139&t=54593&start=10#p172298
I have also read that vTiger v6.1 will support PHP5.4+ but we'll have to wait and see...


text:
Q: $D^{n}$ with all but one edge identified with a point is homeomorphic to $D^{n}$. Let us denote $D=[0,1]^{n}$ and let $A=\bigg\{(x_{1},...,x_{n})\in D^{n}\,,\exists i\,,s.t\,,1<i\leq n\, ,x_{i}\in\{0,1\}\bigg\}\cup\bigg\{\{1\}\times[0,1]^{n-1}\bigg\}$. Then I want to prove that $D/\sim$ with $A$ identified to a point is homeomorphic to $D$ .
I am having trouble as to produce an explicit homeomorphism(or even a continuous surjection from $D^{n}$ to itself which identifies $A$ with a point and makes $\{0\}\times[0,1]^{n-1}$ the boundary of $D^{n}$ .
In terms of CW complexes , I can say that the space consists of a single $0$-cell with the $n-1$-cell $D^{n-1}$ attached to it by the constant map(So that it is homeomorphic to $S^{n-1}$) . And then we attach the $n$-cell $D^{n}$  with the boundary $S^{n-1}$ being attached to $S^{n-1}$ of the $n-1$ skeleton by the identity map. So it is homeomorphic to $D^{n}\cong D$ .
I tried to do it for the $n=2$ case by mapping $\{0\}\times[0,1]$ to the boundary of $S^{1}$ by $(0,x)\mapsto e^{2i\pi x}$  and $\bigg\{\{1\}\times[0,1]\bigg\}\cup\bigg\{[0,1]\times\{0\}\bigg\}\cup\bigg\{[0,1]\times\{1\}\bigg\}$ to the point $(1,0)$ . Now this map $p:\partial(D)\to D^{2}$ is such that $p_{*}$ is the trivial homomorphism so it extends continuously to a map $p:D\to D^{2}$ but how do I tell if it is surjective or anything else?
I have also considered by transforming the square to a hemisphere with boundary(lower) such that the boundary represents . (in the case of D^{2}, I want $[-1,1]$ represent the lower boundary which we will identify with the three edges of the square) . After that I want to draw lines from a point say $p=(0,0,...,0,-2)$ to the (upper) boundary and extend this line to meet $p$ and then use the universal property of the quotient to identify the lower boundary with the point $(0,0,...,0-2)$ to get a bijection which will be a homeomorphism because our space is compact , hausdorff and so is the target.
Here is a picture which will perhaps explain a bit more on what I was trying to do:-

But as I said, even in this case the explicit map is very complicated and does not allow us to readily view continuity or bijectivity. It's all in terms of lines which depend on the end point. I want to see an explicit map which would help me in constructing these in the future. Most books do not provide explicit maps and say in words however for an initial course in topology and algebraic topology, these things help us to see what's happening more explicitly.
Why I need this: I am trying to show that for $n\geq 2$ every cts $f:S^{n}\to X$ extends to a cts map $F:D^{n+1}\to X$ iff $\Pi_{n}(X,x_{0})$ is trivial. Where $X$ is a path connected space.
To prove the converse I will need the above result.

A: I believe that these figures show a continuous map from $D^2$ to $D^2$ which maps all
border in the "Source" except $(0,1)\times\{0\}$ (largest $\Pi$-shaped line in the "Source" figure) to the single point
$(1/2, 1)$ (blue dot in the "Target" figure), while being a one-to-one homeomorphism in
the rest of $D^2$, where each line in the "Source" figure maps to a line of the same color in the "Target".

A: Let $x \in S^{n-1}$. As you've said, what you want to prove is equivalent to proving that identifying a closed subset, A, of $S^{n-1}$, viewed of the boundary of $D$ leads to a homeomorphism
$$
D / A \sim D.
$$
To avoid messing around with complicated coordinates, we can look locally around the part of the boundary that is being identified, and construct an explicit map there. Then you can construct a homeomorphism by patching together this map with the identity on the rest of the sphere. Locally the boundary looks like
$$
\mathbb R^{n}_+ = \{(x_1, \dots, x_n)\ |\  x_1 \geq 0\}.
$$
and we can assume that $A = \{0\} \times D^{n-1} \subseteq \mathbb R^n_+$ by shrinking $A$, similar to making $A$ a hemisphere but continuing to shrink it into a neighborhood of the south pole, say. Now we're in good shape because the task is to prove that there is a homeomorphism
$$
\varphi : \mathbb R^n_+ \to \mathbb R^n_+/A
$$
and we can write out an explicit map. To do this consider the homotopy
$$
H_t(x_2, \dots x_n) = \begin{cases}
\frac{t}{t + 1}x &\text{If } x \in D^{n-1} \\
\frac{1}{\|x\|}\left(\frac{t}{t+1} + \|x\| - 1\right)x &\text{Otherwise}
\end{cases}
$$
that shrinks $D^{n-1}$ to the identity. Then we let $\varphi : \mathbb R^n_+ \to \mathbb R^n_+ / A$ be such that
$$
\varphi : (x_1, \dots, x_n) \mapsto [(x_1, H_{x_1}(x_2, \dots, x_n))].
$$
This is a homeomorphism since for each $t \neq 0$, $H_t$ is a homeomorphism and $H_t$ varies continuously with $t$, and this has the required properties on the boundary $t = 0$ by construction.
For large $x$, $\varphi(x)\sim x$ and so we can construct a homeomorphism of $D^n$ by picking a neighborhood $U$ of the south pole and a homeomorphism
$$
U \to \mathbb R_n^+.
$$
and then shrink/move $A$ to be such that the image of $A$ under this homeomorphism is as we assumed. Then define the homeomorphism on $U$ to be $\varphi$ and just the identity on the rest of the disk.


text:
Q: 3 variables and conditional probability Following a previous question, lets say we now have 3 variables:
$L$, $B$, $S$:
     S
   /   \
  L     B

So
$L$ depends on $S$
$B$ depends on $S$
$P(S) =$ 0.5
$P( \lnot S) =$ 0.5
$L$ that depends on $S$:
$P(L|S) =$ 0.10
$P( \lnot L|S) =$ 0.90
$P(L| \lnot S) =$ 0.01
$P( \lnot L| \lnot S) =$ 0.99
$B$ that depends on $S$:
$P(B|S) =$ 0.60
$P( \lnot B|S) =$ 0.40
$P(B| \lnot S) =$ 0.30
$P( \lnot B| \lnot S) =$ 0.70
I have gotten
$P(L) =$ 0.055    $P(\lnot L) =$ 0.945
$P(B) =$ 0.45     $P(\lnot B) =$ 0.55
As the previos question to get
$P(S)$ after I observe that $P(L)=1$
$P(S∣L)=  P(L∣S)P(S)  / P(L) =$ (0.10)(0.5)  / (0.055)  = 0.9091
so
$P(S)=$ 0.9091
Similarly when we have $P(B)=$1
$P(S∣B)=  P(B∣S)P(S)  / P(B) =$ (0.40)(0.5)  / (0.45)  = 0.3636
so
$P(S)=$ 0.3636
But What do you do when you observe both events:
$P(L)=$1  and
$P(B)=$1
How do you modify the above formula to get $P(S)$?

A: At first we don't know the outcomes of $L$ and $B$:
$$P_{prior} = \begin{matrix}
P_{prior}(S \land       L \land       B) & P_{prior}(\lnot S \land       L \land       B) \\
P_{prior}(S \land       L \land \lnot B) & P_{prior}(\lnot S \land       L \land \lnot B) \\
P_{prior}(S \land \lnot L \land       B) & P_{prior}(\lnot S \land \lnot L \land       B) \\
P_{prior}(S \land \lnot L \land \lnot B) & P_{prior}(\lnot S \land \lnot L \land \lnot B)
\end{matrix}$$
$$ = \begin{matrix}
0.5 \cdot 0.1 \cdot 0.6 & 0.5 \cdot 0.01 \cdot 0.3 \\
0.5 \cdot 0.1 \cdot 0.4 & 0.5 \cdot 0.01 \cdot 0.7 \\
0.5 \cdot 0.9 \cdot 0.6 & 0.5 \cdot 0.99 \cdot 0.3 \\
0.5 \cdot 0.9 \cdot 0.4 & 0.5 \cdot 0.99 \cdot 0.7 \\
\end{matrix}$$
We then observe L and B.
$$P_{posterior} = \begin{matrix}
0.5 \cdot 0.1 \cdot 0.6 & 0.5 \cdot 0.01 \cdot 0.3 \\
0 & 0 \\
0 & 0 \\
0 & 0 \\
\end{matrix} \cdot \frac{1}{0.5 \cdot 0.1 \cdot 0.6 + 0.5 \cdot 0.01 \cdot 0.3}$$
$$ = \begin{matrix}
20/21 & 1/21 \\
0 & 0 \\
0 & 0 \\
0 & 0 \\
\end{matrix}$$
$$P_{posterior}(S) = \frac{P_{prior}(S \land       L \land       B)}{P_{prior}(S \land       L \land       B) + P_{prior}(\lnot S \land       L \land       B)} = 20/21 \approx 0.95$$


text:
Q: Problems installing CPAN Modules i'm having loads of problem in trying to install CPAN Modules. Using the cpan.exe, I try to install a module with, for example, "install Win32::IE::Mecahnize" but I end up hitting a wall. In the beginning it find dmake.EXE and is okay, but when the install finishes it says dmake.exe is NOT OK, and Dmake.exe Error code 255 , while making 'test-dynamic'.
I'm very confused as to what is happening and why its not working?? Help is much appreciated.
This is the current error I get:
dmake.EXE: Error code 255, while making 'test_dynamic'
C:\strawberry\c\bin\dmake.EXE test -- NOT OK
Running make install
  make test had returned bad status, won't install without force
ABELTJE/Win32-IE-Mechanize-0.009.tar.gz     : make_text NO

A: It's not your fault. That module doesn't work for anyone. When you run into a failure with a module, investigate it to see if other people are having problems. You can look on its CPAN Search page to see that there are no passing testers reports for that distribution. That distribution should not install without force. We cover some of this in Effective Perl Programming's section on researching modules.
Can you install other modules without a problem?

A:
ya, well here's the thing, I have both ActivePerl and Strawberry Perl installed, is that a problem?

Shouldn't be an issue. However, you need to make sure that Strawberry Perl's distro contains the binaries and libraries you need to build and install non-text only modules. You need to make sure you're using Strawberry Perl's stuff and not ActivePerl. I recommend putting Strawberry Perl in your PATH, but not ActivePerl.
Easiest thing to do is not use CPAN, but ActivePerl's own PPM manager. ActivePerl has probably prebuilt about 90% of the CPAN modules and have them available via their PPM manager. Try that.


text:
Q: How to customize boostrap3 colum to 70px width I try, to customize boostrap colum to 70px width.
Now, i have col-lg-1 column 64.984px width, i need 70px.
How to do that in Boostrap 3. I use standart 1170 container.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

I am 64px width block

A: You can set width manually as follows:

A: If you want that whenever you will call col-xl-1 the width will be 70% then go to bootstrap.css file. Search for col-xl-1 & change
.col-xl-1 {
  width: 64.984px%;
}

to
.col-xl-1 {
  width: 70%;
}

A: Bootstrap's grid its based on flexbox. All you need to do is add custom class and set flex-basis attribute.

.custom {
  flex-basis: 70px;
}

I am 64px width block


text:
Q: "Problems" window shows fake errors Eclipse CDT is showing strange errors in my editor/problems windows. For example, for a line like:
#include <string>

it says: Unresolved inclusion: <string>, as if Eclipse couldn't find such a basic include file. Of course because of those include errors, almost no definition is recognized later, resulting in even more errors. This is despite that the project builds correctly from Eclipse.
This is an autotools-based source. The project was set to custom Makefile mode. I use Debian, Eclipse 3.7.
How to get rid of those fake errors?

A: I have seen eclipse have issues like this occasionally in the past. For me, it was a project with a few header files, but no actual compile-able items. It would correctly detect errors when building projects that referenced it, but would fail to get rid of the errors once they were fixed.
You can start by deleting the particular errors/warnings manually in the problem window and see if they stay away.


text:
Q: Using Python to gather attributes I have a shapefile that has been drawn to encompass certain points in another layer.  I can use the intersection feature to gather all the data from the points layer, for points that lie in this polygon I have drawn.  However, I need to be able to export this to CSV.
How can I write a Python script that will pull all the points data that lie within this polygon.
points layer = ("xyz")
polygon layer = ("abc")

I am looking to have all the data from the points layer that are within my polygon layer.

A: You could simply use Select Features by Polygon (click the small arrow on the right of the selection button) and then, using Save Selected Features As from the layers panel, export the selection as a CSV file.
Links are to screenshots.


text:
Q: AS3 Sprite Button Depth Not Working I am having trouble getting the sprite button to display in the proper depth. I suspect it may have something to do with my Loader objects but can't find a solution. When I trace the depth it is correct index of 3 but still shows up on index 0. Code between "Close Video Start and Close Video End comments Thank You.
import flash.display.Loader;
import flash.events.Event;
import flash.display.MovieClip;

import flash.utils.Timer;
import flash.events.TimerEvent;

import flash.display.Shape;
import flash.display.Sprite;

//----------------------------------- 300x250 Start ---------------------------------\\

//SWF Load and URL Request
var myLoader:Loader = new Loader();
var url:URLRequest = new URLRequest("_/media/300x250.swf");

//Function for Replay
function loadSWF():void {
//Add URL to Load Object
myLoader.load(url);
//Index 0
addChild(myLoader);
//Loader Cordinates
myLoader.x = 803;
myLoader.y = 331;
}

// Mask for Load Object 300x250
var maskSWF:Shape = new Shape();
maskSWF.graphics.lineStyle();
maskSWF.graphics.beginFill(0x0);
maskSWF.graphics.drawRect(803, 331, 300, 250);
maskSWF.graphics.endFill();
this.addChild(maskSWF);

myLoader.mask = maskSWF;

//----------------------------------- 300x250 End ---------------------------------\\

//----------------------------------- Video Start ---------------------------------\\

//Video Player Load and URL Request
var myLoaderVidPlay:Loader = new Loader();
var urlVidPlay:URLRequest = new URLRequest("_/media/vid_player.swf");

//Timer Function to Play Video Player UI
function timerListenerVidPlay (e:TimerEvent):void{
//Add URL to Load Object
myLoaderVidPlay.load(urlVidPlay);
//Index 1
addChild(myLoaderVidPlay);

//Loader Cordinates
myLoaderVidPlay.x = 803;
myLoaderVidPlay.y = 331;
}

//New Timer Object Video Background
var myTimerVidPlay:Timer = new Timer(1400,1);
myTimerVidPlay.addEventListener(TimerEvent.TIMER, timerListenerVidPlay);

//Creating NetConnection object - Set to null when local folder
var nc:NetConnection = new NetConnection();
nc.connect(null);

//New NetStream
var ns:NetStream = new NetStream(nc);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
function asyncErrorHandler(event:AsyncErrorEvent):void
{
    // ignore error
}

//New Video Object
var vid:Video = new Video();

//Timer Function to Play Vid
function timerListenerVid (e:TimerEvent):void{
//Index 2
ns.play("./_/media/vid.flv");
vid.attachNetStream(ns);
addChild(vid);
vid.x = 818;
vid.y = 345;
vid.width = 271;
vid.height = 153;
}

//New Timer Object Video
var myTimerVid:Timer = new Timer(1500,1);
myTimerVid.addEventListener(TimerEvent.TIMER, timerListenerVid);

//------------------------------------ Video End ---------------------------------\\

//----------------------------------- Replay Start ---------------------------------\\

//Removes and Reloads SWFs for Replay
replay.addEventListener(MouseEvent.CLICK, replayClickHandler);

//Replay Advertisement
function replayClickHandler(event:MouseEvent):void
{
    myLoader.unload();
    myLoaderVidPlay.unload();
    myTimerVidPlay.stop();
    //Closes Video Stream
    ns.close();

    loadSWF();
    myTimerVidPlay.start();
    myTimerVid.start();
}

//----------------------------------- Replay End ---------------------------------\\

//----------------------------------- Close Video Start ---------------------------------\\

var closeVid:Sprite = new Sprite();
closeVid.graphics.beginFill(0xFF0000, .5);
closeVid.graphics.drawRect(703, 331, 300,250);
closeVid.graphics.endFill();
//Index 3
addChild(closeVid);
//trace(getChildIndex(this.closeVid));

//Adds hand cursor
closeVid.useHandCursor = true;
closeVid.buttonMode = true;

closeVid.addEventListener(MouseEvent.CLICK, myClickCloseVid);

function myClickCloseVid (e:MouseEvent):void{
    myTimerVidPlay.stop();
    myLoaderVidPlay.unload();
    //Closes Video Stream
    ns.close();
    removeChild(vid);
}

//----------------------------------- Close Video End ---------------------------------\\

//Start Functions
loadSWF();
myTimerVid.start();
myTimerVidPlay.start();

A: well you are calling addChild(closeVid); before calling addChild(myLoader);
call addChild(closeVid); after calling loadSWF(); which calls addChild(myLoader);
That was solution to your problem.
Now, loadSWF? what kind of name it is? it is misleading and later (month, year) you will need to inspect the body of function ti find out what it does.
addChild in the function is also a bad idea - why? well it is root of your problem:) and this function does more than adding a child to a display list which should be kept separate.


text:
Q: BASH script reading variable from another .txt file I have output.txt file, where my script is storing some outputs, I just need to get the output of ID which is in the 1st line of the output.txt in myscript.sh file, can someone suggest a way to do that
{"id":"**dad04f6d-4e06-4420-b0bc-cb2dcfee2dcf**","name":"new","url":"https://dev.azure.com/vishalmishra2424/82c93136-470c-4be0-b6da-a8234f49a695/_apis/git/repositories/dad04f6d-4e06-4420-b0bc-cb2dcfee2dcf","project":{"id":"82c93136-470c-4be0-b6da-a8234f49a695","name":"vishalmishra","url":"https://dev.azure.com/vishalmishra2424/_apis/projects/82c93136-470c-4be0-b6da-a8234f49a695","state":"wellFormed","revision":12,"visibility":"public","lastUpdateTime":"2021-04-22T14:24:47.2Z"},"size":0,"remoteUrl":"https://vishalmishra2424@dev.azure.com/vishalmishra2424/vishalmishra/_git/new","sshUrl":"git@ssh.dev.azure.com:v3/vishalmishra2424/vishalmishra/new","webUrl":"https://dev.azure.com/vishalmishra2424/vishalmishra/_git/new","isDisabled":false}

A: The snippet you posted looks like
JSON and a utility named file
which can guess different types of file says that too:
$ file output.txt
output.txt: JSON data

You should use JSON-aware tools to extract value of id, for example
jq:
$ jq -r '.id' output.txt
**dad04f6d-4e06-4420-b0bc-cb2dcfee2dcf**

or jshon:
$ jshon -e id < output.txt
"**dad04f6d-4e06-4420-b0bc-cb2dcfee2dcf**"


text:
Q: Deploying laravel 8 app on shared hosting folder structure How can I deploy laravel 8 application via git access with new folder structure on shared hosting for laravel 8 applications? (hostinger)
As I know for laravel 8 you need to separate project folder and public folder to public_html for example. I'm not sure why structure have to be like this, older versions were deployed with whole application to public_html folder.
My question is how can I deploy application with this structure when I deploy my github repository? In my github repo structure is not same as I need on shared hosting?


text:
Q: Emulate Bluetooth LE Adapter for Acceptance Testing I'm developing an Android app that captures Bluetooth LE signals and I'm a big fan of test driven and behaviour driven development. So, I want to develop my app by using TDD and BDD. When it comes to TDD it is no problem to test the bluetooth part with Robolectric. But, when I want to write my behaviour driven tests, I can not test bluetooth because the android emulator does not support bluetooth in any way (see here).
So, I thought it must be possible to simulate a Bluetooth LE device in software which forwards simulated Bluetooth broadcast packages to an Android X86 running in a virtual machine.
Do you have any pointers to implement that? I'm thinking about a small user space program which receives simulated Bluetooth signals from my BDD framework over TCP and then forwards those signals to the simulated device. Then the device forwards them to the Android X86 VM and the Android app catches and processes the signals.
This post seemed promising but did not work. Qemu can emulate Bluetooth hardware but it supports only Bluetooth keyboard.
I don't want to use any hardware because our CI system runs in a docker container on a server. I do not have any access to the server.


text:
Q: Why does my SSML not work on Alexa Devices? I am making an extremely simple skill to test out Alexa's SSML capabilities. For simplicity's sake I am building the whole thing in Alexa's online Developer Portal. Here is the LaunchRequest I have in my index.js:
const LaunchRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
    },
    handle(handlerInput) {
       var speechOutput = '<prosody pitch="low">Hello.</prosody>';
        return handlerInput.responseBuilder
            .speak(speechOutput)
            .reprompt(speechOutput)
            .getResponse();
    }
};

When I go to the Test Page of the Developer Console and run my skill it performs exactly as it should, with Alexa saying "Hello" in a low voice. But when I try to launch the same skill from any of my Echo devices she tells me "Sorry, I'm having trouble. Please try it in a little while."
I have other skills that don't use SSML and they work just fine on all my devices, so what's going on in this case?

A: When Alexa responds with "Sorry, I'm having trouble. Please try it in a little while." it usually means it's not even getting to the skill for one of multiple reasons, it's therefore unlikely to be related to SSML.
This often is a problem with internet or the device acting up (try checking for updates), restarting it usually solves this issue for me.
Are you logged in with the same developer account on your devices as the one you created the skill on?
If not, the devices won't be able to see your skill (as it's not live yet) when you call it from a different account. Another option is to add your echo device's account as a beta tester on your developer account under distribution.
Another reason could be that Alexa is not understanding what you're saying (either pronunciation issue or ambiguous skill name).
To check what Alexa is hearing when you speak, you can view your utterance history, listen to what you said and read how Alexa interpreted it and the action taken.
You can view that here (change .com to whatever you're using): https://alexa.amazon.com/spa/index.html#settings/dialogs

A: This behavior work well on my devices.
What I did >

*

*Create a new custom Alexa Skill Hosted (local en-US)

*Set the invocation name to : "test one"

*Update the speak output from

const speakOutput = 'Welcome, you can say Hello or Help. Which would you like to try?';

to:
const speakOutput = '<prosody pitch="low">Welcome, you can say Hello or Help. Which would you like to try?</prosody>';

Then I tested on the developer console: OK.
Then I tested on Echo Dot 4: OK
Now you need to debug what is wrong:

*

*Go to the log on cloudwatch (if it is not on the default region, try the other one)

*

*Then go inside your latest log

You should be able to see what went wrong here.
If not, provide detail about your skill (local, logs, ...) & which device you've used to test.


text:
Q: Comparing timestamps and working with timezones on iOS Given a unix timestamp, how can my iOS code know if it is before or after 6am (6am = the most recent 6am that occurred)? Are there time zones involved?

A: Convert the unix timestamp to a Date. Then use Calendar to get the DateComponents from the Date. By default, these components will be interpreted in the user's current timezone. If you wish to interpret the date in a different timezone, set the calendar's timezone before getting the components from the date.
By looking at the desired components you can make your decision about the hour.
let date = Date(timeIntervalSince1970: someUnixTimeStamp)
let components = Calendar.current.dateComponents(in: TimeZone.current, from: date)
// look at hour as needed

There are other Calendar APIs if you just want a single component or just a smaller subset of components instead of all components from the date.


text:
Q: grep -v '.*' not working This entirely useless command excludes everything piped to grep, as expected:
$ man man | grep -v '.*'
$

How am I getting output from piping bind -p to this?
$ bind -p | grep -v '.*'
"?": self-insert
"?": self-insert
"?": self-insert
"?": self-insert
"?": self-insert
(227 more...)

The exit code is 0 and there is nothing written to stderr.

A: On my machine, your "?" is actually "�". That's the UNICODE character used as a fallback when decoding fails.
It looks like bind -p outputs invalid UTF-8 sequences, and grep -v '.*' does not filter them because it cannot decode them in the first place.


text:
Q: Is there a way to guarantee that internet explorer will alway be the topmost window? I'm trying to force an internet explorer window to be TOPMOST. No other windows should show on top of the internet explorer window. I have to use internet explorer. I'm also running this in Windows 7. Apparently that makes a difference but all the information I found on that is rather vague and basically consists of people shouting "why isn't this easier!".  This is my code:
HWND ieWin = FindWindow(TEXT("IEFrame"), 0);
SetFocus(ieWin);
SetWindowPos(ieWin, HWND_TOPMOST, 0, 0, 100, 100, SWP_SHOWWINDOW );
UpdateWindow(GetParent(ieWin));

This is running in a loop so I can force the window to have these settings continuously but it's not helping. Sometimes the above code works and sometimes it doesn't.

A: No. What if two programs did this?.

A: After much discussion I did wind up forcing the window to stay on top using a loop. If anyone else really needs to do this in the future they really need to make sure they are following the steps below.
1) Ensure that they will have absolute control over the windows that their user can open. In my case The user will only be able to open my program and internet explorer.
2) The first time you set the IE window to show set it to the foreground.
3) While looping to set the window to TOP_MOST do NOT set the focus to the IE window.
4) Make sure you have SWP_SHOWWINDOW, SWP_NOSIZE, and SWP_NOMOVE. Otherwise that loop will change your window's size and place at every iteration.
And if you can avoid it at all possible, don't ever do this at all :P


text:
Q: Places Api stopped working in android I integrated Places API in my android project and it was working fine from past few months but suddenly it is giving me the following exception :-
This IP, site or mobile application is not authorized to use this API key. Request received from IP address 175.176.186.118, with empty referer
Please help me know what is the issue and how can i solve it.
I am using my Api key for getting the places response. It was working with my API key. I read on stack overflow that you need server key for this but i am unable to find any option for creating a server key.
Any help will be apreciated, Thank you.

A: Include a referrer in your network request.
Example: HTTP header "Referer:anmol.com"

A: Check your API Restrictions for your specific project in the Google API console. You can find it by navigating to your project on the console. Select credentials in the left tab and then select the "API restrictions" tab next to "Application restrictions" near the bottom of the page. From their, click the "Select API" drop down box and select Places SDK for Android. Or you can delete all the api restrictions to have no restrictions. Also check your application restrictions to restrict it to android apps if you're not using servers to make the request. Here is a question I answered a few weeks ago on how to set that up.


text:
Q: how to set an X-Forwarded-For in http request in PyQt4 I would like to know how can I add X-Forwarded-For paramet to my header.
for example if I want to change user-uagent in my application, I would do some thing like this:
class MyBrowser(QWebPage):
    ''' Settings for the browser.'''

    def __init__(self):
        QWebPage.__init__(self)

    def userAgentForUrl(self, url):
        ''' Returns a User Agent that will be seen by the website. '''
        return "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15"

and than I would do something like:
class Browser(QWebView):
    def __init__(self, user_info):
        QWebView.__init__(self)
        self.setPage(MyBrowser())

A: QWebView has void QWebView::load ( const QNetworkRequest & request, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, const QByteArray & body = QByteArray() ). You can set any header on QNetworkRequest with void QNetworkRequest::setRawHeader ( const QByteArray & headerName, const QByteArray & headerValue )
I'm not python developer but in C++ it would be something like this:
QWebView * view = new QWebView;
QNetworkRequest req(QUrl("http://www.google.pl"));
req.setRawHeader("X-Forwarded-For", "MyData");
req.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15");
view->load(req); // will perform get operation by default
view->show();


text:
Q: Is there a Mushroom collector in Paldea? An Item Maniac is a person who will purchase certain items from the player at a higher price than what they would be sold for, like in 5th generation games. I own several valuable items and I want to sell them at the best price.
The description for the Big Mushroom suggests it:

It's extremely popular with a certain class of collectors.

Is there a Mushroom collector in Paldea?

A: Unfortunately, the Mushroom Collector is missing from Pokemon Scarlet/Violet.
You cannot sell the Mushrooms in the game to a Mushroom Collector, because the game does not have Item Maniacs like the previous titles that buy the items for high prices.
You can head over to a Pokemart and sell the mushrooms there, at a lower price.


text:
Q: Why "silver-tongued" for someone who is convincing? I understand that "silver-tongued" or "silver-tongued devil" means to be a good orator, or:

able to speak in a way that makes other people do or believe what you want them to do or believe
  Merriam Webster

My question is: why silver?
This question on quora goes into detail about where & when the phrase appears to originate from.
But why would silver be chosen as the adjective to describe someone's tongue?
I'm making the assumption that it means the valuable metal silver and not simply the color, but would gold not have been more apt, as it is worth more? Or why not jewel encrusted tongue?
It just seems rather arbitrary to choose a valuable metal, but not the most valuable, to describe someone with a tongue that is valuable. I was wondering if there is any evidence of a deeper or more substantial meaning as to the original choice.

A: It does not refer to the value but to  the "sound" produced by silver objects:

*

*Of voices, words, etc., from 1520s in reference to the metal's pleasing resonance; silver-tongued is from 1590s.

Etymonline

A: Silver tongue is a phrase used in the Bible. Proverbs, 10:20, King James Version

The tongue of the just is as choice silver: the heart of the wicked is
  little worth.

The OP asks: but would gold not have been more apt, as it is worth more?
Golden-tongued has been used, the most famous examples that of a 4th century saint and a 19th century U.S. politician.
Golden tongued, or, more exactly, golden-mouthed was appended to the name of St. John, Archbishop of Constantinople.  See Wikipedia, John Chrysostom

John Chrysostom ..... c. 349 – 407,... Archbishop of Constantinople, was an
  important Early Church Father. He is known for his preaching and
  public speaking, his denunciation of abuse of authority .. by both
  ecclesiastical and political leaders, the Divine Liturgy of St. John
  Chrysostom, and his ascetic sensibilities. The epithet Χρυσόστομος
  (Chrysostomos, anglicized as Chrysostom) means "golden-mouthed" in
  Greek and denotes his celebrated eloquence.  (Emphasis added.)

See also William Jennings Bryan: Golden-Tongued Orator by Robert A. Allen, Peggy Trabalka (Illustrator).  (WJB, 1860 to 1925.)

Describes the life of the lawyer, orator, and politician who ran
  unsuccessfully for the Presidency three times.

As for silver- vs gold-tongued: @ Mick says in his comment

The finest musical instruments were originally made of silver.

But that pushes the OP's question to: why were the finest musical instruments  made of silver and not gold?  It may be simply because gold is so much more expensive than silver, and thus gold instruments were exceedingly rare.
@JOSH said in his answer that silver has a pleasing resonance, but gold musical instruments also have a fine tone, as the following reference on gold flutes discusses.
A flute can be made of even 24K gold. From The Flute Center of New York

Most flutes made of gold or platinum have a silver mechanism, but for
  those willing to go the extra mile, we have flutes with gold mechanism
  as well. The added weight of a gold mechanism will certainly affect a
  flute's resistance, its weight, and its price! While 14K gold is most
  common, many flute makes use other alloys, like 9K, 10K, 18K, 19.5K or
  even 24K because of the unique tonal characteristics of each alloy.

The ultimate is a platinum flute (See, e.g., Altus Platinum flute)
, but platinum was not known in ancient times, and, because of its very high melting point, probably could not have been worked.  so platinum-tongued never became established.
If the OP wants to pursue the dominance of silver musical instruments over gold musical intruments, https://musicfans.stackexchange.com/ or https://music.stackexchange.com/ may be a better place to ask.

A: "Speech is silver, silence gold". Unable to recall when first I heard this but have always understood that choosing to be silent is more valuable than speech.

A: I always thought that "silver-tongued" referred not to silver, but to mercury, or quicksilver.


text:
Q: Microsoft Band 2 + UWP + Background Task => An error occurred while attempting to acquire the Bluetooth device service I'm writing a Windows 10 UWP app on my Surface Pro 3 which is connected to my Microsoft Band 2 and I can connect to it just fine when I'm running the app in the foreground.
But now I'm trying to use the DeviceUseTrigger and run some logic in a background task. When I call the method to connect to the band:
var bandInfo = (await BandClientManager.Instance.GetPairedBandsAsync()).FirstOrDefault();
var bandClient = await BandClientManager.Instance.ConnectAsync(bandInfo);

I get the following error:

An error occurred while attempting to acquire the Bluetooth device
  service. This error can occur if the paired device is unreachable or
  has become unpaired from the current host.

I added the following capabilities to my UWP appxmanifest:
<DeviceCapability Name="bluetooth" />
<DeviceCapability Name="location" />
<DeviceCapability Name="proximity" />
<DeviceCapability Name="bluetooth.rfcomm">
   <Device Id="any">
     <Function Type="serviceId:A502CA9A-2BA5-413C-A4E0-13804E47B38F" />
     <Function Type="serviceId:C742E1A2-6320-5ABC-9643-D206C677E580" />
   </Device>
</DeviceCapability>

And this is my declaration of the background task:
<Extensions>
  <Extension Category="windows.backgroundTasks" EntryPoint="WindowsRuntimeComponent1.BandBackgroundTask">
     <BackgroundTasks>
        <Task Type="deviceUse" />
      </BackgroundTasks>
   </Extension>
</Extensions>

A: Just a guess, but does this paragraph from the Band SDK documentation possibly help with your call of GetPairedBandsAsync as well?

If your app wants to connect to the Band from the background, then the
  app should call GetBandsAsync(isBackground: true) to get a connection
  that will not interfere with any app that is running in the foreground
  and currently using a Band connection.


text:
Q: Where/how can I host my small, database-driven, Sinatra-powered Ruby app? Heroku limits database connections Here is my app: a price inflation calculator. If you click 'Calculate,' you'll probably get a server-related error. When I tested the app out in Sinatra, I got an error saying
PG::Error: FATAL: too many connections for role "********"

After looking into it, it turns out that Heroku limits its free databases to 20 connections.
I'd like to continue developing small apps (especially database-driven ones) on Heroku, but I may not be able to if I'm unable to get around this restriction. I would pay $50/month to get a database that allows more connections, but I do not yet know if it would be worth it.
My question is: Does anyone know if it's possible to get around this restriction for free, or if there are alternatives to Heroku that can host a database-driven Sinatra app?
Here's the code I use that adds inflation data to the database:
require 'rubygems'
require 'rest-client'
require 'nokogiri'
require 'sequel'

### MAKE CPI DATABASE ###
db_name = 'DATABASE_NAME_HERE'
DB = Sequel.postgres(db_name,:user=>'USER_NAME',:password=>'PASSWORD',:host=>'HOST',:port=>5432,:sslmode=>'require')
    DB.create_table! :cpi_nsa_annual do
        primary_key :id
        Integer :year
        Float :cpi
    end # DONE: DB.create_table :cpi_nsa_annual do
cpi_annual = DB[:cpi_nsa_annual]
### DONE MAKING CPI DATABASE ###

post_url = "http://data.bls.gov/pdq/SurveyOutputServlet"

post_params = {
    'delimiter'=>'comma',
    'output_format'=>'html',
    'output_type'=>'column',
    'periods_option'=>'all_periods',
    'series_id'=>'CUUR0000SA0',
    'years_option'=>'all_years'
}

if page = RestClient.post(post_url,post_params)
    npage = Nokogiri::HTML(page)
    data = npage.css('table.regular-data tbody tr')

    data.each{|row|
        month_prefix = (row.css('th')[2].text)[0]
        year = row.css('th')[1].text
        month = (row.css('th')[2].text)[1..2]
        cpi = row.css('td').text

        if month_prefix=='M' and month=='13'
                cpi_annual.insert(
                    :year=>year,
                    :cpi=>cpi
                ) # DONE: cpi_annual_insert
                p ["YEAR",year,cpi]
        end # DONE: month_prefix=='M' and month!='13'
    }
end # DONE: if page
p cpi_annual.each{|row| p row}

A: It really doesn't seem like you need a database to accomplish what you want in that app. Can't you just store the annual rates in an array in your ruby code?
$inflation_rates = {"1999" => 2.19, "2000" => 2.97, "2001" => 3.73}

Or maybe I'm misunderstanding how your app works.
I've hosted small Sinatra apps with databases on Heroku without problems. The 20 connection limit has been enough. Are you sure its not a fault of your app? Maybe its using an excessive number of connections? Could you post your code?
Also, OpenKeyVal is an awesome free key/value data store with no connection limit (the only limit is the key must be under 64KB). It might force you to change your code around but its at least worth looking into. Because you can store data with JSONP calls you can build an app that uses the datastore in a single static html file.

A: meub's answer suggesting you store the data outside of a database is sound, but if you feel like you really want to stick with a database try looking into why your app is using so many connections.
If you run select * from pg_stat_database WHERE datname = 'yourdbname' the 'numbackends' field will tell you how many connections are being made to your database. If you do a fresh deploy to heroku and then visit your app a few times does the number of connections increase? Perhaps you need to close your connection.
If you add DB[:cpi_nsa_annual].disconnect at the end of your code does the number of connections stop going up with each page load?


text:
Q: contar resultados desde el controlador Con el siguiente código hago que busque en una BD=payments y si 'fecha_pago' es igual a hoy me lo muestre en la vista. Y según lo encontrado me agregue un contador. Si encontró 2 resultados el valor de la variable $varnum= 2.
Pero mi duda es como puedo hacer lo mismo sin que pase a una vista, directo del controlador. Mi objetivo es si encuentro 2 que coincidan con "hoy" poderlo guardar en una BD=system->numph. Igual si hay sugerencias en mi código de la vista las acepto por que recién ando aprendiendo.
tengo un controlador (UpdateController.php)
public function index(Request $request)
{
$hoy = \Carbon\Carbon::now()->toDateString();
$payments = Payment::searchdatepay($hoy)->orderBy('id','ASC')->paginate(10);
return view('update.update')->with(['payments'=> $payments, 'varnum' => 0]);
}

un scope (Payment.php)
protected $table = "payments";
protected $fillable = ['loan_id', 'id', 'pago', 'pagado', 'motivo', 'estado', 'fecha_pago', 'fecha_promesa', 'pago_abono', 'pago_adeudo', 'dias_atraso', 'asesor', 'remember_token', 'created_at', 'updated_at'];

public function scopeSearchDatePay($query, $var)
{
return $query->where('fecha_pago','LIKE',"%$var%");
}

una vista (update.update)
@section('content')

        Nº
        Fecha de Pago
        Motivo
        Estado

        @foreach($payments as $payment)

            {{ $varnum = 1 + $varnum }}
            {{ $payment -> id }}
            {{ $payment -> fecha_pago }}
            {{ $payment -> motivo }}
            {{ $payment -> estado }}

        @endforeach

{!! $payments-> render() !!}

@endsection

A: Por lo visto estás buscando count(), una función de PHP:
public function index(Request $request)
{
    $hoy = \Carbon\Carbon::now()->toDateString();
    $payments = Payment::searchdatepay($hoy)
        ->orderBy('id','ASC')
        ->paginate(10);
    $varnum = count($payments);
    return view('update.update', compact('payments', 'varnum'));
}

Le hice una pequeña mejora a tu código, sin embargo hay otras dos mejoras que sugiero:

*

*No debería ser responsabilidad del controlador obtener datos de la base de datos (o en este caso tener contacto con el Query Builder). Esta parte debería estar delegada a un servicio, job, repositorio o similar.

*Para respetar PSR-2, el cual es usado por Laravel, deberías declarar Carbon con use, algo así:
use Carbon\Carbon;

class PaymentController // ....
{
    // ...
    public function index(Request $request)
    {
        $hoy = Carbon::now()->toDateString();

        // ...
    }
}


text:
Q: OPENJSON unable to parse Portuguese characters I'm trying to convert my JSON data into a table format in SQL Server Express 2019. Following are my JSON data:
    DECLARE @token INT;
    DECLARE @ret INT;

    DECLARE @url NVARCHAR(MAX);

    DECLARE @json AS TABLE(Json_Table NVARCHAR(MAX))

    SET @url = 'http://www.test.com/webservice.php?user=DHRWWF&pass=CVernise&key=DFGJRTSrnwieuwn3&format=json'

    EXEC @ret = sp_OACreate 'MSXML2.XMLHTTP', @token OUT;
    IF @ret <> 0 RAISERROR('Unable to open HTTP connection.', 10, 1);

    EXEC @ret = sp_OAMethod @token, 'open', NULL, 'GET', @url, 'false';
    EXEC @ret = sp_OAMethod @token, 'send'

    INSERT into @json (Json_Table) EXEC sp_OAGetProperty @token, 'responseText'

    SELECT * FROM @json

    SELECT
        metadata.[col1],
        metadata.[col2],
        metadata.[col3],
        x1.[col1],
        x1.[col2],
        metadata.[col4],
        metadata.[col5],
        x2.[col1],
        x2.[col2],
        x3.[col1],
        x3.[col2],

    FROM OPENJSON((SELECT * FROM @json))  -- USE OPENJSON to begin the parse.

    -- At the highest level we n parts
    WITH (
        [Produts] NVARCHAR(MAX) AS JSON
    ) AS  Data

    -- Parse the Metadata
    CROSS APPLY OPENJSON([Data].[Produts])
    WITH(
        [col1] NVARCHAR(MAX),
        [col2] NVARCHAR(MAX),
        [col3] NVARCHAR(MAX),
        [col4] NVARCHAR(MAX) AS JSON,
        [col5] NVARCHAR(MAX),
        [col6] NVARCHAR(MAX),
        [col7] NVARCHAR(MAX) AS JSON,
        [col8] NVARCHAR(MAX) AS JSON,
    ) AS metadata

    CROSS APPLY OPENJSON([Metadata].[col4])
    WITH(
        [col1] NVARCHAR(MAX),
        [col2] NVARCHAR(MAX)
    ) AS x1

    CROSS APPLY OPENJSON([Metadata].[col7])
    WITH(
        [col1] NVARCHAR(MAX),
        [col2] NVARCHAR(MAX)
    ) AS x2

    CROSS APPLY OPENJSON([Metadata].[col8])
    WITH(
        [col1] NVARCHAR(MAX),
        [col2] NVARCHAR(MAX)
    ) AS x3

The result is:

metadata.[col1]
metadata.[col2]
metadata.[col3]
x1.[col1]
x1.[col2]
metadata.[col4]
metadata.[col5]
x2.[col1]
x2.[col2]
x3.[col1]
x3.[col2]

AABBCC
BBCCDD
DDEEFF
1
2
Sistema automático
ASDVDs
1
2
3
4

And a need this result

metadata.[col1]
metadata.[col2]
metadata.[col3]
x1.[col1]
x1.[col2]
metadata.[col4]
metadata.[col5]
x2.[col1]
x2.[col2]
x3.[col1]
x3.[col2]

AABBCC
BBCCDD
DDEEFF
1
2
Sistema automático
ASDVDs
1
2
3
4

TY


text:
Q: Pesquisa em php não retorna os resultados corretamente Estou com um problema referente ao retorno das informações do banco de dados em php, tenho duas tabelas, uma tb_regiao, com os estados brasileiros e outra, tb_representante com os representantes em cada estado.
Abaixo é a parte com o select:
 <form class="ajs-form-representante" method="GET" action="pesquisar_representantes_art_ferro_moveis_fibra_sintetica.php">
            <select type="text" name="pesquisar" >
                <option class="lista-cidade" value="" selected="selected">Escolha a Região</option>
                <?php require_once ("ajs-script-php/selecta_cidade.php");?>
            </select>
            <input type="submit" value="BUSCAR">
        </form>

O script para selecionar a região é esse abaixo:
<?php
require_once("ajs-adm/conexao/conecta.php");

$pesqu = $_GET["pesquisar"];
$listar = $conexao->prepare('SELECT * FROM tb_regiao WHERE regiao LIKE "%'.$pesqu.'%" LIMIT 27');
$listar->execute();
while ($exibe = $listar->fetch()){
    $nome_cidade = utf8_encode($exibe['regiao']);
    $nome_id = utf8_encode($exibe['id_id_reg']);
    echo "<option  class='$nome_id'>$nome_cidade</option>";
}

O código da pagina para exibir o resultado é esse abaixo:

            <?php
                $pesquisar = $_GET['pesquisar'];
                $result_repres = "SELECT * FROM tb_representante WHERE estado LIKE '%".$pesquisar."%' LIMIT 1";
                $result_resul_repres = mysqli_query($conect, $result_repres);
                   while($rows_repres = mysqli_fetch_array($result_resul_repres)){
                       echo "
Representante: ".utf8_encode($rows_repres['nome_rp'])."
";
                       echo "
E-mail: ".utf8_encode($rows_repres['email'])."
";
                       echo "
Celular: ".utf8_encode($rows_repres['cel_a'])."
";
                       echo "
Celular: ".utf8_encode($rows_repres['cel_b'])."
";
                       echo "
Telefone Fixo: ".utf8_encode($rows_repres['tel_fixo'])."
";
                       echo "
Empresa: ".utf8_encode($rows_repres['nome_empresa'])."
";
                       echo "
Endereço: ".utf8_encode($rows_repres['rua'])."
";
                       echo "
Bairro: ".utf8_encode($rows_repres['bairro'])."
";
                       echo "
Cidade: ".utf8_encode($rows_repres['cidade'])."
";
                       echo "
Cep: ".utf8_encode($rows_repres['cep'])."
";
                       echo "
Estado: ".utf8_encode($rows_repres['estado'])."
";
                   }
            ?>

abaixo é a tabela tb_regiao:
--

CREATE TABLE `tb_regiao` (
  `id_reg` int(11) NOT NULL,
  `id_id_reg` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `regiao` varchar(30) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Extraindo dados da tabela `tb_regiao`
--

INSERT INTO `tb_regiao` (`id_reg`, `id_id_reg`, `regiao`) VALUES
(1, '1', 'Acre'),
(2, '2', 'Alagoas'),
(3, '3', 'Amapá'),
(4, '4', 'Amazonas'),
(5, '5', 'Bahia'),
(6, '6', 'Ceará'),
(7, '7', 'Distrito Federal'),
(8, '8', 'Espírito Santo'),
(9, '9', 'Goiás'),
(10, '10', 'Maranhão'),
(11, '11', 'Mato Grosso'),
(12, '12', 'Mato Grosso do Sul'),
(13, '13', 'Minas Gerais'),
(14, '14', 'Pará'),
(15, '15', 'Paraíba'),
(16, '16', 'Paraná'),
(17, '17', 'Pernambuco'),
(18, '18', 'Piauí'),
(19, '19', 'Rio de Janeiro'),
(20, '20', 'Rio Grande do Norte'),
(21, '21', 'Rio Grande do Sul'),
(22, '22', 'Rondônia'),
(23, '23', 'Roraima'),
(24, '24', 'Santa Catarina'),
(25, '25', 'São Paulo'),
(26, '26', 'Sergipe'),
(27, '27', 'Tocantins');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tb_regiao`
--
ALTER TABLE `tb_regiao`
  ADD PRIMARY KEY (`id_reg`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tb_regiao`
--
ALTER TABLE `tb_regiao`
  MODIFY `id_reg` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

E abaixo é a tabela tb_representante:
--

CREATE TABLE `tb_representante` (
  `id` int(11) NOT NULL,
  `id_id_reg` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `nome_rp` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `nome_one` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `nome_two` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `nome_three` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `nome_empresa` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `tel_fixo` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `cel_a` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `cel_b` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `rua` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `bairro` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `cidade` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `cep` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `estado` varchar(40) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Extraindo dados da tabela `tb_representante`
--

INSERT INTO `tb_representante` (`id`, `id_id_reg`, `nome_rp`, `email`, `nome_one`, `nome_two`, `nome_three`, `nome_empresa`, `tel_fixo`, `cel_a`, `cel_b`, `rua`, `bairro`, `cidade`, `cep`, `estado`) VALUES
(1, '9', 'Alamo Manini Representações', 'alamomaninirep@terra.com.br', 'Elaine', 'Ataíde', 'Deivide', 'Alamo Manini Representações', '(62) 3515-1110', '(62) 99945-0318', '(62) 98252-1518', 'Rua 6, nº 370 Quadra E3, Lote 31, Sala 910', 'Empire Center, setor oeste', 'Goiânia', '74.115-070', 'Goiás'),
(2, '5', 'Caires Representações', 'cairesrepresentacoes@hotmail.com', 'Edvando', 'Zilmz', '', 'Caires Representações', '(77) 3441-2728', '(77) 99997-7885', '(77) 99996-3581', 'Praça dr. Nelson Lula, nº 22', 'Centro', 'Brumado', '46100-000', 'Bahia');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tb_representante`
--
ALTER TABLE `tb_representante`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tb_representante`
--
ALTER TABLE `tb_representante`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Quando clico para buscar o resultado, é retornado apenas o segundo registro, não mostra o primeiro e nenhum outro.

A: encontrei o erro, com essa dica sua, no script para selecionar a região, eu coloquei class='$nome_id', quando você escreveu acima, "colocar o valor" eu olhei e alterei para "value='$nome_id'", e pronto, rodou normal, quem quiser usar o código é só alterar que roda 100%`
esse é o script corrigido
<?php
require_once("ajs-adm/conexao/conecta.php");

$pesqu = $_GET["pesquisar"];
$listar = $conexao->prepare('SELECT * FROM tb_regiao WHERE regiao LIKE "%'.$pesqu.'%" LIMIT 27');
$listar->execute();
while ($exibe = $listar->fetch()){
    $nome_cidade = utf8_encode($exibe['regiao']);
    $nome_id = utf8_encode($exibe['id_id_reg']);
    echo "<option  value='$nome_id'>$nome_cidade</option>";
}


text:
Q: Inserting data in h2 using YAML, Play, JPA and Hibernate i'm quite new to using Play so please bear with me.
I would like to run jUnit tests on a my controllers. I want to insert my data using a test-data.yml file before the test runs. I have seen how it is done with Ebean but I was hoping not to add another library to the project just for testing.
My question is : can it be done without Ebean and if so how ?

A: If you see ZenTasks sample application for Play Framework, the Global class has this Yaml.load("initial-data.yml") on a static class called from onStart(). ZenTask sample uses Ebean, but is this the spot you are looking for?
Users are retrieved on a Map object all.get("users") but then you can save the data anyway you want. And this topic answers better to that i guess if JPA in mind.
Another way than YAML is to write Evolutions manually. Ebean generates evolutions for you automatically but you can also write them manually. See:
http://www.playframework.com/documentation/2.2.x/Evolutions


text:
Q: Sort list of dictionaries based on keys I want to sort a list of dictionaries based on the presence of keys. Let's say I have a list of keys [key2,key3,key1], I need to order the list in such a way the dictionary with key2 should come first, key3 should come second and with key1 last.
I saw this answer (Sort python list of dictionaries by key if key exists) but it refers to only one key
The sorting is not based on value of the 'key'. It depends on the presence  of the key and that too with a predefined list of keys.

A: Just use sorted using a list like [key1 in dict, key2 in dict, ...] as the key to sort by. Remember to reverse the result, since True (i.e. key is in dict) is sorted after False.
>>> dicts = [{1:2, 3:4}, {3:4}, {5:6, 7:8}]
>>> keys = [5, 3, 1]
>>> sorted(dicts, key=lambda d: [k in d for k in keys], reverse=True)
[{5: 6, 7: 8}, {1: 2, 3: 4}, {3: 4}]

This is using all the keys to break ties, i.e. in above example, there are two dicts that have the key 3, but one also has the key 1, so this one is sorted second.

A: How about something like this
def sort_key(dict_item, sort_list):
    key_idx = [sort_list.index(key) for key in dict_item.iterkeys() if key in sort_list]
    if not key_idx:
        return len(sort_list)
    return min(key_idx)

dict_list.sort(key=lambda x: sort_key(x, sort_list))

If the a given dictionary in the list contains more than one of the keys in the sorting list, it will use the one with the lowest index. If none of the keys are present in the sorting list, the dictionary is sent to the end of the list.
Dictionaries that contain the same "best" key (i.e. lowest index) are considered equal in terms of order. If this is a problem, it wouldn't be too hard to have the sort_key function consider all the keys rather than just the best.
To do that, simply return the whole key_idx instead of min(key_idx) and instead of len(sort_list) return [len(sort_list)]

A: I'd do this with:
sorted_list = sorted(dict_list, key = lambda d: next((i for (i, k) in enumerate(key_list) if k in d), len(key_list) + 1))

That uses a generator expression to find the index in the key list of the first key that's in each dictionary, then use that value as the sort key, with dicts that contain none of the keys getting len(key_list) + 1 as their sort key so they get sorted to the end.


text:
Q: Projectile search only part of the project When using emacs Projectile and helm-projectile, I am used to search for text inside the whole project. However is there a way to search only part of the project?
Something like:

*

*search inside a subfolder only

*search while excluding a subfolder

A: Yes you can exclude (sub) folders. Add a line in your .projectile:
-/sub/folder

So search inside a subfolder, I don't see something automatic. You could put project files in some subfolders (https://projectile.readthedocs.io/en/latest/configuration/#file-local-project-root-definitions) and switch projects.

A: For now I am using rgrep, which prompts for a string and a directory to find.
I would be happy to hear about an equivalent solution using ag, and I should mention I haven't yet dug into the link from @goromlagche (https://github.com/ggreer/the_silver_searcher#emacs).

A: Install helm-ag, this requires silversearcher-ag package; for debian apt install silversearcher-ag. And then you can

*

*helm-do-ag to search inside a sub-folder/directory inside project

*to ignore sub-folders/directories add them to either .gitignore or .hgignore if it is git and hg project respectively or add then to .projectile file, details here.

references:

*

*https://github.com/emacsorphanage/helm-ag

*https://github.com/ggreer/the_silver_searcher


text:
Q: Parsing url using url-parse I am using library to parse urls on my page:
import * as urlParse from 'url-parse';

const parseUrl = url => {
try {
 return urlParse(url);
} catch (e) {
 return null;
 }
};

The issue is when the url 'www.stackoverflow.com' is passed to the function, parseUrl returns http:localhost\www.stackoverflow.com
should I use to obtain the value http://www.stackoverflow.com?

A: You don't really need any external lib for this:
const parser = document.createElement('a');
parser.href = '//www.stackoverflow.com';
console.log(`${parser.protocol}//${parser.hostname}`); // 'https://stackoverflow.com'


text:
Q: UserAccountsDrawerHeader CircleAvatar suddenly not showing Suddenly the CircleAvatar has started not to show in the emulator or on phone, not sure why. Code hasn't changed, working with Android Studio on windows.
Tried copying to new project and fresh install of android studio.
UserAccountsDrawerHeader(
                accountName: Text('Test'),
                accountEmail: Text('test@gmail.com'),
                currentAccountPicture: CircleAvatar(
                  backgroundColor: Colors.blue,
                  child: Text('DB'),
                ),
              ),

No errors.
Result

A: I don't see the issue you stating.

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(),
      drawer: AppDrawer(),
    );
  }

  Widget AppDrawer() {
    return Drawer(
      child: ListView(
        children: <Widget>[
      UserAccountsDrawerHeader(
      accountName: Text('Test'),
      accountEmail: Text('test@gmail.com'),
      currentAccountPicture: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text('DB'),
      ),
    ),
        ],
      ),
    );
  }
}


text:
Q: Javascript URL parameter passing and receiving I have a question regarding URL parameters with Javascript...
Supposing I have:
<script src="http://example.com/javascript.js?param=true"></script>

How do I accept or receive the "param" parameter in the javascript.js script end.

A: Try this:
<script>
var param1var = getQueryVariable("param1");

    function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      alert('Query Variable ' + variable + ' not found');
    }
    </script>

A: <script src="my.js?myvar=123"></script>

and inside you js file,
var myTags=document.getElementsByTagName("script");
var src= myTags[myTags.length-1].src;
var state=unescape(src).split("myvar=")[1].split("&")[0];
alert(state);


text:
Q: installing and building Go after installing go and setting the GOPATH value while trying to execute a file present in bin(hello.exe) as %GOPATH%\bin\hello,the error shows bash:fg: no such job(used gitbash)

A: The problem you're facing is due to the way you're referencing the GOPATH. In Bash (and every shell I've used), variables are accessed by preceding the variable name with a dollar ($) symbol, like so:
echo $GOPATH

so what you should be using to run your program is:
$GOPATH/bin/hello

(Note: in Bash paths are separated with forward slashes, rather than the back slashes used in Windows)
An explanation of the error message
In bash and other shells, the percentage (%) symbol is used to reference stopped jobs. For example, we could do:
vim

(vim opens)
pressing ctrl + z will then send a stop signal to vim and return you to the shell. typing
    jobs
will then give you a list of stopped jobs:
jobs
[1]+  Stopped                 vim  (wd: ~)

you can then re-start the job, bringing it back to the foreground using
%1

or
fg %1

(one being the number of the stopped job),


text:
Q: onsubmit validateForm funxtion is not working here for validation i used onsubmit event.
but any how its not working.
i just want check that textbox  filed is empty or not.
    <!DOCTYPE html>

        <title>temple3</title>
        <link rel="stylesheet" type="text/css" href="temple3css.css">

    <form id="form" class="form"  onsubmit="return validateForm()">

Feedbak Form

            <input type="radio" name="view" value="public"  checked="checked"> Public
            <input type="radio" name="view" value="private" >Private

            Category:
            <select class="dropDownCate" autofocus>
            <option value="bug">Bug</option>
            <option value="1">1</option>
            <option value="2">2</option>
            </select>

            Comments:
            <textarea id="comments" name="Comments" placeholder='Your Feedback Here!' autofocus></textarea>

            Email
            <input type="email" id="email" name="Email" placeholder="example@stevens.edu(optional)" autofocus>

<input type="submit" id="submit-feedback-button"  autofocus>

</form>

earlier i  used same this for form validation. but i don't why its not working here. i tried to debug but function has not been call.

A: The problem is you are doing ajax submit in the button click event, not in the form submit.
The click handler is triggered before the submit event handler, so the validation does not have any effect.
The solution will be to use the form submit event handler for both validation and the ajax call as given below, and then there is no need to have the inline event handler like onsubmit="return validateForm()"
$("#form").submit(function () {
    if (validateForm() === false) {
        return false;
    }

    var category = $(".dropDownCate").val();
    var roption = $('input:radio[name=view]:checked').val();
    var message = $("#comments").val();
    var email = $("#email").val();

    $.ajax({
        type: "POST",
        url: "feedback.php",
        data: "category=" + category + "&roption=" + roption + "&message=" + message + "&email=" + email,

        success: function (result) {
            if (result == "true") {
                $("#form").hide();
                $("#container1").html("
Thank you for your feedback We will get back to you ASAP
 ");
            } else {
                $("#form").hide();
                $("#container1").html("
 database error
");
            }
        }
    });
    return false;
});


text:
Q: What is a simplest way to add a flag to a number in JavaScript without compromising its functionality? The code below:
var x = 600;
x.foo = true;
console.log("value: ",x);
console.log("foo: ",x.foo);

obviously this won't work, as JS numbers are unboxed. An obvious alternative would be to box all your numbers:
var x = { value: 600, foo: true }
console.log("value: ",x.value);
console.log("foo: ",x.foo);

but suppose you are using this method in a numerically expensive application. Then you get a heavy slowdown, as, now, you are creating a boxed object for every single number in your algorithm, which will wreak havoc in the memory management of the runtime. If all you need is a flag, though, a more lightweight option would be something like:
var x = flag_as_foo(600);
console.log("value: ",extract_value(x));
console.log("foo: ",is_foo(x));

where flag_as_foo, flag_as_not_foo, is_foo and extract_value could operate by flipping the bits on the number, or maybe using some clever arithmetic. My question is, what is the best way to implement it in JavaScript? This is not obvious, considering JS has no ints and a non-usual way to treat numbers.
Please read the question. I am specifically asking for a bitwise or arithmetic solution of tagging a number.

A: JavaScript does, in fact, have logical integers, which are employed when using certain operations like bitwise booleans and shifts. Here's a set of functions that meet your criteria, assuming you only work with integer values:
function flag_as_foo(n) {
    n = n << 1;
    return n | 1;
}

function extract_value(n) {
    return n >> 1;
}

function is_foo(n) {
    return !!(n & 1);
}

var x = flag_as_foo(600);
console.log("value: ",extract_value(x));
console.log("foo: ",is_foo(x));

This reserves the least significant bit as a flag. The number is, of course, not usable as a proper value without running it through extract_value (as you've specified), since x here is not used as an integer, but as a string of bits (the first 31 of which represent a number, and the 32nd of which is a flag).
Note that the maximum number of usable numerical bits here becomes 31, as constrained by the logical ECMAScript operator ToInt32.

A: This is the closest you can get:
var a = new Number(1), b = new Number(2);
a.isBlue = true;        //you can do this since a and b are now an Object

console.log(a+b);       //3
console.log(a.isBlue);  //true

One major drawback is that you need extra effort to check if two numbers are the same:
a == b                  //false (assuming both have the same value)

Since they are now Objects, you would have to do this:
a.valueOf() === b.valueOf() //true

Update:
If you are a bitwise or arithmetic solution of tagging a number, what I would do is to utilize the sign of the number (assuming you only have possible numbers.) Otherwise, I can't think of any simple solution.

A:
considering JS doesn't have integers

You can't store any sort of flag on an int to begin with. That said your best option would be to use an object literal. I do realize you stated in your question that you did not want to use objects. Yet doing something like
var a = {"number": "1337" , "color": "blue"};
alert(a.color);

seems to make the most sense.


text:
Q: How do I improve the performance of a listview? When I use images from the internet in a Listview, my Listview scrolls very slowly.
But in some applications such as Twitter, Google+ and other applications (despite showing images from the internet) there is no problem with scrolling and it is very fast and smooth.
How do I improve the performance of a Listview with images?

A: Check out this one, list view performance optimization from Larse Vogella
You can also use endless list or lazy loading where you load only some part of data in listview & load other when user reaches bottom of list
lazy loading OR
Commonsware's adapter for endless loading

A: There are some ThumbRules which might help you in optimizing listview:
-> Reuse Views by using ConvertView, in
`getView(AdapterView<?> adapterView, View convertView, int position, long id)`

->. Use Lazy Loading for Loading images from web, see
http://codehenge.net/blog/2011/06/android-development-tutorial-asynchronous-lazy-loading-and-caching-of-listview-images/
->   Also use ViewHolders to improve inflation time.check link:
http://jmanzano.me/efficient-listviews-in-android-viewholder-pattern-2/

A: use LoaderImageView in your listview. you can get LoaderImageView code from here http://blog.blundell-apps.com/imageview-with-loading-spinner/
modify the LoaderImageView code to store the drawable downloaded


text:
Q: logging libraries for visual studio 2010 Visual Studio 2010
I was using log4net for Visual Studio 2005. However, I am now using visual studio 2010.
log4net is not available for that framework.
Is there any other logging libraries out there that I can use?
Many thanks,

A: Just to clarify, the IDE isn't really a factor here.  That said, use Enterprise Library.

A: If you want to stick with log4Net, it may be as simple as changing your application's target framework.  See this post that describes how the author was able to get log4Net up and running: http://krishnabhargav.blogspot.com/2010/02/using-net-35-clr-20-dll-inside-visual.html


text:
Q: Accessing a database running in docker container from the internet I have an application running inside a Docker container in Azure, running as an App Service. The application uses a MimerSQL database that is inside the same container as the application.
I would like to be able to access the database port (1360) from my desktop to look inside the database for debugging purposes but I have not discovered a way to reach it from the outside.
If I run the Docker container on my desktop I have no problems as I can supply the "-p" directive and hence map the database port to a port accessible from my host (or any other computer, for that) but I have so far not been able to find a similar directive in Azure to expose the port to the outside world, neither as 1360 nor as anything else.
I was thinking about mapping the database to a web port but the application uses the https port for a status message so that one is gone.


text:
Q: How to make glassmorphic navbar? Some websites have blur background navbar. How can such transparency effect be achieved with HTML & CSS?

A: You can do this with two lines of CSS:
background: rgba(255, 255, 255, .4);
backdrop-filter: blur(10px);

If you run the fully-documented snippet I created below, you can see that I've made both the card AND the navbar part transparent. I also added the Stack Overflow logo underneath to display the glassmorphic effect. Because I used a Bootstrap navbar, there are two things to note:

*

*You need to remove the default bootstrap navbar classes in order to apply these effects.

*You need to change the Z-Index of the navbar if you want any design to show up underneath.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href= "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <title>Glassmorphism effect by Billy for StackOverflow</title>

        Navbar

Glassmorphism for StackOverflow

Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit perferendis illum,
            placeat quod perspiciatis sequi ullam odit.

        Read more


text:
Q: Json View doesn't restrict the fields in the response I need to send only 1 field annotated with @JsonView(in my case : eNumber) in my response. Also, this has to be only when the call is from Controller1 which also has a JsonView annotation.
But, eNumber field value is sent also when the call is from Controller2 which is not annotated with @JsonView. What am I missing here ?
Below is my code:
DTO:
public class MyClass {

    @JsonView(Views.InternalRequest.class)
    public String getEnumber() {

      return eNumber;
    }

    .... other fields
}

Controller classes :
@RequestMapping("/api/ctr")
public class Controller1 {

    @GetMapping(value = "/{serviceId}/eva", produces = MediaType.APPLICATION_JSON_VALUE)
    @JsonView(Views.InternalRequest.class)
    public ResponseEntity<MyClass> findAllEva() {

        return ResponseEntity.ok(new MyClass());
    }
}

@RequestMapping("/api/abcd")
public class Controller2 {

    @GetMapping(value = "/{serviceId}/evss", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<MyClass> findAllEvs() {

        return ResponseEntity.ok(new MyClass());
    }
}

View:
public class Views {
    public static class InternalRequest {
    }
}

A: I believe you need to do the following:

*

*Define two views; one for internal one for public.

*Annotate the fields not the getters (I believe, not 100% sure about this step).

*Annotate the Controller2 method with "@JsonView(Views.Public.class)"

Here is a Baeldung article describing JsonViews


text:
Q: perl script wont run unless I use perl prefix I have a weird problem trying to run a simple perl script on ubuntu 22.04.
test.pl content:
#!/usr/bin/perl
print "Hello\n";

output of which perl command:
/usr/bin/perl

I used to run scripts with just their path, but now I get permission denied when doing so, unless I use the perl prefix.
distcc@a172-24-178-137:~$ ./test.pl
bash: ./test.pl: Permission denied
distcc@a172-24-178-137:~$ perl ./test.pl
Hello

Permissions look fine to me:
distcc@a172-24-178-137:~$ ls -l test.pl
-rwxr-xr-x 1 distcc staff 33 Feb  6 17:07 test.pl

what is causing the problem?


text:
Q: Illegal Start of Expression, trying to print I'm getting several errors here, a ";" and ")" expected error, an "illegal start of expression error and a "not a statement error."
These two lines are the culprits.
System.out.println("Rectangle alpha has a width of "+alpha.width+", a height of "+alpha.height+" a perimeter of "alpha.getPerimeter()+" and an area of "+alpha.getArea()+".");
System.out.println("Rectangle beta has a width of "+beta.width+", a height of "+beta.height+" a perimeter of "beta.getPerimeter()+" and an area of "+beta.getArea()+".");

Unfortunately this is one of those times where I don't even know what I don't know to look for  what I need to understand/fix this. I actually wanted to use a method to print these two, but I got 'not a statement errors' when I decided to instead do the above and get many more errors...
Thank you so much, I was stuck on this for like 2 hours...not understanding what was wrong...The code itself took 10% of the time :|

A: You are missing a + in between your string and alpha.getPerimeter()/beta.getPerimeter().
System.out.println("Rectangle alpha has a width of "+alpha.width+", a height of "+alpha.height+" a perimeter of "+alpha.getPerimeter()+" and an area of "+alpha.getArea()+".");
System.out.println("Rectangle beta has a width of "+beta.width+", a height of "+beta.height+" a perimeter of "+beta.getPerimeter()+" and an area of "+beta.getArea()+".");

I always put a space on both sides of operators. This issue confirmed why I do that - you would have definitely noticed the missing + had you done this.


text:
Q: (Anonymous) Namespaces, Functions, and Header Files Not sure if this question has been asked before. I searched around and couldn't find an exact answer for my scenario, but I may have missed it.
The issue: I have a namespace in a header file, and some function prototypes inside that namespace in the header:
namespace Foo{
    void SomeFunc();
    void SomeOtherFunc(int);
}

In the .cpp file, I want to define the functions in the namespace while also providing some protection to an random number generator they all rely on with an anonymous namespace:
namespace Foo{

    namespace{
        RNG rando = new RNG();
    }

    void SomeFunc(){
        //implementation
    }

    void SomeOtherFunc(){
        //implementation
    }
}

The issue I am having is that there is no guarantee that the prototypes in the header file match up to the functions I am defining in the cpp file. Everything in the namespace{} code block can just be something new added to the namespace.
In the above code examples, SomeOtherFunc() is implemented without an argument of type int, but its declaration says it takes some argument. In actuality, it seems I overloaded the SomeOtherFunc() signature.
I could use the following in the cpp file:
namespace Foo{

    namespace{
        RNG rando = new RNG();
    }

}
void Foo::SomeFunc(){
    //implementation
}

void Foo::SomeOtherFunc(int){
    //implementation
}

The compiler seems to enforce the relationship between the functions' declaration and implementation, which I like. But then the functions seemingly don't have access to the data inside the anonymous namespace.
Am I missing something here? Is there something I could do to resolve the issues I feel are present in this implementation? I am not very well-versed in using (anonymous) namespaces, and so I apologize if this seems basic.

A: Move the unnamed namespace out of the other namespace:
namespace{
    RNG rando = new RNG();
}

void Foo::SomeFunc(){
    //implementation
}

void Foo::SomeOtherFunc(int){
    //implementation
}

It can't be accessed outside the translation unit anyways.

A: The usual convention is to as far as I know is to declare the anonymous namespace at the start of the .cpp files. In your case your cpp file should look like this.
namespace{
   RNG rando = new RNG();
}

void Foo::SomeFunc(){
    //implementation
}

void Foo::SomeOtherFunc(int){
    //implementation
}

This way the functions should have access to rando.

A: The anonymous namespace is a red herring. You can ignore it, it's literally an implementation detail.
Yes, you can overload a function from the header in the .cpp file. However, if you would try to use the undefined half of the pair, you'd get a linker error.