text:
Q: Java application CPU/load much higher when built against JDK8 I have a Java application developed in Eclipse Luna in Windows that runs in Amazon EC2 (c3.large, Amazon Linux).  This application processes work at a very consistent incoming rate.  When I build the application against JDK 8u31, the EC2 CPU load is much higher than the same application built against JDK 7u75.
The application originally ran with the default JRE on EC2, and I added the OpenJDK 1.8.0.31 to take advantage of the Java 8 Process waitFor(long timeout, TimeUnit unit).  The main work this application does involves invoking an application using Runtime.exec.
$ sudo alternatives --config java

There are 2 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
*  1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
 + 2           /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-2.b13.5.amzn1.x86_64/jre/bin/java

Example load average when the application is built against 1.7:
top - 00:20:28 up 4 days, 10:41,  4 users,  load average: 0.37, 0.26, 0.52

Example load average when the application is built against 1.8:
top - 23:45:52 up 4 days, 10:06,  4 users,  load average: 2.28, 2.60, 2.01

It seems like it may be related to the Open JDK 1.8.0.31, but I don't know how to debug this.  There are no code changes, I'm only changing the compliance level and build between 1.7 and 1.8 in Eclipse Luna.  Any idea why the load would be so much different?
UPDATE:
I see similar high CPU load when I use the Oracle JDK on EC2.
$ sudo alternatives --config java

There are 3 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
   1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
   2           /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-2.b13.5.amzn1.x86_64/jre/bin/java
*+ 3           /usr/java/jdk1.8.0_31/bin/java

Load average:
top - 01:45:27 up 4 days, 12:06,  4 users,  load average: 2.28, 1.50, 1.04

A: You've described symptoms, but I don't think this is enough to go on, if only because it will be impossible to search for things like "java 8 high CPU" anywhere (google, the java bug parade, etc.) and find useful results. Unfortunately, you need to collect more information about what's using CPU. Here are some thoughts on how to do so:

*

*Profile with a tool such as VisualVM. The load differences are extreme, so you might just be able to spot what's using the CPU.

*Find the busy threads. You can take a bunch of thread snapshots and eyeball it, or try a tool such a jvmtop.

*Check what the garbage collector is doing, either by enabling GC logging or with a tool such as jstat.

*Use strace to trace the execution of system calls.

A: The documentation says: "The default implementation of this methods polls the exitValue to check if the process has terminated. Concrete implementations of this class are strongly encouraged to override this method with a more efficient implementation."
I strongly suspect this to be the reason.
See http://docs.oracle.com/javase/8/docs/api/java/lang/Process.html#waitFor--


text:
Q: Using C++ library on website I'm about to write a large amount of code in C++ for maximum portability. I need this code to be able to run on a website and on an Android application through JNI. Although Java is technically also an option here, I may want to use this library in other projects in the future which will all be C++ based and I want to get the advantage of native speed because it's a math related library.
My question is what the best option is to run this code on a web site. The website itself doesn't have to be written in C++ just like the Android application itself is mostly written in Java.
I can see the following options:

*

*Write a PHP module to interface with this library

*Write a server in C++ for the API of the site that the site written in PHP accesses

*Write a fastcgi server

What do you think is my best option here?

A: The choice is obviously yours and all of the options sound great but I think using factcgi with something like WT or CPPCMS will be awesome. Take a look at both of them they are wonderful libraries for this task, I prefer CPPCMS but I think that depend on your need

A: What about a good old cgi programm? Is it penalty of starting up a process too big to justify the higher complexity of fastcgi?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swap classes between div's I have 2 main div's. Group1 and group2. Those group divs contain other 2 (or more) div each. All the div's inside the group's have a class of .grp_item. Now grp_item is display:none and only one div in each group has a class .sel which is display:block .
How can I swap the class .sel between the groups ? Div's inside the groups are the same between them.
Here is the structure:

        Div First

        Div second

<button id="swap">SWAP</button>

        Div First

        Div Two

So for this example, when swap button pressed, set .sel in group one to the first Div and in group2 set .sel to Div Two.
Here is the fiddle of the structure: http://jsfiddle.net/d6TFh/
Note that I can't add any more classes in the inner div's so I would imagine I should be first setting the classes to each and then removing them.
Is this possible using .contain() or any other way?

A: Try this: http://jsfiddle.net/d6TFh/3/
$("button").on("click", function () {
    $('div[id^="group"] > div').toggleClass('sel')
});

A: Based on your conversation with Ayman Safadi I think this is what you are looking for:
var a = $('#anything .sel').attr('id')
var b = $('#something .sel').attr('id')

$('#anything .sel').removeClass('sel')
$('#anything').find('#' + b).addClass('sel');

$('#something .sel').removeClass('sel')
$('#something').find('#' + a).addClass('sel');

And the jsFiddle: http://jsfiddle.net/d6TFh/10/


text:
Q: Hiding Empty ttk Notebook Tabs with Grid vs Pack At https://github.com/muhammeteminturgut/ttkScrollableNotebook there is a lovely demo of effectively adding scrolling tabs at the top of a notebook.  But there is actually a notebook elements, one on top of the other.
if self.useGrid:
    self.rowconfigure(0, weight=1)
    self.columnconfigure(0, weight=1)
    leftArrow.grid(row=0, column=0)
    rightArrow.grid(row=0, column=1)
    slideFrame.grid(row=0, column=0, sticky=NE)
    self.notebookContent.grid(row=1, column=0, sticky="nsew")
else:
    leftArrow.pack(side=LEFT)
    rightArrow.pack(side=RIGHT)
    slideFrame.place(relx=1.0, x=0, y=1, anchor=NE)
    self.notebookContent.pack(fill="both", expand=True)

I am trying to convert it to use grid instead of pack, but when using grid the empty tabs of the bottom notebook are displayed.  Somehow they are hidden when using pack.  What is the difference here?  How can grid reproduce pack's functionality here?


text:
Q: HTML5 & CSS - media queries operators question I was wondering if someone can explain what each of the media queries in the example below mean in simple terms?
Here is the examples.
media="not screen and (color)"
media="projection, screen and (color)"
media="only projection and (color)"

A: To analyze what media queries mean, you basically need to keep these things in mind:

*

*A comma means "or".

*The unparenthesized thing at the beginning of a media query is the name of the medium the query is for (unless that word is "not" or "only", in which case the second word is the medium involved.

*"not" negates everything up to the comma that follows.

*Things in parens are modifiers.

*The algorithm HTML4 specified for parsing media is horribly broken: it just extracts the first word from each part between commas.  The keyword 'only' was introduced to allow media query authors to work around this bug.  A UA that implements media queries just ignores this keyword.

So now in order.
Your first media query selects everything that's not a "screen and (color)".  So it selects anything that's not a color screen (i.e. non-screens and also monochrome screens).
Your second media query selects anything that's a projection medium (whether color or monochrome) or a color screen.
Your third media query selects color projection media in UAs that implement media queries.  In a UA that implements the HTML 4 algorithm, it's ignored because "only" is not an HTML 4 media specifier.  If "only" were left out, then in old UAs it would select all projection media, because it would just extract that first word and ignore the "and (color)" part.


text:
Q: Cochrane-Orcutt Prediction in R I am trying to predict specific values after using a cochrane-orcutt adjustment.  My issue is that using predict() or predict.orcutt(), is only returning the predicted values using the original data used to build the model.  The example below is not my data, but it can be used to replicate the problem.
# Values used to build model
build_model = mtcars[1:22,]

# Input values for future predictions
predict_values = mtcars[23:32,]

# Linear Model
fit = lm(mpg~cyl, build_model)

# Cochrane.Orcutt correction
coch_class = cochrane.orcutt(fit)

# Use Predict Function
predict.orcutt(coch_class, newdata = predict_values$cyl)

[,1]
Mazda RX4           20.46226
Mazda RX4 Wag       20.46226
Datsun 710          26.01009
Hornet 4 Drive      20.46226
Hornet Sportabout   14.91443
Valiant             20.46226
Duster 360          14.91443
Merc 240D           26.01009
Merc 230            26.01009
Merc 280            20.46226
Merc 280C           20.46226
Merc 450SE          14.91443
Merc 450SL          14.91443
Merc 450SLC         14.91443
Cadillac Fleetwood  14.91443
Lincoln Continental 14.91443
Chrysler Imperial   14.91443
Fiat 128            26.01009
Honda Civic         26.01009
Toyota Corolla      26.01009
Toyota Corona       26.01009
Dodge Challenger    14.91443

A: The orcutt library doesn't seem to support prediction with new data. The source for the predict.orcutt function just returns the fitted values. It ignores any parameters.
orcutt:::predict.orcutt
# function (object, ...)
# {
#     return(object$fitted.values)
# }

Perhaps contact the authors of the package to see if they derived a method to make predictions after the adjustment.


text:
Q: Cannot install nativescript I'm trying to install NativeScript and I am getting this error when I do
npm i -g nativescript

npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\Program
  Files\nodejs\node.exe"
  "C:\Users\John\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js"
  "i" "-g" "nativescript" npm ERR! node v8.9.1 npm ERR! npm  v4.0.3
npm ERR! Cannot read property 'assert-plus' of undefined
. . .
npm ERR! Cannot read property 'minimist' of undefined

when I run this command on a Mac, I get:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: abbrev@1.1.0
  (node_modules/nativescript/node_modules/fsevents/node_modules/abbrev):
  npm WARN enoent SKIPPING OPTIONAL DEPENDENCY: ENOENT: no such file or
  directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/abbrev'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.abbrev.DELETE'
npm ERR! path
  /usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex
  npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall rename npm
  ERR! enoent ENOENT: no such file or directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.ansi-regex.DELETE'
  npm ERR! enoent This is related to npm not being able to find a file.
  npm ERR! enoent

Does anyone know how to work around this? I have the latest version of Node and npm. Maybe that is my problem? Does anyone know what version would work? Thanks!

A: Since you are using windows you need to run this for installation
@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://www.nativescript.org/setup/win'))"

See https://docs.nativescript.org/start/quick-setup section Windows

A: This was interesting to me. I had had npm 4.01 on the Windows machine and getting the lastest (npm i -g npm@latest), 5.5.1, made it work. On the Mac machine I already had 5.5.1 but rolling that back to 4.1.1 allowed the install to work. So on Windows, 5.5.1 was good but not on the Mac.


text:
Q: Should I worry about dynamic codegen mismatch with my other modules written in C++ I have a Proto file which is being used in a NodeJs and C++.
C++ is using protoc compiler whereas NodeJS is using dynamic codegen, My worry is that if the C++ uses a different compiler version than my NodeJS dynamic codegen, could it be an issue for us?
If yes, What do you guys recommend to resolve this? Should I use static codegen? What are the advantages and disadvantages for both If anyone can help me understand, Thanks

A: There should not be a problem with using those two different protobuf/gRPC code generation methods together. The different code generation methods affect the API, but they are still working with the same serialized format, so they can send messages to each other without problems. In fact, gRPC has a continuous interoperability test suite to ensure that these different clients and servers can communicate with each other.
One potential issue to keep in mind is a bug with the way the current Node.js gRPC dynamic codegen handles repeated primitive fields. To avoid this problem, you should explicitly set the packed attribute on any repeated primitive field.


text:
Q: Aiogram событие mention (в entities) не возвращает user for en in message.entities:
    if en.type == 'mention':
        logging.info(en.as_json())
        user_receiver = en.user
        command = command.split('@')[0].strip()

ошибка:
AttributeError: 'NoneType' object has no attribute 'id'

mention в логах:
{"type": "mention", "offset": 4, "length": 12}


text:
Q: Get common element from 2 given lists So i have this 2 collections:
import collection.mutable.ListBuffer

val list1 = ListBuffer[(String, String)]()
list1 += (("Italy", "valid"))
list1 += (("Germany", "not valid"))
list1 += (("USA", "not valid"))
list1 += (("Romania", "valid"))

val list2 = ListBuffer[String]()
list2 += "Germany"
list2 += "USA"
list2 += "Romania"
list2 += "Italy"
list2 += "France"
list2 += "Croatia"

I want to get new list that contain common countries with specific condition for example valid so the result will be new list:
Italy, Romania

A: When you need to filter and map at the same time, use collect:
list1.collect { case (c, "valid") => c } intersect list2

A: Using a for comprehension as follows,
for ((a,"valid") <- list1 if list2.contains(a)) yield a

This comprehension desugars into a flatMap and a lazy filter. We pattern match (extract) those tuples whose second item matches "valid" and check whether the validated country belongs to the second list.

A: I think you should filter, map and then intersect
list1 filter(_._2=="valid") map(_._1) intersect list2

A: You could define following method:
def intersectWithCond[A, B](xs: Seq[(A, B)], ys: Seq[A])(cond: B => Boolean): Seq[A] = {
  xs.filter(x => cond(x._2)).map(_._1).intersect(ys)
}

Usage:
intersectWithCond(list1, list2)(_ == "valid") // returns ListBuffer(Italy, Romania)


text:
Q: cmd for loop converting special/foreign characters? I have a directory with a file with some unusual characters in its name, a simple dir command returns the correct filename:
> dir /b
ćłńó.txt

I have a very simple for loop running in a command prompt.
However, for some reason the for loop is returning a filename with similar but different characters:
> for /f "delims=" %F in ('dir /b') do echo %F
clnó.txt

Obviously this is not the desired result.
How do I fix this?


text:
Q: How to make Secure Gateway Client to resolve the hostname of the destination's host I would like to use a hostname instead of IP address as a destination's host in Bluemix Secure Gateway. I use the docker Secure Gateway Client. I tried to realize it by editing /etc/hosts of the host os in which the docker Secure Gateway Client is installed and by running the SG Client with --net="host" or --add-host=hosname:IP address. Secure Gateway Service seems not to use DNS regarding the following Q&A's Answer, so I tried to use /etc/hosts.
How to resolve SG Client's ENOTFOUND error
But I couldn't succeed, SG Client got ENOTFOUND. Could you teach me how to make Secure Gateway Client to resolve the hostname of the destination's host.
[results of --net="host"]

*

*I confirmed the host os resolved the hostname.

#ping httpserver1
  PING httpserver1 (192.168.56.1) 56(84) bytes of data.
  64 bytes from httpserver1 (192.168.56.1): icmp_seq=1 ttl=128 time=7.10 ms
  64 bytes from httpserver1 (192.168.56.1): icmp_seq=2 ttl=128 time=6.89 ms

*I ran SGClient with --net="host"

# docker run -it ibmcom/secure-gateway-client XXXXXXXXXX --net="host"
  IBM Bluemix Secure Gateway Client Version 1.2.1

  [2015-07-08 15:47:01.097] [INFO] The Secure Gateway tunnel is connected

*SG Client got ENOTFOUND error

#[2015-07-08 15:47:01.097] [INFO] The Secure Gateway tunnel is connected
  [2015-07-08 15:57:08.588] [INFO] Connection #3 is being established to httpserver1:3000
  [2015-07-08 15:57:16.602] [ERROR] Connection #3 to destination httpserver1:3000 had error: ENOTFOUND
  [2015-07-08 15:57:16.603] [INFO] Connection #3 to httpserver1:3000 was closed

*SG seems to support --net="host" regarding the SG docs, but it seems not work well.
https://www.ng.bluemix.net/docs/troubleshoot/SecureGateway/ts_index.html#ts_sg
[results of --add-host=httpserver1:192.168.56.1]

*

*I ran SGClient with --add-host=httpserver1:192.168.56.1

#docker run -it ibmcom/secure-gateway-client XXXXXXXXXX --add-host="httpserver1:192
  .168.56.1"
  IBM Bluemix Secure Gateway Client Version 1.2.1
  [2015-07-08 16:09:20.028] [INFO] The Secure Gateway tunnel is connected

*SG Client got ENOTFOUND error

[2015-07-08 16:09:37.214] [INFO] Connection #5 is being established to httpserver1:3000
  [2015-07-08 16:09:45.231] [ERROR] Connection #5 to destination httpserver1:3000 had error: ENOTFOUND
  [2015-07-08 16:09:45.232] [INFO] Connection #5 to httpserver1:3000 was closed

A: I think the only way to get this to work locally is if you get your internal IT group to add the name of that host to the DNS. Remember updates to the /etc/hosts file are local in scope, no other machines will use that information to resolve your hostname to that IP. I this case you are asking the Secure Gateway server in Bluemix to find something that you have defined locally in your own class C/D subnet, it cannot do that without a DNS change.
Another alternative would be to try and use the docker '--dns ' parameter, providing the ip address of the DNS that is reachable.


text:
Q: set Time on a message using javascript/jquery I want to display a message for about 5 - 10 seconds. After 5 - 10 seconds the message should disappear from the screen.
My code:
if (hasAnyPickedToken == true) {
   htmlToken += '
You Have Successfully Picked the token,now you can start your work by clicking open Token.</button>
';
}

This message should disappear after 5 - 10 seconds after page loaded.

A: WORKING FIDDLE
You can hide it out this way
$(document).ready(function(){
    function hideMsg(){
    //alert("hi");
        $("span").fadeOut();
    }
    setTimeout(hideMsg,10000);
});

Change elements accordingly.

A: Try using setTimeout to create a delay before firing a function. This function might add a class to fade out your message with CSS3, or you might prefer jQuery.

A: You can use fadeOut(time) function of jquery...
For example
$(document).ready(function{

    $("#divId").fadeOut(10000); })

A: If you only want to display the message once per visitor, you'll have to use some client side storage such as cookies.
Here's a working example:
<!DOCTYPE html>

    <meta charset=utf-8 />
    <title>Message Cookie Demo</title>

Hello, there!

This is some content

      This message will vanish after 5 seconds. It will only display once"

This uses the following cookie library. The cookie will expire after one day and is valid across the entire site. You can easily tweak this to suit your purposes.
When you try this demo, be sure to run it on a server. It won't work locally in some browsers.


text:
Q: Can't keep width of div in tailwindcss framework I am trying to make a copy of the example TailwindCSS card element, but instead of the default style (the bottom one in the below example) I want to make the area where the picture is another text area.
However, I can't get the (former-)picture div to keep its width / dimensions the way it does when there is a picture in it. Currently, the two divs inside the topmost card seem to overlap.
What am I missing? How can I make the (former-)picture div maintain width as windows resize etc as it does in the original when there is a picture in it?

Testing text

WELCOME

              Rec

Testing text

              <img class="h-48 w-full object-cover md:h-full md:w-48" src={`${process.env.PUBLIC_URL}/img/photo-test.png`} alt="Man looking at item at a store" />

2021 - Present · STUFF

              STUFF

Testing text


text:
Q: Как вызвать функцию в компоненте из другого компонента? как вызвать функцию в компоненте по onClick из другого? Я набросал примитивный пример, разумеется, в данном примере можно всё перенести в один компонент, но на реальном проекте мне нужно, чтобы функция changeData выполнилась в отдельном компоненте.
В интернете нашёл инструкцию только по классовым компонентам.
Ссылка на CodeSandbox


text:
Q: fetch elements that occurred multiple times in Ruby Array Given you have a Ruby Array like a = [1,2,3,2,4,4,2,5] how can you select elements that occurred multiple times in the given array ?
so return value == [2,4]

A: a.group_by(&:itself).select{|_, a| a[1]}.keys

A: My colleague suggested this :
a = [1,2,3,2,4,4,2,5]
a.select{ |el| a.count(el) > 1 }.uniq
# => [2,4]


text:
Q: Returning an object from a callback I want to return an object out of a callback. When I run the below code, the log of the body object looks as expected. It appears to be the correct JSON object containing the response I want from the server: name, email, website, etc.
But the result object appears to contain information about the request itself instead of the response object.
How do I return the body object so that I can access it from the result variable?
const request = require('request'); // npm i request -s

module.exports = async config => {
  ...

  const result = await request.get( url, options,
    ( error, response, body, ) => {
      console.log( 'body', body, ); // I want the other log to look like this log.
      return body;
    }
  );

  console.log( 'result', result, ); // I want this log to look like the above log.
  // In other words, I want the below line to be the name, email, website JSON object
  // contained in the body
  return result;
}

This is what I want from result.

console.log( 'body', body, );

body {
  "name": "foo",
  "email": "foo@example.com",
  "website": "www.example.com",
  ...
}

This is what I actually get from result.

console.log( 'result', result, );

result Request {
  _events: [Object: null prototype] {
    error: [Function: bound ],
    complete: [Function: bound ],
    pipe: [Function]
  },
  _eventsCount: 3,
  _maxListeners: undefined,
  uri: Url {
    protocol: 'https:',
    slashes: true,
    auth: null,
    host: 'api.example.com',
    port: 443,
    hostname: 'api.example.com',
    hash: null,
  },
  callback: [Function],
  method: 'GET',
  readable: true,
  writable: true,
  explicitMethod: true,
  _qs: Querystring {
    request: [Circular],
    lib: { formats: [Object], parse: [Function], stringify: [Function] },
    useQuerystring: undefined,
    parseOptions: {},
    stringifyOptions: {}
  },
  _auth: Auth {
    request: [Circular],


text:
Q: Default report paramter value in SSRS 2012 I am receiving the following error from my child report: "The report parameter 'prmDefaultValueForSnapShots' has a value of DefaultValue or a ValidValue that depends on the report parameter 'prmStoreName'. Forward dependencies are not valid."
I have a parent report that feed values to the child report to display all sales data for the specific store. However, this report is rather large, thus I'm trying to set a snapshot for it on the Report Manager to execute in the early mornings for better user experience. For the snapshot to work, I need a default value on the parameter and I have been unable to make it work.
If anyone has any idea how to resolve this particular issue. Please, give me any suggestion as you can.
Regards,
Marcus
I have been researching this issue since Tuesday and I have not had any luck.

A: I'm not entirely sure I understand your goal or configuration. I'm also not sure if prmDefaultValueForSnapShots and prmStoreName are parameters of the main report or the sub-reports, and which of the two throws the error.
However, this error may occur if a parameter depends on another parameter which is not yet provided. Note that the order of the parameters is important. By "order", I mean the order in which they are defined, which is also the order in which they appear in the list (you can reorder them using the arrow buttons).
Is it possible that prmDefaultValueForSnapShots depends on prmStoreName, but is defined before it?


text:
Q: How to check if substring of string's array match to patterns from other string array I wonder if there is any groovy-way to check if substring of strings matches to patterns.
For example I have strings List (or array):
def Errors = ['File xyz cannot be created: No space left on device', 'File kjh has errors: some_error']
Then I have list of strings, for example def Patterns = ['Tests failed', 'No space left on device', 'Something goes wrong', ...some strings... ]
I would like to check if some elements of List Patterns are substrings of  Errors elements .
In that example it should return true, because Patterns has No space left on device and Errors has 'File xyz cannot be created: No space left on device'.
I know how to write it very ulgy and not efficient by using two for loops and method contains, but I know that Groovy has much more powerfull built-in methods. I have tried with findAll(), but it doesnt worked at all.
Do you have any ideas? Is there any way to make it more clever?

A: Explicitly naming pattern and error:
patterns.find { pattern -> errors.find { error -> error.contains(pattern) } }  // -> No space left on device
patterns.any { pattern -> errors.find { error -> error.contains(pattern) } } // -> true

depending on what/how many you want to find.
Or even shorter:
patterns.find { errors.find { error -> error.contains(it) } }
patterns.any { errors.find { error -> error.contains(it) } }


text:
Q: Wagtail Feedback form in homepage Tell me how to get the Wagtail form not in its separate template but on the homepage, since I do not need lending and another page. I can not find how to specify it in the get_context of the Home model

A: This is very similar to the question/answer about putting a form on every page.
Nonetheless, here is a way to implement this solution.
Example
In your my_app/models.py -
class HomePage(Page):
    """A Page model that represents the home page at the root of all pages."""

    # must have way to know WHICH FormPage to use, this makes it user editable
    form_page = models.ForeignKey(
        'wagtailcore.Page',
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        related_name='embedded_form_page',
        help_text='Select a Form that will be embedded on this page.')

    # ... all other fields

    def get_context(self, request, *args, **kwargs):
        """Add a renderable form to the page's context if form_page is set."""
        # context = super(HomePage, self).get_context(request, *args, **kwargs) # python 2.7 syntax
        context = super().get_context(request, *args, **kwargs)
        if self.form_page:
            form_page = self.form_page.specific  # must get the specific page
            # form will be a renderable form as per the dedicated form pages
            form = form_page.get_form(page=form_page, user=request.user)
            context['form'] = form
        return context

    content_panels = Page.content_panels + [
        PageChooserPanel('form_page', ['base.FormPage']), # Important: ensure only a FormPage model can be selected
        #... other fields
    ]

Then in your template my_app/templates/my_app/home_page.html
<div>
  {% if self.form_page %}
    <form action="{% pageurl self.form_page %}" method="POST" role="form">
      {% csrf_token %}
      {{ form.as_p }} {# form is avaialable in the context #}
      <input type="submit">
    </form>
  {% endif %}
</div>

Explanation

*

*First we provide a way to know which FormPage we want to render, we could assume by just grabbing the first one with FormPage.objects.get() but this is bad practice and could be unreliable. This is why we have added a ForeignKey to wagtailcore.Page - note we do not link to our FormPage model here.

*Then we restrict the linking inside the PageChooserPanel, in the example our FormPage model is located in the base app, hence ['base.FormPage].

*Then we override the get_context method, the only real reason we need to do this as it gets us the current request and FormPage.getForm needs the current request to be used.

*Finally, we update our template following the form rendering example in the docs pretty closely. With the difference being that our POST URL for the form is actually the form_page not the current page (homePage).

*Important Note: The form actually POSTS to the form page, not your home page, this means that we do not need to handle any kind of POST request to the home_page. It is a simple solution but it means that the landing page will be rendered ad the form page's URL.


text:
Q: Uncaught exception undefined within promise I have trouble correcting an error in my script, the console simply states "uncaught exception: undefined". Could you help me to identify the source of the problem ?
General explanation: I am coding a "copy to clipboard" share-button for a web-app. When the button is pressed, a link get generated and copied to the user clipboard. The link generation is dependent on external factors, reports that are stored in an Oracle database. There is an array named Reports that keeps track of them, but it needs to be up to date to generate a functional sharing-link. The anonymous function getterReports does it in an asynchronous way (JQuery + AJAX).
In order to copy my data to the clipboard, I am using the method described in this link: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
A snackbar (share_bar) is displayed on the screen to indicate that the operation is over.
Here is the raw code:
function copySharingURLToClipboard() {
    let share_bar = document.getElementById("modal_share");

    //getterReports ensures that the "Reports" array of reports objects is properly updated beforehand (AJAX <-> Database)
    getterReports().then(function () { //this ".then" ensurea that the main code is only executed after getterReports is over
        let report = getSavedReport(); //finds a report object by iterating the "Reports" array

        if (report == undefined) { //no saved report were found
            //snackbar related code :
            document.getElementById("popup_message").innerHTML = "Temporary reports cannot be shared: please save your report first.";
            share_bar.style.backgroundColor = "red";
            share_bar.classList.add('show');//launching the fade-in fade-out animation from the associated css class
            setTimeout(function () { share_bar.classList.remove('show'); }, 4200);//removing the class after the animation is done
        }
        else {
            let data = BaseURL + "/DisplayReportPage.aspx?id=" + report.id; //generating the string that we want to copy in the clipboard
            navigator.clipboard.writeText(data).then(function () {
                /* success */
                //snackbar related code :
                document.getElementById("popup_message").innerHTML = "URL copied to the clipboard successfully";
                share_bar.style.backgroundColor = "lightgreen";
                share_bar.classList.add('show');//launching the fade-in fade-out animation from the associated css class
                setTimeout(function () { share_bar.classList.remove("show"); }, 4200); //removing the class after the animation (it takes 4s + eventual minor latency)
            }, function () {
                /* failure case */
            });
        }
    });
}

During the execution of copySharingURLToClipboard(), the "uncaught exception: undefined" error happens in the following line, at ".then":
navigator.clipboard.writeText(data).then(function () {

My Web-app doesn't crash though, but the code is simply skipped. The error is only displayed when going step by step in devtool (otherwise the portion of the code is simply skipped without any error message). My Firefox browser is up to date.
All involved function are working fine in other part of the code. I am confident in the fact that getterReports() is working fine on its own. The same is true for the copy to clipboard part of copySharingURLToClipboard(), without the getterReports() updating the "Reports" array, it works fine (but its results are not up to date obviously):
function copySharingURLToClipboard() {
    let share_bar = document.getElementById("modal_share");

    //getterReports ensures that the "Reports" array is properly updated beforehand (AJAX <-> Database)
        let report = getSavedReport(); //finds a report object by iterating the "Reports" array

        if (report == undefined) { //no saved report were found
            //snackbar related code :
            document.getElementById("popup_message").innerHTML = "Temporary reports cannot be shared: please save your report first.";
            share_bar.style.backgroundColor = "red";
            share_bar.classList.add('show');//launching the fade-in fade-out animation from the associated css class
            setTimeout(function () { share_bar.classList.remove('show'); }, 4200);//removing the class after the animation is done
        }
        else {
            let data = BaseURL + "/DisplayReportPage.aspx?id=" + report.id; //generating the string that we want to copy in the clipboard
            navigator.clipboard.writeText(data).then(function () {
                /* success */
                //snackbar related code :
                document.getElementById("popup_message").innerHTML = "URL copied to the clipboard successfully";
                share_bar.style.backgroundColor = "lightgreen";
                share_bar.classList.add('show');//launching the fade-in fade-out animation from the associated css class
                setTimeout(function () { share_bar.classList.remove("show"); }, 4200); //removing the class after the animation (it takes 4s + eventual minor latency)
            }, function () {
                /* failure case */
            });
        }
}

Am I missing something simple ? A syntax error maybe ?

A: Firefox does not allow async copy-to-clipboard functionality.
Calling navigator.clipboard.writeText() in a promise resolve or an async function does not work intentionally. The code is working properly on other browsers.
After some research, it appears that there is still no available alternative implementation on Firefox. The logic of the project as a whole needs to be adapted in order to not use asynchronous functions when copying something in the clipboard.


text:
Q: Compress images on client side before uploading Does anyone know of any free script that compresses JPG, GIF and PNG files as much as possible?

A: I'm late to the party, but this solution worked for me quite well. Based on this library, you can use a function lik this - setting the image, quality, max-width, and output format (jepg,png):
function compress(source_img_obj, quality, maxWidth, output_format){
    var mime_type = "image/jpeg";
    if(typeof output_format !== "undefined" && output_format=="png"){
        mime_type = "image/png";
    }

    maxWidth = maxWidth || 1000;
    var natW = source_img_obj.naturalWidth;
    var natH = source_img_obj.naturalHeight;
    var ratio = natH / natW;
    if (natW > maxWidth) {
        natW = maxWidth;
        natH = ratio * maxWidth;
    }

    var cvs = document.createElement('canvas');
    cvs.width = natW;
    cvs.height = natH;

    var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
    var newImageData = cvs.toDataURL(mime_type, quality/100);
    var result_image_obj = new Image();
    result_image_obj.src = newImageData;
    return result_image_obj;
}

A: I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!
You can try the demo here : http://makeitsolutions.com/labs/jic
and get the sources here : https://github.com/brunobar79/J-I-C

A: I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html
The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...
However, I'm not sure about using canvas to compress images, but you can certainly resize them.

A: You might be able to resize the image with canvas and export it using dataURI. Not sure about compression, though.
Take a look at this: Resizing an image in an HTML5 canvas

A: If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.


text:
Q: What dimensions would L1 in this 433MHz tank circuit receiver be if it is actually 1.5 turns? Specifically, this circuit from Elektor:

The asterisk denotes that L1 in this 433MHz receiver circuit would be 1.5 turns. If that is accurate, what would the dimensions of the inductor air core be? You would need the coil diameter, wire diameter, and the coil length.
My thought is that 1.5 turns seems inaccurate, so if you have suggestions as to what the inductance should actually be here, that would be great as well. I considered 67.55, but that does not appear to resonate correctly at 433MHz though.

A: To resonate a printed coil or wired coil with 2pF at 433 MHz , you can't use a ground plane, which ends up adding to the 2pF significantly.
You have to decide if you want it shielded, coplanar, spiral formed on a screw (metric or imperial) or square printed on FR4.  So you have a lot of options but 1.5 turns sounds right for an air core with ~0.6" diameter

*

*If you want some immunity from crosstalk and magnet interference then you design it into a loose cavity as a shield to make it 2 pF to the shield.

*If you wanted a printed square coil with no ground plane then it would be:

*

*3 square turns coplanar 64.65 nH then add 0.8nH/mm for feed tracks that are not paired, less if paired as the inductance cancels.

8mm OD , 3 mm ID
0.5mm W, 0.5mm S

*Another method is to use a plastic screw with a wire diameter that fills the thread with an almost perfect helix.

*Here with no gap, except the magnetic wire coating in a spiral.

*Next: With larger solid stamped copper loops, I have seen precision coils inside a 4 walled shield soldered into a PCB as a high Q LC resonant accurate filter, where the tilt angle slightly tunes C (pf) with ~ 3/4 turn

simulate this circuit – Schematic created using CircuitLab
These are 5 options.


text:
Q: Webpack not reading my html navigation I'm creating a component in my webpack and I'm receiving this error:
ERROR in ./src/components/MainNav.js
Module build failed: SyntaxError: Unterminated JSX contents (121:12)
  ReactDOM.render(
>    <MainNav/>,
               ^
 document.getElementById('MainNavigation'));

The error is saying I need to remove the comma after , but the comma certainly belongs there.  I'm thinking there is another syntax error in my html or I have elements that need to be modified in order to be read by my webpack. Not sure what's wrong????
Below is my component:
        export class MainNav extends React.Component {
          render() {
            return (

        //     Brand and toggle get grouped for better mobile display

              <button type="button" className="navbar-toggle
collapsed" data-toggle="collapse" data-target="#bs-example-navbar-
collapse-1" aria-expanded="false">
                Toggle navigation

              </button>

        //     Collect the nav links, forms, and other content for
toggling

                              Tools

                     Welcome Back:

                    User ID:

User:

Company ID:

Company:

Logout

                // Sidebar

Shipments

All Documents

  All Messages 33

  Reports

 Dashboard

  Users

Invoicing & Statements

 Status Key

 Wittwer Contacts

  Warehouse

Log Out

               //  #sidebar-wrapper

                // Page Content

           );
          }
         }

        ReactDOM.render(
          <MainNav/>,
          document.getElementById('MainNavigation')
        );

A: When pasted the MainNav code into Visual Studio Code I received some errors indicating there was missing closing
 tags and unterminated string literal for className and href attribute values. I added two
 at the very end of the component render HTML as well as remove line breaks from attribute string values and it was able to render successfully. I also had to remove a style attribute, but that could simply be the way CodeSandbox renders React.
Here is a CodeSandbox showing the component rendering successfully (without styles).
Here is the full code that I was able to get to render:
export class MainNav extends React.Component {
  render() {
    return (

            // Brand and toggle get grouped for better mobile display

              <button
                type="button"
                className="navbar-toggle collapsed"
                data-toggle="collapse"
                data-target="#bs-example-navbar-collapse-1"
                aria-expanded="false"
              >
                Toggle navigation

              </button>

            // Collect the nav links, forms, and other content for toggling

                        {' '}
                        Tools

                     Welcome Back:

                      User ID:

                      User:

                      Company ID:

                      Company:

                      Logout

          // Sidebar

                  Shipments

                  All
                  Documents

                   All
                  Messages 33{' '}

                  {' '}
                  Reports

                  {' '}
                  Dashboard

                   Users

                  Invoicing
                  & Statements

                  {' '}
                  Status Key

                   Wittwer
                  Contacts

                   Warehouse

                  Log Out

          // #sidebar-wrapper // Page Content

    );
  }
}

ReactDOM.render(
    <MainNav />,
    document.getElementById('MainNavigation')
);

Hopefully that helps!


text:
Q: Recovering file from bad synchronization I am using Ubuntu One file synchronization on two computers. Both systems were disconnected from the Ubuntu One service for some days and changes were made to the same file on both systems. On one system the changes were insignificant, something like the file being touched or something similar. On the other system there were significant changes. Both of the systems reconnected to the file synchronization service at about the same time and Ubuntu One overwrote the file with all of the changes. There were no conflict files in this case. I would have hoped for and expected a conflict.
It seems like there should be something I can do about this, that the service wouldn't just overwrite files without some way of restoring old versions. Revision history is supposed to be a strength of couchdb. Can I use this strength to restore my files?

A: Versioning is a strength of CouchDB, but CouchDB is not used by file synchronization.
However, conflicts are handled gracefully, albeit not entirely user friendly yet. In the same directory as your original file, you will find files called filename.u1conflict*, like mydocument.odf.u1conflict and mydocument.odf.u1conflict2, etc. Those are the original conflict files, so you can just rename and use them as before.


text:
Q: skipping if{} even though the condition is true? I have no idea what went wrong, but if statement is skipping its statement even though the condition is clearly true. I checked with MsgBox or ToolTip right before the if statement to check that toughEnemy does equal to false. You can see the log, and the code skips from line 55 to 60.. I know that there is a flow in my code not ahk, but I can't find it.
Any help? thanks.
Gosub, CheckEnemyBlackList

if (tughEnemy = false) {
MsgBox, %toughEnemy%
    mouseX := 575
    break ; this statement is in a loop.
}

CheckEnemyBlackList:
Loop, read, EnemyBlackList.txt
{
    if (A_LoopReadLine = enemyID) {
    toughEnemy = true
    }
    else {
    toughEnemy = false
    }
}
return

below are the log
166: Loop,read,EnemyBlackList.txt
168: if (A_LoopReadLine = enemyID)
172: toughEnemy = false
173: }
174: MsgBox,%A_LoopReadLine% %toughEnemy% (0.75)
175: }
176: Return
055: if (toughEnemy = false)
060: }

A: try changing these lines:
toughEnemy = true
toughEnemy = false

to this:
toughEnemy := true
toughEnemy := false

reference:

*

*Autohotkey Help > Basic Usage and Syntax > Variables and Expressions > Variables > Storing values in variables


text:
Q: How do I get a button press to instantly run it's if statement this is my first time using stack overflow and I'm relatively new to python as well, I'm running a while=true statement checking for temp and also checking for button presses, the problem is I have to hold the button until it's finished getting the temp and checks if the button is pressed, how do I make it so when I click the button it will instantly run it's bit of code?
Thanks- beginner
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
import time
b = 38
r = 40
import Freenove_DHT as DHT
DHTPin = 11
dht = DHT.DHT(DHTPin)
Hitemp = 75
Lotemp = 70
GPIO.setup(b, GPIO.OUT)
GPIO.setup(r, GPIO.OUT)
GPIO.setwarnings(False)
b1 = 31
b2 = 32
b3 = 18
GPIO.setup(b1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(b3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(b2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while(True):
            chk = dht.readDHT11()     #read DHT11 and get a return value.
            time.sleep(0.1)
            Ctemp = float(("%.2f \n"%(dht.temperature)))
            Ftemp = 1.8*(Ctemp) + 32
            print (Ftemp)
            if Ftemp > Hitemp:
                GPIO.output(b, GPIO.HIGH)
                GPIO.output(r, GPIO.LOW)
            elif Ftemp < Lotemp:
                GPIO.output(r, GPIO.HIGH)
                GPIO.output(b, GPIO.LOW)
            else:
                GPIO.output(r, GPIO.LOW)
                GPIO.output(b, GPIO.LOW)
            if GPIO.input(b1)==GPIO.HIGH:
                print("Button Press1")
            if GPIO.input(b2)==GPIO.HIGH:
                print("Button Press2")
            if GPIO.input(b3)==GPIO.HIGH:
                print("Button Press3")
            time.sleep(1)


text:
Q: How to find the nearest larger number that is divisible by X Javascript I have a math problem like this:
When I enter a number, I find the nearest larger number that is divisible by a number x
Example: x = 50
Input = 20 => output = 50
Input = 67 => output = 100
Input = 200 => output = 200
Input = 289 => output = 300
Input = 999 => output = 1000
.......
I have a function below, but is there a way to make it faster?

console.log(roundNumber(199));

function roundNumber(n) {
  let x = 50;
  let flg = false;
  while (flg === false) {
    if (n > x) {
      x += 50;
    } else {
      flg = true;
    }
  }
  return x;
}

A: Yes, you can divide the input value by 50, take the "floor", add 1, and then multiply by 50.
function roundNumber(n) {
  let x = 50;
  return (Math.floor((n + x - 1) / x)) * 50;
}

Whether this will be much faster is kind-of irrelevant, unless for some reason you're performing this operation thousands and thousands of times over a short interval.


text:
Q: Push/Fetch command for Git in QtCreator works only in Remotes-menu I'm currently fighting with QtCreator 2.5.0 and Git. I initialized a local repo in my project's root-directory. After that I added my remote repo on GitHub (SSH key etc. - all set). For some reason though QtCreator refuses to push/fetch my code to the remote repo when I use Tools->Git->Push/Fetch. However if I go to Tool->Git->Remotes... and pus/fetch from there it is working. Needless to say this is at least for me a very strange behaviour. The pushing from inside my terminal is also not an issue and works like a charm.
Here is what I've done so far:

*

*I've checked with git in terminal to see if everything is set as you can see below.
USER:~/QtProjects/TestProject$ git remote -v
TestProject git@github.com:USERNAME/TestProject.git (fetch)
TestProject git@github.com:USERNAME/TestProject.git (push)

*Pushed/Fetched a couple of times in terminal with success (result was also visible on GitHub/local repo)

*Pushed/Fetched a couple of times in Remotes-menu of QtCreator with success (result was also visible on GitHub/local repo):
21:46 Executing in /home/USER/QtProjects/TestProject: /usr/bin/git push TestProject
Everything up-to-date
The command '/usr/bin/git' finished successfully.

*Pushed/Fetched a couple of times using Tools->Git->Push/Fetch with failure.

Now I've noticed that when pushing using Tools->Git->Push/Fetch I get an empty string where my repo's name should be standing as displayed above along with the good old error of a missing push destination (below I've marked it with MISSING_REPO_NAME_HERE):
21:46 Executing in /home/redbaron/QtProjects/HskaCompiler: /usr/bin/git push MISSING_REPO_NAME_HERE
fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using

git remote add <name> <url>

and then push using the remote name

git push <name>

The command '/usr/bin/git' terminated with exit code 128.

Has anyone experienced something like this and maybe know how to fix it? I recently switched from Ubuntu 12.04 LTS 32bit with don't know which version of QtCreator (I guess the latest in the repos of Precise) to Debian Wheezy 7.6 64bit. In Ubuntu I didn't encounter such an issue. The most interesting thing here is that what QtCreator actually does is call git remote -v the same way I do - in the project's root directory. In one case (Remotes-menu) it works, in the other - not.

A: It seems that this is some kind of a bug either in Qt Creator or git (at least the version that I'm using), or both.


text:
Q: In R: replacing specific factor in a dataframe with another existing factor I have a large data frame with a variable 'home_ownership' which can take the factors : 'own', 'mortgage', 'none', 'other'
I want to replace the values which are 'none' to 'other'.
I tried
df$home_ownership[df$home_owneship == "none"] <- "other"

which runs without an error.
But then when I do table(df$home_ownership) I still get a count of 46 for "none" Whilst I was expecting it (and wanting) it to have a count of 0.

A: there's a typo in
df$home_ownership[df$home_owneship == "none"] <- "other"

with the missing r it should do what you want ;)
--
But if you're really talking about the levels of a factor this should help:
levels(df$home_ownership)[levels(df$home_ownership)=="none"] <- "other"

or use factor() again after replacing the value.
For renaming levels look here.


text:
Q: Obfuscating Android activity names Is there any way I can obfuscate the names of my Android activities? I would like to be able to hide them from view, if someone were to attempt to reverse engineer my APK. Of course, I could simply manually rename them all with nonsense names and change the manifest as well, but is there any other way?

A: I think what you're looking for is ProGuard.


text:
Q: stdin restoring after processing I have a function. I use pipe() and then change stdin and stdout with close() and dup(). I am trying to save the handle, but something goes wrong.
N-number of elements are in array **arr, which is an array of arguments for the shell's pipe. *i is used to index the elements in **arr.
int extraFd;

int conveer(char **arr,int * i,int N){
    char **args = NULL;
    key_t target_pid;
    int j = 0,fd[2];

    while((*i) < N && strcmp(arr[*i],"|") &&
        strcmp(arr[*i],"<")   &&
        strcmp(arr[*i],">")   &&
        strcmp(arr[*i],">>")  &&
        strcmp(arr[*i],"&&")  &&
        strcmp(arr[*i],"&")   &&
        strcmp(arr[*i],";")   &&
        strcmp(arr[*i],"||")  &&
        strcmp(arr[*i],"(")   ){
        j++;
        args = realloc(args,sizeof(char *) * j);
        args[j-1] = arr[*i];
        (*i)++;
    }
    args = realloc(args,sizeof(char *) * (j+1));
    args[j] = NULL;

    if( (*i) < N && strcmp(arr[(*i)],"|") == 0){
        (*i)++;
        pipe(fd);
        if ( (target_pid = fork() ) ){
            close(fd[0]);
            dup2(fd[1],1);
            close(fd[1]);
            execvp(args[0],args);
        }
        else{
            close(fd[1]);
            close(0);
            dup(fd[0]);
            close(fd[0]);
            return conveer(arr,i,N);
        }
    }
    else{
        if ( target_pid = fork() ){
            execvp(args[0],args);
        }
        else {
            close(0);
            dup2(extraFd,0);
            close(extraFd);
            return 1;
        }
    }
}

...
extraFd = dup(0);
check = conveer(arr,&i,N);
...

The function conveer should process the input, which is a string, but it just terminates without processing anything. What's wrong?


text:
Q: How to add password parameter field without showing values via cloudformation? I will be taking few inputs when i'm creating the cloudformation stack. Cloudformation stack will create a SSM document (AWS systems manager) and I want to give password as an input parameter to the SSM document before the execution.
"parameters": {
              "sourceAMIid": {
              "type": "String",
              "description": "Source/Base AMI to be used for generating your Automated AMI",
              "default": { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "HVM64"]}
                       },
               "Username": {
                           "type": "String",
                           "description": "account username/email",
                           "default": "none"
                       },
                       "password": {
                           "type": "String",
                           "description": "account password",
                           "default": "none"
                       },

                       "productName": {
                           "type": "String",
                           "description": "The syntax of this parameter is ProductName-ProductVersion.",
                           "default": {
                               "Ref": "productName"
                    }
       }
}

When i enter the password in this field it will show the exact word as it is. is there any way that i can define password parameter to display as below

A: Yes you can mask your password using cloud formation template.All you need to is set "NoEcho" to "true" inside parameters as shown below.Refer to this and Using Input Parameters with NoEcho for Credentials in this for more information.
"Parameters" : {
  "DBPort" : {
    "Default" : "3306",
    "Description" : "TCP/IP port for the database",
    "Type" : "Number",
    "MinValue" : "1150",
    "MaxValue" : "65535"
  },
  "DBPwd" : {
    "NoEcho" : "true",
    "Description" : "The database admin account password",
    "Type" : "String",
    "MinLength" : "1",
    "MaxLength" : "41",
    "AllowedPattern" : "^[a-zA-Z0-9]*$"
  }
}

A: Using the terminal, this can be accomplished by using bash and read -s -p.
In the example below I have a Makefile, which reads the password, but does not echo the input to the terminal.
The Make Command
make create-test

Makefile
create-test: s3 delete-test
     @read -s -p "Enter DB Root Password: "  pswd; \
     aws cloudformation create-stack --stack-name test --template-body file://master.yaml --parameters ParameterKey=DBRootPassword,ParameterValue=$$pswd


text:
Q: Can we ignore the ssl validation in NSMutableURLRequest? I am very new to IOS development, I wish to know if it possible to ignore ssl validation for "NSMutableURLRequest" class. If so please guide me.  I have ignored the SLL validation through delegate by overriding
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;

I wish to ignore the SLL validation without Delegate.
my code snippet
 NSString *username = _userName.text;
    NSString *password = _password.text;

    //HTTP Basic Authentication
    NSString *authenticationString = [NSString stringWithFormat:@"%@:%@", username, password];
    NSData *authenticationData = [authenticationString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authenticationValue = [authenticationData base64Encoding];

    //Set up your request
    NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:url];

                                                                             // Set your user login credentials
     [request1 setValue:[NSString stringWithFormat:@"Basic %@", authenticationValue] forHTTPHeaderField:@"Authorization"];

                                                                             // Send your request asynchronously
      [NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responseCode, NSData *responseData, NSError *responseError) {
        if ([responseData length] > 0 && responseError == nil){
            //logic here
            NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            NSLog(@"RESPONSE WITHOUT DELEGATE: %@",newStr);
            [[ApplicationStorage applicationStorage] setUserName:_userName.text];
            [[ApplicationStorage applicationStorage] setUserName:_password.text];
            [[ApplicationStorage applicationStorage] setUserName:_serverAdd.text];
        }}];

Thanks
Amith

A: I think this has been answered before. You can try to add this to your AppDelegate.m, after @end
#if DEBUG

@implementation NSMutableURLRequest (NSURLRequestWithIgnoreSSL)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES;
}

@end

#endif


text:
Q: Como imprimir pulando linhas (cada variável em uma linha)? Como imprimir pulando linhas (cada  variável em uma linha)?
nome ='Paulo'
profissao = 'estudante'
escola = 'estadual dourado'
idade = 18

print 'Nome: '+nome   + 'Trabalho: '+profissao +  'Escola: ' +escola+   'Idade: '+str(idade)+ ' anos'

A: Assim:
nome ='Paulo'
profissao = 'estudante'
escola = 'estadual dourado'
idade = 18

print 'Nome: '+nome   + '\nTrabalho: '+profissao +  '\nEscola: ' +escola+   '\nIdade: '+str(idade)+ ' anos'

Nota para python3.x seria:
print('Nome: '+nome   + '\nTrabalho: '+profissao +  '\nEscola: ' +escola+   '\nIdade: '+str(idade)+ ' anos')

Mas atenção, a maneira mais aconselhada para este contexto é o format:
print 'Nome: {}\nTrabalho: {}\nEscola: {}\nIdade: {} anos'.format(nome, profissao, escola, idade)

A: Creio que você possa usar multiplos print. Na minha opinião, facilita a compreensão do seu código:
 #Define as variáveis de jeito mais organizado

 nome, idade = ("Wallace", 26)

 print "Nome: " + nome

 print "Idade: " + str(idade)

Veja funcionando no IDEONE
Você também pode usar a formatação de print combinada com o \n:
 print "Nome : %s\nIdade :%s" % (nome, idade)

Em sistemas operacionais Windows, você teria que usar \r\n ao invés de \n. Veja o porquê aqui:

*

*Qual é a diferença entre "\n" e "\r\n" (caracteres especiais para quebra de linha)?

A: print 'Nome: '+nome + '\n'  + 'Trabalho: '+profissao + '\n' + 'Escola: ' +escola+ '\n' + 'Idade: '+str(idade)+ ' anos'

Basta usar o caractere   \n   no locais da frase que você quiser pular a linha. Cada   \n  é uma linha pulada!


text:
Q: Execution failed for task ':app:transformClassesWithMultidexlistForDebug' in Android Studio 2.3 I can build my project but can not run the app. When executing app it gives me error like
Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.android.multidex.ClassReferenceListBuilder with arguments {/home/Git_Projects/Test1/app/build/intermediates/multi-dex/debug/componentClasses.jar /home/Git_Projects/Test1/app/build/intermediates/transforms/jarMerging/debug/jars/1/1f/combined.jar}

I tried to clean and rebuild project and Invalidate Catche and Restart. But, nothing helped me.
build.gradle (app)
apply plugin: 'com.android.application'

android {
    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.app.test1"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
    maven { url 'https://github.com/Kaustubh-Deshmukh/progressbar_repo/raw/master' }

    maven { url 'https://dl.bintray.com/yazeed44/maven' }
    }

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.google.android.gms:play-services-places:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-vision:10.0.1'

    compile 'com.github.clans:fab:1.6.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.1.1'
    compile 'com.android.support:appcompat-v7:26.0.0'
    compile 'com.android.support:design:26.0.0'
    compile 'com.android.support:recyclerview-v7:26.0.0'
    compile 'com.android.support:cardview-v7:26.0.0'
    compile 'com.android.support:support-v4:26.0.0'
    compile 'com.android.support:support-annotations:26.0.0'
    compile 'com.android.support:percent:26.0.0'
    compile 'com.android.support:support-v13:26.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    compile 'com.facebook.fresco:fresco:1.5.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.kontaktio:sdk:3.3.2'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

    testCompile 'junit:junit:4.12'
}

If I randomly remove some dependencies, then it executes fine. Does large app size creating problem to execute app ?
I am using android studio 2.3 and java-8-openjdk-amd64 and ubuntu 16.04
One strange thing : Everything was working correct before executing command
apt-get update

I am searching from days but nothing seems work.

A: As from your build.gradle file you have two versions for
compile 'com.android.support:support
Try using only one of the following:
compile 'com.android.support:support-v4:26.0.0'
compile 'com.android.support:support-v13:26.0.0'

A: Try to add below to build.gradle
compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
}

Try to build by command line
gradle clean assembleDebug

A: After updating Android Studio from 2.3.0 to 3.0.1 , my problem solved.
Now, it works perfect.


text:
Q: Is the inverse of an $\alpha$-Hölder function a $\beta$-Hölder function, for some $\beta$? I have a linearization of an one-dimensional map, given by the Hartman-Grobman Theorem:
$\pi = H^{-1} \circ \lambda\circ H$.
I know that $H$ is $\mathcal{C}^{1,\alpha}$.
Can I say that $H^{-1}$ is $\beta$-Hölder, for some $\beta$?


text:
Q: Form validation and storing with php I have a task in which I am required to build a very simple website in which the user is prompted to fill a form and submit it. After that, a validation check will be made and a message of success will be presented to him (maybe in a different page). The fields of the table in which the form's inputs are going to be stored are the following:
TABLE inquiries (
inquiry_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
submit_date DATETIME,
first_name VARCHAR(35),
last_name VARCHAR(35),
address VARCHAR(255),
postcode VARCHAR(8),
email VARCHAR(254),
phone VARCHAR(11),
wedding_date DATE,
wedding_location VARCHAR(50),
special_req TEXT
);

So, basically my form includes everything from above, but inquiry_id and submit_date.
Initially, I validate my form by putting in my HTML code the following
<form name = "Order Form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">

and in a php script before I make all the ckecks. This works fine.
My main problem is in storing these inputs in the given DB. Upon now, I've tried this:
a)Before closing the form, I have this php script:
        $connection=mysqli_connect("serverName","username","password","DB");
        if (mysqli_connect_errno())
        {
           echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
       date_default_timezone_set('Europe/London');
//I use a datepicker with the format mm/dd/yyy, but I want the format yyyy/mm/dd TIMESTAMP
       $currentDate = date('Y/m/d h:i:s a', time());
       $date = date('Y-m-d');
       mysqli_query($connection,"INSERT INTO inquiries
        (submit_date, first_name, last_name, address,    postcode, email, phone,  wedding_date,     wedding_location, special_req)
        VALUES
        ('$currentDate', '$firstName', '$lastName', '$street', '$postcode', '$email',  '$mobileNumber', '$date', '$city', '$comments')");
       mysqli_close($connection);

This doesn't work...
b) I created a new php file and named it "DBStore.php" in order to call it in the previous form, so now action="DBStore.php". Unfortunately, I don't have access to the DB to see if the inputs are stored properly, but the only thing I get is a blank page.
I want to combine both the validation and the store in one file, if it's possible.
How can I do the previous (both validation and storing, with a presentation of a proper message)?
I would prefer to keep in both cases php coding.
The code for the validation is:
<?php //code retrieved and customized from: http://www.w3schools.com/php/php_form_validation.asp and http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required
              // define variables and set to empty values
            $firstNameError = $lastNameError = $streetError = $cityError = $postcodeError = $emailError = $mobileNumberError = $dateError = "";
            $firstName = $lastName = $street = $city = $postcode = $email = $mobileNumber = $date = "";
            if ($_SERVER["REQUEST_METHOD"] == "POST")
            {
                if (empty($_POST["firstName"]))
                {$firstNameError = "Please fill this field";}
                else
                {
                    $firstName = test_input($_POST["firstName"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$firstName))
                    {
                        $firstNameError = "Please use only letters and white spaces";
                    }
                }
                if (empty($_POST["lastName"]))
                {$lastNameError = "Please fill this field";}
                else
                {
                    $lastName = test_input($_POST["lastName"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$lastName))
                    {
                        $lastNameError = "Please use only letters and white spaces";
                    }
                }
                if (empty($_POST["street"]))
                {$streetError = "Please fill this field";}
                else
                {
                    // check if street address syntax is valid
                    $street = test_input($_POST["street"]);
                    if(!preg_match('/[^A-Za-z0-9]/', $street)){
                        $streetError = "Please use only letters, numbers and whitespaces";
                    }
                }
                if (empty($_POST["city"]))
                {$cityError = "Please fill this field";}
                else
                {
                    // check if city syntax is valid
                    $city = test_input($_POST["city"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$city))
                    {
                        $cityError = "Please use only letters and whitespaces";
                    }
                }
                if (empty($_POST["postcode"]))
                {$postcodeError = "Please fill this field";}
                else
                {
                    //check if postcode syntax is valid
                    $postcode = test_input($_POST["postcode"]);
                    if(!preg_match('/[^A-Za-z0-9]*$/', $postcode)){
                        $postcodeError = "Please use only letters, numbers and whitespace";
                    }
                }
                if (empty($_POST["email"]))
                {$emailError = "Please fill this field";}
                else
                {
                    $email = test_input($_POST["email"]);
                    // check if e-mail address syntax is valid
                    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
                    {
                        $emailError = "Please rewrite your email address in the format a@b.code";
                    }
                }
                if (empty($_POST["mobileNumber"]))
                {$mobileNumberError = "Please fill this field";}
                else
                {
                    $mobileNumber = test_input($_POST["mobileNumber"]);
                    // check if mobile number syntax is valid
                 if (!preg_match('/^\d+$/',$mobileNumber))
                    {
                    $mobileNumberError = "Please write only numbers";
                    }
                }
                if (empty($_POST["date"]))
                {$dateError = "Please fill this field";}
            //echo "I'm here";
            //exit();
        }
        function test_input($data)
        {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }
    ?>

The full HTML form is this:
<form name = "Order Form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">--></form>

                        * First name:

                        <input type = "text" name = "firstName" value = "<?php echo $_POST['firstName']; ?>"/>

                        <?php echo $firstNameError;?>

                        * Last name:
                        <input type = "text" name = "lastName" value = "<?php echo $_POST['lastName']; ?>"/>

                        <?php echo $lastNameError;?>

                        * Address:
                        <input type = "text" name = "street" value = "<?php echo $_POST['street']; ?>"/>

                        <?php echo $streetError;?>

                        * Postcode:
                        <input type = "text" name = "postcode" value = "<?php echo $_POST['postcode']; ?>"/>

                        "><?php echo $postcodeError;?>

                        * E-mail:
                        <input type = "text" name = "email" value = "<?php echo $_POST['email']; ?>"/>

                        "><?php echo $emailError;?>

                        * Contact number:
                        <input type = "text" name = "mobileNumber" value = "<?php echo $_POST['mobileNumber']; ?>"/>

                        <?php echo $mobileNumberError;?>

                        *Wedding date:
                        <input type = "text" name = "date" id ="date" value = "<?php echo $_POST['date']; ?>"/>

                        <?php echo $dateError;?>

                        * Wedding location:
                        <input type = "text" name = "city" value = "<?php echo $_POST['city']; ?>"/>

                        "><?php echo $cityError;?>

                         Leave your comments:
                        <textarea rows = "7" cols = "30" name = "comments" id = "comments" value = "<?php echo $_POST['comments']; ?>"/></textarea>

                <input type = "submit" name = "submit" value = "Submit Details" style ="margin-left: 145px;"/>
                <input type = "reset" value = "Clear Form"/>

</form>

Thanks :)


text:
Q: How to filter a dataframe, by getting everything in a df, MINUS another df? If I have this pandas dataframe:
data = [{'Name': 'Tom', 'Age': 42}, {'Name': 'Adam', 'Age': 25}
         ,{'Name': 'Bill', 'Age': 65}]

df = pd.DataFrame(data)

q = df[df['Name'] == 'Tom']

How can I filter df to get all of the rows of the dataframe, except for, what I filtered in q
So it should return {'Name': 'Adam', 'Age': 25} and {'Name': 'Bill', 'Age': 65}.
Thanks!

A: If possible, you can invert mask by != for not equal:
new = df[df['Name'] != 'Tom']
print (new)
   Name  Age
1  Adam   25
2  Bill   65

Another idea is remove index values of q from original DataFrame, but it working well only if unique index values:
q = df[df['Name'] == 'Tom']
new = df.drop(q.index)
print (new)
   Name  Age
1  Adam   25
2  Bill   65

A: For this you can use LOC and ~. It will help you to "filter" your DF
df = df.loc[~df.Name.isin(['Adam']),:]


text:
Q: Compile css with Ruby Sass, via php I'm currently using https://github.com/richthegeek/phpsass
With every page load, I am doing the following:

*

*get list of scss files

*check if any of them are newer than the last time, if so:

*make an @import list and file_put_contents($importlist)

*instantiate PhpSass, give it the $importlist path: $css = $sass->toCss(pathtoImporterSass);

*write the css file:  file_put_contents($pathtocachefile, $css);

*and then, serve the css.

So, I am wondering how to do step 4 via Ruby, instead of phpSass.  PhpSass is working ok, but it has some limitations (doesnt understand all of sass functions, strips !important, etc )


text:
Q: Debug both javascript and c# in ASP.NET Core MVC using VS Code Is there a way to set breakpoints and debug javascript and c# at the same time in VS Code (on macOS)?
I have installed the chrome debugger extension and then created a new MVC app using dotnet new mvc.
But when I launch the app breakpoint are only hit in the C# files, they stay grayed out in the js files (site.js) because no symbols have been loaded.
These are my launch settings (the only thing I have modified is osx command because chrome is not my default browser on macOS):
"version": "0.2.0",
   "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            // If you have changed target frameworks, make sure to update the program path.
            "program": "${workspaceRoot}/bin/Debug/netcoreapp1.1/Foo.PhotoSite.dll",
            "args": [],
            "cwd": "${workspaceRoot}",
            "stopAtEntry": false,
            "internalConsoleOptions": "openOnSessionStart",
            "launchBrowser": {
                "enabled": true,
                "args": "${auto-detect-url}",
                "windows": {
                    "command": "cmd.exe",
                    "args": "/C start ${auto-detect-url}"
                },
                "osx": {
                    "command": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
                },
                "linux": {
                    "command": "xdg-open"
                }
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceRoot}/Views"
            }

A: serverReadyAction recommended over launchBrowser
if you create a new reactredux net core application with dotnet new reactredux -n testreactredux browser launches but still not debuggable until change action to debugWithChrome as following
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/testreactredux.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            "stopAtEntry": false,
            // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
            "serverReadyAction": {
                "action": "debugWithChrome", // <---- CHANGE HERE ( default is 'openExternally' )
                "pattern": "^\\s*Now listening on:\\s+(https?://\\S+)"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        }
    ]
}

this way if I place breakpoint on c# code debugger will hit

and either on javascript ( I used typescript tsx )

I noted that breakpoint on js code still gray at start but then it stop there correctly.

A: What you want to do is debug 2 different processes. With your configuration you debug the server. If you want to debug the browser as well you have 2 options.
First option, just start a second debug session. VS Code will automatically start multi-target debugging. You will want to start an "attach to chrome" session (see below for configuration sample) or "Launch chrome" session. After that you debug the chrome instance you picked or started and the server.
Second option, possibly more convenient if you do it a lot is to create a compound. Results in the same thing but you can start it with one click.
In this case you could remove your launch browser configurations that start your browser unless you attach to that instance.
To get it running you can try your browser configuration separately. Make chrome debugging work correctly (ignore the server) and then combine it in the compound.
Example with 2 chrome configurations for launching or attaching:
Configuration should look like this:
Please keep in mind that I took it from my Windows machine in case there are special notations for macOS or different debugging ports.
{
    "version": "0.2.0",
    "configurations": [
        {
            // ...your configuration for .NET Core here...
            // called .NET Core Launch (web)
        }
        {
            "type": "chrome",
            "request": "launch",
            "name": "LaunchChrome",
            "url": "http://localhost:8080",
            "webRoot": "${workspaceRoot}"
        },
        {
            // This one in case you manually start 2 debug sessions.
            // Like first .net core
            // then attach to the browser that was started.
            "type": "chrome",
            "request": "attach",
            "name": "AttachChrome",
            "port": 9222,
            "webRoot": "${workspaceRoot}"
        }
    ],
    "compounds": [
        {
            "name": "Debug MVC and Chrome",
            "configurations": [".NET Core Launch (web)", "LaunchChrome"]
        }
    ]
}

Essentially you use 2 different debugging extensions. The .NET debugger extension and the chrome debugger extension. Hence the 2 different configuration parts.
Reference:
Microsoft calls it "multitarget-debugging" in VS Code. See the docs here: https://code.visualstudio.com/docs/editor/debugging#_multitarget-debugging

A: Works fine changing action "openExternally" to "debugWithChrome".
Less code and more functional than composing with "compounds". Thanks to Lorenzo Delana!
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/testreactredux.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            "stopAtEntry": false,
            // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
            "serverReadyAction": {
                "action": "debugWithChrome", // <---- CHANGE HERE ( default is 'openExternally' )
                "pattern": "^\\s*Now listening on:\\s+(https?://\\S+)"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        }
    ]
}


text:
Q: Ubuntu 19.10 / 20.04 webcam crashing This is a follow up of this question: Merlin U740 USB 2.0 camera not working
Basically I have Merlin U740 USB 2.0 camera. I managed to make it work on Ubuntu 18.04 and it was working well until I upgraded to 19.10. A subsequent upgrade to 20.04 didn't make any difference and now the camera doesn't work.
It's recognised by the system and starts in Zoom, Slack and Cheese only to fail a few seconds later, causing Zoom to freeze / become unresponsive for a moment (up to 30s, other apps seem to handle it better). I tried all the USB ports available on my PC and it made no difference.
I ran the usual commands and here are the results:
lsmod | grep video

uvcvideo               98304  0
videobuf2_vmalloc      20480  1 uvcvideo
videobuf2_memops       20480  1 videobuf2_vmalloc
videobuf2_v4l2         24576  1 uvcvideo
videobuf2_common       49152  2 videobuf2_v4l2,uvcvideo
videodev              225280  3 videobuf2_v4l2,uvcvideo,videobuf2_common
mc                     53248  5 videodev,snd_usb_audio,videobuf2_v4l2,uvcvideo,videobuf2_common

lsusb

Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 010: ID 1410:1410 Novatel Wireless Merlin U740 (non-Vodafone)
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 1ea7:0064 SHARKOON Technologies GmbH 2.4G Mouse
Bus 001 Device 002: ID 046d:c534 Logitech, Inc. Unifying Receiver
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

dmesg -H

[May26 08:07] usb 3-4: USB disconnect, device number 2
[  +0.001971] uvcvideo: Failed to resubmit video URB (-19).
[  +0.003994] uvcvideo: Failed to resubmit video URB (-19).
[  +0.004001] uvcvideo: Failed to resubmit video URB (-19).
[  +0.003998] uvcvideo: Failed to resubmit video URB (-19).
[  +0.004001] uvcvideo: Failed to resubmit video URB (-19).
[  +0.334387] usb 3-4: new high-speed USB device number 9 using xhci_hcd
[  +0.113622] usb 3-4: New USB device found, idVendor=1410, idProduct=1410, bcdDevice= 0.00
[  +0.000003] usb 3-4: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[  +0.000001] usb 3-4: Product: USB 2.0 Camera
[  +0.000001] usb 3-4: Manufacturer: Sonix Technology Co., Ltd.
[  +0.010509] uvcvideo: Found UVC 1.00 device USB 2.0 Camera (1410:1410)
[  +0.025696] uvcvideo 3-4:1.0: Entity type for entity Extension 4 was not initialized!
[  +0.000002] uvcvideo 3-4:1.0: Entity type for entity Processing 3 was not initialized!
[  +0.000001] uvcvideo 3-4:1.0: Entity type for entity Camera 1 was not initialized!
[  +0.000059] input: USB 2.0 Camera: SD webcam 5160 as /devices/pci0000:00/0000:00:08.1/0000:09:00.3/usb3/3-4/3-4:1.0/input/input31
[  +0.013231] usb 3-4: 3:1: cannot get freq at ep 0x84
[  +0.022373] usb 3-4: USB disconnect, device number 9
[  +0.342659] usb 3-4: new high-speed USB device number 10 using xhci_hcd
[  +0.118345] usb 3-4: New USB device found, idVendor=1410, idProduct=1410, bcdDevice= 0.00
[  +0.000002] usb 3-4: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[  +0.000001] usb 3-4: Product: USB 2.0 Camera
[  +0.000002] usb 3-4: Manufacturer: Sonix Technology Co., Ltd.
[  +0.009629] uvcvideo: Found UVC 1.00 device USB 2.0 Camera (1410:1410)
[  +0.025813] uvcvideo 3-4:1.0: Entity type for entity Extension 4 was not initialized!
[  +0.000002] uvcvideo 3-4:1.0: Entity type for entity Processing 3 was not initialized!
[  +0.000001] uvcvideo 3-4:1.0: Entity type for entity Camera 1 was not initialized!
[  +0.000058] input: USB 2.0 Camera: SD webcam 5160 as /devices/pci0000:00/0000:00:08.1/0000:09:00.3/usb3/3-4/3-4:1.0/input/input32
[  +0.013238] usb 3-4: 3:1: cannot get freq at ep 0x84
[  +0.203878] usb 3-4: 3:1: cannot get freq at ep 0x84
[  +0.012130] usb 3-4: 3:1: cannot get freq at ep 0x84

The camera doesn't seem damaged in any way, but maybe there's something wrong with the hardware itself?

A: I have Ubuntu 19.10 and faced this issue several days ago too. The reason is updating from 5.3.0-53 kernel to 5.3.0-55. As a workaround, you can choose 53 version in GRUB.
For 20.04 kernel version 5.6.15 should work: Webcam stopped working after recent kernel update


text:
Q: How can I process a file uploaded through an HTML form in Spray/Scala/Java? I have an application written using Spray, and I have a page which has an <input type="file" name="foo"> form element that gets POSTed to /fileUpload.
I have a Spray route set up to listen to the path /fileUpload using this code:
path("fileUpload") {
  get { ctx => {
    val request: HttpRequest = ctx.request
    //Process the file, somehow with request?
    ctx.complete("File Uploaded")
  }}
}

I can't figure out how to get the POST body and get a handle on the file, and I can't find any examples online.
It must be possible to receive a file and process it with Spray or even through simple Scala or Java, but I don't know how to do it.
Can anybody help?
Thanks!

A: It's possible with Spray, although I haven't checked if streaming works properly. I fiddled a bit and got this working:
  post {
    content(as[MultipartFormData]) {
      def extractOriginalText(formData: MultipartFormData): String = {
        formData.parts.mapValues { (bodyPart) =>
          bodyPart.content.map{
            (content) => new String(content.buffer)
          }
        }.values.flatten.foldLeft("")(_ + _)
      }
      formData =>
        _.complete(
          extractOriginalText(formData)
        );
    }

If you upload a plain text file to a service that has this code in it, it coughs the original text back up. I've got it running together with an ajax upload; it should also work with an old fashioned file upload form.
It seems to me that there must be an easier way to do this, particularly the deep nesting of the content is rather clunky. Let me know if you find a simplification.
UPDATE (thx akauppi):
entity(as[MultipartFormData]) { formData =>
  complete( formData.fields.map { _.entity.asString }.flatten.foldLeft("")(_ + _) )
}

A: I ended up using the code below. Wasn't too hard, but there really should have been a Spray sample available somewhere about this.
multipart/form-data forms must always be used (instead of the traditional application/x-www-form-urlencoded) if binary uploads are involved. More details here.
My requirements were:

*

*need to upload binary files of reasonably large size

*wanted to have metadata as fields (not embedded in URL or the upload's filename)

Some questions:

*

*is the way I'm managing errors the "best" way?

It's in the essence of REST API design to treat the client as a "human" (in debugging, we are), giving meaningful error messages in case something is wrong with the message.
post {
  // Note: We cannot use a regular 'return' to provide a routing mid-way. The last item matters, but we can
  // have a 'var' which collects the correct success / error info into it. It's a write-once variable.
  //
  var ret: Option[Route] = None

  // Multipart form
  //
  // To exercise this:
  //  $ curl -i -F "file=@filename.bin" -F "computer=MYPC" http://localhost:8080/your/route; echo
  //
  entity(as[MultipartFormData]) { formData =>
    val file = formData.get("file")
      // e.g. Some(
      //        BodyPart( HttpEntity( application/octet-stream, ...binary data...,
      //                    List(Content-Type: application/octet-stream, Content-Disposition: form-data; name=file; filename=<string>)))
    log.debug( s".file: $file")

    val computer = formData.get("computer")
    // e.g. Some( BodyPart( HttpEntity(text/plain; charset=UTF-8,MYPC), List(Content-Disposition: form-data; name=computer)))
    log.debug( s"computer: $computer" )

    // Note: The types are mentioned below simply to make code comprehension easier. Scala could deduce them.
    //
    for( file_bodypart: BodyPart <- file;
        computer_bodypart: BodyPart <- computer ) {
      // BodyPart: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.BodyPart

      val file_entity: HttpEntity = file_bodypart.entity
        //
        // HttpEntity: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.HttpEntity
        //
        // HttpData: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.HttpData

      log.debug( s"File entity length: ${file_entity.data.length}" )

      val file_bin= file_entity.data.toByteArray
      log.debug( s"File bin length: ${file_bin.length}" )

      val computer_name = computer_bodypart.entity.asString    //note: could give encoding as parameter
      log.debug( s"Computer name: $computer_name" )

      // We have the data here, pass it on to an actor and return OK
      //
      ...left out, application specific...

      ret = Some(complete("Got the file, thanks.")) // the string doesn't actually matter, we're just being polite
    }

    ret.getOrElse(
      complete( BadRequest, "Missing fields, expecting file=<binary>, computer=<string>" )
    )
  }
}

A: Ok, after trying to write a Spray Unmarshaller for multipart form data, I decided to just write a scala HttpServlet that would receive the form submission, and used Apache's FileUpload library to process the request:
class FileUploadServlet extends HttpServlet {

  override def doPost(request: HttpServletRequest, response: HttpServletResponse) {
    val contentType = request.getContentType
    val boundary = contentType.substring(contentType.indexOf("boundary=")+9)
    val multipartStream = new MultipartStream(request.getInputStream, boundary)

    // Do work with the multipart stream
  }

}

A: To grab the posted (possibly binary) file, and stick it somewhere temporarily, I used this:
  post {
    entity(as[MultipartFormData]) {
      formData => {
        val ftmp = File.createTempFile("upload", ".tmp", new File("/tmp"))
        val output = new FileOutputStream(ftmp)
        formData.fields.foreach(f => output.write(f.entity.data.toByteArray ) )
        output.close()
        complete("done, file in: " + ftmp.getName())
      }
    }
  }


text:
Q: Defining array bound with const int does not work I want to initialize an array based on how many lines there are in a text file, so that I can read the text data into the program, but I am having issues with the struct. I so far understand that I need to define the array bounds with a constant, which I've tried to do, but I get errors saying that I am not defining with an integral constant-expression, though I believe that is what I am doing.
I am using g++ to compile my code with the C++17 standard. Below I included only relevant code.
//tools.h

int findMaxID()
{
    std::ifstream fin("\data\items.txt");
    char ch;
    int z = 1;
    while(fin)
    {
        fin.get(ch);
        if(ch == '\n')
            z++;
    }
    return z;
}
const int MaxID = findMaxID();

// data.h

#include"tools.h"

struct ItemData
{
    public:
        unsigned int ID[::MaxID];
        char Name[::MaxID][32];
        char Type[::MaxID][8];
};

data.h:15:21: error: size of array 'ID' is not an integral constant-expression
   15 |   unsigned int ID[::MaxID];
      |                   ~~^~~~~
data.h:16:15: error: size of array 'Name' is not an integral constant-expression
   16 |   char Name[::MaxID][32];
      |             ~~^~~~~
data.h:17:15: error: size of array 'Type' is not an integral constant-expression
   17 |   char Type[::MaxID][8];

I'm stumped as to what to do. I've tried absolutely everything, I tried using vector instead of arrays, but I found it awkward and confusing when using it multi-dimensional, and I tried using a pointer to the value. Maybe I set it up wrong. All I know is that I've tried my absolute best to overcome this, but the problem doesn't seem to be in my reach to solve. I hope you can help me with this issue.

A: When designing data structures try and think of the single case first:
struct ItemData
{
    public:
        unsigned int ID;
        std::string Name;
        std::string Type;
};

Then treat these structures in aggregate separately:
std::vector<ItemData> items;

Where you can add entries to that quite easily with emplace_back by reading the data in and parsing it.

A: The array size must be a compile-time constant.
In this case your size variable takes the value at runtime and this is forbidden by the standard.
To resolve this problem try to use c++ utilities like std::string for an array of char, and std::vector for an array of other types.


text:
Q: Does kinetic energy warp spacetime? My interpretation of GR leads me to think that energy (namely kinetic) also adds to the curvature of space-time. Which, has raised a thought experiment. If a $10000$ kg ship closely passed a $1$ kg glass ball at $0.8c$ relative to the glass ball, would the glass ball be moved in the direction of the ship for the tiny fraction of a second that its passing by, more so than if the ship popped in and out of existence at rest for the same time period relative the glass ball?

A: The answer is yes, and this is actually an important point when considering extremely high-energy physics. As a result of this effect, gravity is the dominant interaction at sufficiently high energies, at least if we can trust the most straightforward extrapolation of the current foundations of physics. This is highlighted in 't Hooft (1987), "Graviton dominance in ultra-high-energy scattering," Physics Letters B 198: 61-63. The abstract says:

The scattering process of two pointlike particles at CM [center-of-mass] energies in the order of Planck units or beyond, is very well calculable using known laws of physics, because graviton exchange dominates over all other interaction processes. At energies much higher than the Planck mass black hole production sets in, accompanied by coherent emission of real gravitons.

A: Kinetic energy is part of the time-time component of the stress energy tensor, so by the Einstein field equations it does influence the curvature. However, the relationship is too complicated to justify a straightforward assertion that it adds to the curvature.
First, the curvature is a rank 4 tensor, not a scalar. So it has many independent components and increasing the KE may impact many of those components, often in opposite directions. So while it certainly changes the curvature what would it even mean to simply "add to the curvature"?
Second, an increase in the KE is always accompanied by an change in momentum also. The momentum will alter one or more of the time-space components of the stress energy tensor. Sometimes the momentum changes will roughly cancel the energy-based curvature changes, leading to minimal overall change in curvature.


text:
Q: How do I pass a value to a constructor in a class with an @Configuration annotation? I'm new to Spring and I'm trying to figure it out.Let's say I have such a class:
@Configuration
@ComponentScan("com.constructordi")
public class Config {
    private String details;

    Config(String details){ this.details=details; }

    @Bean
    public Engine engine() {
        return new Engine("v8", 5);
    }

    @Bean
    public Transmission transmission() {
        return new Transmission("sliding");
    }
}

I saw that we get the Bean in this way:
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Car car = context.getBean(Car.class);

That is, out of interest, I added myself to this example (In the example of this class, these lines were not there)
private String details;
Config(String details){ this.details=details; }

Because it is interesting to understand how we can pass the value there? Do I understand correctly that it will be necessary to use XML in such cases? I will be glad to help