text:
Q: How to create a custom metrics end point for Grafana using Spring Boot 2? I am trying to learn Grafana and creating application using Spring Boot 2, Prometheus and Grafana for metrics.
I need to create custom metrics for per day student creation count.
import com.demo.mockito.entity.StudentEntity;
import com.demo.mockito.service.StudentService;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {

    @Autowired
    private StudentRepository studentRepository;

    @Timed
    @GetMapping("studentEntity")
    public ResponseEntity<StudentEntity> studentEntity() {
        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setName("shri");
        studentEntity.setSurName("sharma");
        StudentEntity student = studentRepository.save(studentEntity); // <- need to create metrics of student.getRollNo()

        return ResponseEntity.ok(student);
    }
}

application.properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# Enable prometheus exporter
management.metrics.export.prometheus.enabled=true
# Enable prometheus end point
management.endpoints.web.exposure.include=prometheus
# enable percentile-based histogram for http requests
management.metrics.distribution.percentiles-histogram.http.server.requests=true
# http SLA histogram buckets
management.metrics.distribution.sla.http.server.requests=100ms,150ms,250ms,500ms,1s
# enable JVM metrics
management.metrics.enable.jvm=true
spring.application.name=test app
management.metrics.tags.application=${spring.application.name}
spring.app.jpa.properties.hibernate.hibernateDDL=create
spring.app.jpa.properties.hibernate.hibernateShowSql=true
spring.jpa.generate-ddl=true
spring.jpa.database.schema=student_db
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

build.gradle
plugins {
    id 'org.springframework.boot' version '2.3.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}
repositories {
    mavenCentral()
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'com.h2database:h2'
    runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
test {
    useJUnitPlatform()
}

Main Application:
package com.demo.mockito;
import io.micrometer.core.aop.TimedAspect;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;

@SpringBootApplication
public class SpringMockitoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringMockitoApplication.class, args);
    }

    // custom application name
    @Bean
    MeterRegistryCustomizer<MeterRegistry> configurer(
            @Value("${spring.application.name}") String applicationName) {
        return (registry) -> registry.config().commonTags("application", applicationName);
    }

    @Bean
    TimedAspect timedAspect(MeterRegistry registry) {
        return new TimedAspect(registry);
    }
}

I need to create custom actuator endpoint metrics for per day student creation count so that I can plot its graph using Grafana. The rollNo is an auto-generated field so it will give me a count of the total student.
How to create custom metrics in Spring Boot?
Thanks in advance.

A: Since you are working with Prometheus, a prometheusMeterRegistry bean is automatically registered.
In your Controller class, you need to autowire the prometheusMeterRegistry bean. The following will do:
@Autowired
MeterRegistry registry;

Then you can register a counter to the registry and increment it using
Counter counter = registry.counter(counterName);
counter.increment();

See Micrometer docs for more details.


text:
Q: Dynamically setting image in underscore template I'm currently using underscore templates to render a HTML list that displays a list of contacts.
The template looks something like this:

 Name: <=%data.name%>
 Name: <=%data.email%>
 <img class="avatar" src="<=%data.avatar%>">

The issue is, when I set the template data, the source of the image won't be known. Why? Because my data looks something like this:
contact = {
  name: string, // i.e. 'John Doe'
  email: string, // i.e 'john@doe.com'
  avatar: string // i.e. '11a93150-14d4-11e3'
}

The avatar is actually not a URL, rather a link to a remote database that needs fetching. Something like:
function getAvatar(uuid, cb) { // uuid is something like 11a93150-14d4-11e3
 window.db.getImageUrl(function(url) {
  cb(url); // url is something like http://foo.com/avatar.png
 });
}

Question is, is there a way to write my template so that instead of reading the avatar value of the contact object directly, I can embed a reference to a function like getAvatar that when the template is rendered, fetches the url to the image and sets the avatar image URL?
Thanks in advance

A: Here's an example to demonstrate how you can call JavaScript functions and asynchornously update src attribute of thumbnails. I've tried to simulate your DB call using setTimeout and the DB using associative array.
HTML:

JavaScript:
var contacts = [
    {name: 'John Doe', email: 'john@doe.com', avatar: '11a93150-14d4-11e3'},
    {name: 'Hannah Smith', email: 'hannah@smith.com', avatar: '11a93150-14d4-1231' }
],

simulatedDB = [];
simulatedDB['11a93150-14d4-11e3'] = "path to avatar 1";
simulatedDB['11a93150-14d4-1231'] = "path to avatar 2";

$(document).ready(function () {
    var compiled = _.template($("#contactTemplate ").html());

    _.each(contacts, function (d, i) {
        $("#contactList").append(compiled(d));
    });
});
function getPath(target) {
    setTimeout(updateAvatar, 1000, target);
}
function updateAvatar(target) {
    $("#contact-"+target+" img").attr("src", simulatedDB[target]);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Consider $f : \mathbb{N} \to (-1,1) \cap \mathbb{Q}, \ n \overset{f}{\mapsto} \sin(n)$. Is $f$ a surjection? If not can we make it a surjection? This is not homework! I have recently been thinking about the properties of the sine function and whether it can effectively map elements from certain spaces to entirely "fill out" another space. I don't really know how to approach the question I have posed.

A: You can define a function $f : \mathbb{N} \to (-1,1), \ n \overset{f}{\mapsto} \sin(n)$.  It will not be a surjection because there are only countably many points in the image and $(-1,1)$ is uncountable.  To make it a surjection, we can just define the image set to be $T$, the points that are the images of $f$.  The set $T$ looks a lot like the rationals in $(-1,1)$.  It is countable and dense. The only rational point in it is $0$, and that only if $0 \in \Bbb N$ for you.  You in fact now have a bijection between $\Bbb N$ and $T$ based on $f$


text:
Q: My C code doesn't output anything, or end running I'm trying to answer this question:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Here is my code:
#include <stdio.h>

int isPrime(long long num)
{
    for (long long k = 1; k < num; k++)
    {
            if (num%k == 0)
                    return 0;
    }

    return 1;
}
long long num = 600851475143;
int main(void)
{
    long long prime_factor = 0;
    for (long long j = 2; j < num; j++)
    {
            if (num % j == 0 && isPrime(j) == 1)
                    prime_factor = j;
    }

    printf("%lli\n", prime_factor);

}

But for some reason it doesn't print anything, or even end.  What is causing this?

A: That's a terribly inefficient way of finding the prime factors of a number.
To find the prime factors, you should:

*

*Create a static list of primes less than or equal to (number / 2).

*Iterate over each element in the list of primes and see if each
   one can evenly divide the number.

*Divide the original number by the prime, and check the last number
  again.

Why? Well the smallest prime is 2. If the number isn't even then the first prime that can divide any number > 2 is 3.
Every number can be uniquely identified by its prime factors. This is called the Fundamental Theorem of Arithmetic. That means that there is only one way to represent e.g. 15 as a product of primes, in this case { 3, 5 }.
However any prime can divide a number more than once. For example, 49 is the product of two primes { 7, 7 }. Dividing the original number by one of its factors makes subsequent divisions quicker. And you can logically stop checking when the number == 1.

A: It doesn't print anything because it never leaves the loop, after which is found the only line which prints anything in the code. Try a smaller number and see if it ends.


text:
Q: How to autorun files and scripts in Ubuntu when inserting a USB stick like autorun.inf in Windows? Is there a way to execute a specific script or open a file with a particular program when inserting a USB stick on Ubuntu like the autorun.inf file in Windows ? If not, is there another way ?
EDIT:
According to the answer I got I have created a file in the USB root folder named autorun with the above contents:
#!/bin/sh
xdg-open myText.txt

I have also created a file named autorun.inf with the above contents:
[autorun]
icon=icon.ico

The autorun.inf file specifies the USB icon.
From the above autorun files only the autorun.inf seems to work. The autorun script file, when executed it displays the above message.

Am I doing something wrong or there are some more parameters to be configured in order to run the script ?
P.S: The files myText.txt and icon.ico are placed in the USB root folder.
Moreover, the autorun and autorun.inf file mode bits have been set to 755, using :
cd /path/to/usbFolder
chmod 755 autorun
chmod 755 autorun.inf

A: Open System Settings > Details > Removable Media and set Software to Run Software

Your USB Stick must be formatted with a native Linux filesystem like EXT4.
Create a shell script with the name autorun (or autorun.sh, doesn't matter) on your USB Stick and make it executable with chmod 755 autorun.
Next time you insert your USB Stick, Ubuntu will notify you about the autorun and ask if you would like to execute this.

To automatically open a document you can use xdg-open
#!/bin/sh
xdg-open myDocument.odt

This will open myDocument.odt with the default application for this mime-type. So it will work the same with all other files, too.
To have a custom icon for your USB Stick you can create a autorun.inf file with following content
[autorun]
icon=icon.png

and place your icon as icon.png on the Stick.

autorun.inf on Ubuntu support this commands (take a look at autorun.inf on Wikipedia):
[autorun]
icon=iconfilename[,index]
label=text

[Content]
MusicFiles=yes|no
PictureFiles=yes|no
VideoFiles=yes|no

[ExclusiveContentPaths]
/pictures
/music
more music/special

[IgnoreContentPaths]
/pictures
/music
more music/special


text:
Q: Convert int array to variadic template Say I have an int array like int arr[N] and say arr[i] are from a tiny domain (e.g. 1-10). Say I also have a variadic templated class with a common interface (abstract class)
template <int... A>
class FooImpl : public Foo
{
}

The question is how do I implement a function:
Foo* getFoo(int arr[N]);

or maybe better:
Foo* getFoo(int* pint, int size);

which would return FooImpl with template arguments corresponding my array? For example for arr = {4,2,6,1} I would get FooImpl<4,2,6,1>

A: I found the answer to my question. The trick is in using struct variadic templates instead of function variadic templates which I initially tried with. I use _getFoo_impl struct with func function which builds up element by element.
Let's assume the elements are in range [1-5] and the size <= 4 and then the code looks as following:
class Foo
{
};

template <int...A>
class FooImpl : Foo {
};

template<int...As>
struct _getFoo_impl
{
    static Foo* func(int *arr, int sz)
    {
        if (sz == 0)
            return new FooImpl<As...>;

        switch (*arr)
        {
        case 1: return _getFoo_impl<As..., 1>::func(arr + 1, sz - 1);
        case 2: return _getFoo_impl<As..., 2>::func(arr + 1, sz - 1);
        case 3: return _getFoo_impl<As..., 3>::func(arr + 1, sz - 1);
        case 4: return _getFoo_impl<As..., 4>::func(arr + 1, sz - 1);
        case 5: return _getFoo_impl<As..., 5>::func(arr + 1, sz - 1);
        default: throw "element out of range";
        }
    }
};

template<int A1, int A2, int A3, int A4, int A5>
struct _getFoo_impl<A1, A2, A3, A4, A5>
{
    static Foo* func(int*, int sz) {
        std::terminate();
    }
};

Foo* getFoo(int *arr, int size)
{
    return _getFoo_impl<>::func(arr, size);
}

A: You cannot store or generate a type from a class template
template <int... N>
class FooImpl;

with run-time integers as template arguments. However, if the following might also fit your actual problem, you could store and then look up a pointer-to-function
template <int... N>
R FooFun(A...);

given run-time integers as template arguments, assuming the function signature R(A...) is the same for all template arguments. Note that A... is not a pack of template parameters here; it's just a placeholder for the types of your own concrete function parameters, e.g. FooFun(int, int).
It seems to me that this formulation indeed fits your problem because you have a factory function with no input parameters that returns a pointer to object FooImpl<N...> always seen as Foo*, so in your case FooFun would look like
template <int... N>
Foo* FooFun();

A general solution for this kind of conversion is based on a look-up table of pointers-to-function and is given in this answer of my previous question adapting a non-constexpr integral value to a non-type template parameter (which by the way works very smoothly now and I'm very happy with it - my actual implementation is here).
The difference in your case is that you need a multi-dimensional look-up table. I suggest that you first define a function "dispatcher" with only one integer template argument
template <int OFFSET>
R FooDispatch(A...);

which represents the linear offset in the multi-dimensional table. In this case the previous solution applies directly to FooDispatch. Then, you have to convert OFFSET to a set of multi-dimensional indices N..., at compile time. For this, you would also need to know the dimensions of the table, or better its strides, again at compile time. Having deduced arguments N..., FooDispatch can now call FooFun<N...>(...).
To be more precise, the logic of this offset-to-index conversion is exactly as in Matlab's function ind2sub, only it's a compile-time operation. This would need some work, so if you like this approach and need help in this last step, I'd be happy to assist. In this case, I think you'd better post a new question with the sub-problem appropriately formulated.
All the above imply that the number of dimensions is also known at compile time, so eventually a function of the form
Foo* getFoo(int arr[N]);

would be fine as an interface, but
Foo* getFoo(int* pint, int size);

does not make much sense; you could only make a run-time check in the latter case, and maybe throw an exception if dimensions do not agree.
Finally, note that using out-of-range indices at run-time would have the same effect as using out-of-range indices in an ordinary C array.


text:
Q: Email Attachment and HTML Content Error I am writing an email attachment script in PHP. I have successfully done the image attachment to email but I am facing issues with the html.
Two Important thing in the Email:

*

*Email Content which is HTML with some designs.

*Email Attach Images.
If i use the following header I am able to see the Email with HTML designed. But attachment not working.
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

If i use the following header I can able to attach the images successful. but the html is just coming as it is not showing how it was designed...
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

Also this email should be shown perfectly in Outlook:

Can some one help to solve the issue.

A: The better way (easier and works fine) will be to use mailer class like PHPMailer...
But to answer you, you can find some help here.
You can find another helful example here

// Prepare by setting a timezone, mail() uses this.
date_default_timezone_set('America/New_York');

// Save some values to send an email, these might have come from any source:
$to = 'example@eliw.com';
$subject = 'A sample email - Dual Format';

// Create a boundary string.  It needs to be unique (not in the text) so ...
// We are going to use the sha1 algorithm to generate a 40 character string:
$sep = sha1(date('r', time()));

// Define the headers we want passed.  Note that they are separated by \r\n
$headers = "From: php@example.com\r\nX-Mailer: Custom PHP Script";

// Add in our content boundary, and mime type specification:
$headers .=
    "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-{$sep}\"";

// The body of the message.  Use the separator with -- in front of it to
//  mark the beginning of each section, and then provide the content type.
//  A blank line beneath that will define the beginning of the content.
//  At the end finish with the separator again, but this time with a --
//  after it as well.
$body =<<<EOBODY
--PHP-alt-{$sep}
Content-Type: text/plain

This is our sample email message

Hello World!

That's it for now

--PHP-alt-{$sep}
Content-Type: text/html

This is our sample email message

Hello World!

That's it for now.

--PHP-alt-{$sep}--
EOBODY;

// Finally, send the email
mail($to, $subject, $body, $headers);


text:
Q: If I go to '/contact', I want to preserve the previous routes view but show a modal So with the design for my website, there is no dedicated contact page. Instead, when clicking a /contact link, I need to show a modal. I could just do this in the traditional way but I want it so that:
a) If anyone lands directly on 'http://website.com/contact', it defaults to the homepage view and shows the modal automatically
b) If the visitor is already on the site and then activates the /contact route, it preserves the view they're currently on e.g. /about and then shows the modal on top of the /about view
Been trying to work this out in a new Vue 2 installation using Vue router but just can't work it out and i'm finding it very difficult to google.

A: Try the following snippet, although I'm not entirely sure how to demo direct navigation to /contact.

Vue.use(VueRouter)

const contactGuard = function(to, from, next) {
  if (to.name === 'contact') {
    this.$root.$emit('modal', true)
    next(false)
  } else {
    next()
  }
}

const routes = [{
    path: '/',
    name: 'home',
    component: {
      template: `<div><p>Home Page</p></div>`,
      beforeRouteLeave: contactGuard
    }
  },
  {
    path: '/about',
    name: 'about',
    component: {
      template: `<div><p>About Page</p></div>`,
      beforeRouteLeave: contactGuard
    }
  },
  {
    path: '/contact',
    name: 'contact',
    beforeEnter: (to, from, next) => {
      if (from.path) {
        // we're coming from another page
        this.$root.$emit('modal', true)
        next(false)
      } else {
        // we've directly navigated to /contact
        next({
          replace: true,
          path: '/',
          query: {
            contact: true
          }
        })
      }
    }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  next(vm => {
    if (to.query.contact) {
      vm.$root.$emit('modal', true)
    }
  })
})

new Vue({
  el: '#app',
  router,
  data() {
    return {
      modal: false
    }
  },
  mounted() {
    this.$on('modal', show => {
      this.modal = show
    })
  }
})
.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .5);
  display: table;
  transition: opacity .3s ease;
}

.modal-wrapper {
  display: table-cell;
  vertical-align: middle;
}

.modal-container {
  width: 300px;
  margin: 0px auto;
  padding: 20px 30px;
  background-color: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .33);
  transition: all .3s ease;
  font-family: Helvetica, Arial, sans-serif;
}

.modal-header h3 {
  margin-top: 0;
  color: #42b983;
}

.modal-body {
  margin: 20px 0;
}

.modal-default-button {
  float: right;
}

/*
 * The following styles are auto-applied to elements with
 * transition="modal" when their visibility is toggled
 * by Vue.js.
 *
 * You can easily play with the modal transition by editing
 * these styles.
 */

.modal-enter {
  opacity: 0;
}

.modal-leave-active {
  opacity: 0;
}

.modal-enter .modal-container,
.modal-leave-active .modal-container {
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    Foobar
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

          <router-link class="nav-link" :to="{ name: 'home' }">Home</router-link>

          <router-link class="nav-link" :to="{ name: 'about' }">About</router-link>

          <router-link class="nav-link" :to="{ name: 'contact' }">Contact</router-link>

    <router-view></router-view>

  <transition name="modal">

            <slot name="header">
              default header
            </slot>

            <slot name="body">
              default body
            </slot>

            <slot name="footer">
              default footer
              <button class="modal-default-button" @click="$root.$emit('modal', false)">
                OK
              </button>
            </slot>

  </transition>

A: Just wanted to offer another way of doing it. The differences are that it preserves routes (doesn't change to query), and doesn't rely on jQuery.
The way it works is that it (also) relies on beforeEnter to adjust the route information.
Instead of using the default way of defining the component in the routes, I put it into the meta. This makes it easy to copy from from into the to
The /contact route uses a showContact meta to determine whether to show the overlay
example:
const routes = [
  { path: '/', meta: { component: Home } },
  { path: '/bar', meta: { component: Bar } },
  {
    path: '/contact',
    meta: { showContact: Contact, component: null },
    beforeEnter: (to, from, next) => {
      if (from.matched[0]) {
        to.meta.component = from.matched[0].components.default;
      }
      next();
    },
  },
];

The last bit is that the instead of using <router-view/>, I use <component v-bind:is="$route.meta.component"></component> to display the component
And to show the contact form: <component v-if="$route.meta.showContact" v-bind:is="$route.meta.showContact"></component> or `
Here is a condesandbox example, without any styling:


text:
Q: How can I make multiple image picker which upload and set image inside container in flutter?
I want to make this type of image picker when I clicked on the plus sign it will open image picker when I picked images it will fit into this container.
Here is some code I've tried.
In this code, I've use flat button it will pick and image and show it under the flat button. but I want output like I mentioned in images. 5 different images uploader.
import 'dart:io';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import 'package:image_picker/image_picker.dart';

class BusinessProfilePage extends StatefulWidget {

  @override
  _BusinessProfilePageState createState() => _BusinessProfilePageState();
}

class _BusinessProfilePageState extends State<BusinessProfilePage> {
  Future<File> profilepicture;
  bool aggreeandaccept = false;
  bool accepttudo = false;

  pickprofilepicture(ImageSource source) {
    setState(() {
      profilepicture = ImagePicker.pickImage(source: source);
    });
  }

  Widget _buildbusinessprofilepicture() {
    return new FormField(
      builder: (FormFieldState state) {
        return FlatButton.icon(
          icon: Icon(Icons.image),
          label: Text('Business Profile Picture'),
          //color: Colors.white,
          textColor: Colors.black54,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(50),
          ),
          onPressed: () {
            pickprofilepicture(ImageSource.gallery);
          },
        );
      },
    );
  }

  Widget _buildprofileimage() {
    return FutureBuilder<File>(
      future: profilepicture,
      builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
        if (snapshot.connectionState == ConnectionState.done &&
            snapshot.data != null) {
          return Image.file(
            snapshot.data,
            width: 100,
            height: 100,
          );
        } else if (snapshot.error != null) {
          return const Text(
            'Error Picking Image',
            textAlign: TextAlign.center,
          );
        } else {
          return const Text(
            'No Image Selected',
            textAlign: TextAlign.center,
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("BusinessProfile"),
      ),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            SingleChildScrollView(
              child: SafeArea(
                top: false,
                bottom: false,
                child: Form(
                  child: Scrollbar(
                    child: SingleChildScrollView(
                      dragStartBehavior: DragStartBehavior.down,
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: new Container(
                        margin: EdgeInsets.fromLTRB(10, 10, 10, 10),
                        child: new Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            _buildbusinessprofilepicture(),
                            _buildprofileimage(),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

A: You can easily achieve this using a list, I have created a sample code for you please check this.
import 'package:blog_app/models/ImageUploadModel.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class SingleImageUpload extends StatefulWidget {
  @override
  _SingleImageUploadState createState() {
    return _SingleImageUploadState();
  }
}

class _SingleImageUploadState extends State<SingleImageUpload> {
  List<Object> images = List<Object>();
  Future<File> _imageFile;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      images.add("Add Image");
      images.add("Add Image");
      images.add("Add Image");
      images.add("Add Image");
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          centerTitle: true,
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
        Expanded(
          child: buildGridView(),
        ),
      ],
    ),
  ),
);
  }

  Widget buildGridView() {
    return GridView.count(
  shrinkWrap: true,
  crossAxisCount: 3,
  childAspectRatio: 1,
  children: List.generate(images.length, (index) {
    if (images[index] is ImageUploadModel) {
      ImageUploadModel uploadModel = images[index];
      return Card(
        clipBehavior: Clip.antiAlias,
        child: Stack(
          children: <Widget>[
           Image.file(
              uploadModel.imageFile,
              width: 300,
              height: 300,
            ),
            Positioned(
              right: 5,
              top: 5,
              child: InkWell(
                child: Icon(
                  Icons.remove_circle,
                  size: 20,
                  color: Colors.red,
                ),
                onTap: () {
                  setState(() {
                    images.replaceRange(index, index + 1, ['Add Image']);
                  });
                },
              ),
            ),
          ],
        ),
      );
    } else {
      return Card(
        child: IconButton(
          icon: Icon(Icons.add),
          onPressed: () {
            _onAddImageClick(index);
          },
        ),
      );
    }
  }),
);
  }

  Future _onAddImageClick(int index) async {
setState(() {
  _imageFile = ImagePicker.pickImage(source: ImageSource.gallery);
  getFileImage(index);
});
  }

  void getFileImage(int index) async {
//    var dir = await path_provider.getTemporaryDirectory();

_imageFile.then((file) async {
  setState(() {
    ImageUploadModel imageUpload = new ImageUploadModel();
    imageUpload.isUploaded = false;
    imageUpload.uploading = false;
    imageUpload.imageFile = file;
    imageUpload.imageUrl = '';
    images.replaceRange(index, index + 1, [imageUpload]);
  });
 });
 }
 }

ImageUploadModel  class
class ImageUploadModel {
  bool isUploaded;
  bool uploading;
 File imageFile;
  String imageUrl;

  ImageUploadModel({
    this.isUploaded,
    this.uploading,
    this.imageFile,
    this.imageUrl,
  });
}

A: You can make 4 custom buttons (with InkWell/GestureDetector), in their onTap, you can use a logic something like this for all your buttons:
// when button 1 is pressed, you go to image picker page,
// select image from there and when you come back you update _image1
Navigator.push(context, MaterialPageRoute(builder: (_) => ImagePickerPage())).then((pickedImage) {
  if (pickedImage != null) {
    setState(() {
      _image1 = pickedImage;
    });
  }
});

In your image picker page, you need to pass the image back, you'd use
Navigator.pop(context, pickedImage);

A: I hope you help this multi image picker you can be used this dependency to integrate it.

A: You can use file_picker plugin.
It supports all the plaforms and is the best for picking up files/bytes/images/videos/etc... in flutter
here is the working demo for this github


text:
Q: Differentiability on normed spaces My Advanced Calculus homework have the following problem: define differentiability on normed spaces $E,F$. Show that if $U \subset E$ is open and $f: U \to F$ is differentiable at $x \in U$ then continuity of $f$ at $x$ is equivalent to continuity of the derivative (linear transformation) $f'(x): E \to F$.
Now, the definition of differentiability on normed spaces should be the same as the one on euclidian spaces: $f: U \subset E \to F$ is differentiable at $x \in U$ if there exists a linear transformation $T: E \to F$ such that:
\begin{eqnarray}
f(x+h) = f(x) + T(h) + r(h) \tag{1}\label{1}
\end{eqnarray}
where:
$$\lim_{h\to 0}\frac{r(h)}{||h||} = 0,$$ provided $x+h \in U$.
Now, write $\rho(h) = r(h)/||h||$ for every $h \neq 0$ and set $\rho(0) := 0$. Then, (\ref{1}) becomes:
\begin{eqnarray}
f(x+h) = f(x) + f'(x)(h) + \rho(h)||h|| \tag{2}\label{2}
\end{eqnarray}
where $\lim_{h\to 0}\rho(h)=0$ (I wrote $f'(x)$ instead of $T$). Thus, $\lim_{h\to 0}\rho(h)||h|| = 0$ and we have:
\begin{eqnarray}
f(x+h)-f(x) = f'(x)(h) \tag{3}\label{3}
\end{eqnarray}
Now, if we write $x+h = y$, (\ref{3}) becomes
\begin{eqnarray}
f(y) - f(x) = f'(x)(y)-f'(x)(x) \Rightarrow \lim_{y\to x}f(y) - f(x) = 0 \iff \lim_{y\to x}f'(x)(y)-f'(x)(x) = 0 \tag{4}\label{4}
\end{eqnarray}
Question: Is (\ref{4}) sufficient to prove the second statement of the problem, i.e. that continuity of $f$ at $x$ is equivalent to continuity of the derivative $f'(x): E \to F$?

A: It is sufficient. Linear operators $T: E \rightarrow F$ are continuous everywhere iff they are continuous in one point $x \in E$: Let $T$ be continuous in $x \in E$. Now let $z \in E$ be arbitrary and $z_n \rightarrow z$ for some sequence $(z_n)_{n \in \mathbb{N}} \subseteq Z$. Then $z_n+x-z \rightarrow x$. So:
$$
\lvert T(z_n) - T(z) \rvert = \lvert T(z_n +x-z) -T(x) \rvert \rightarrow 0
$$
We used linearity and then continuity in $x$.
Your other arguments are correct, too.

A: $(3)$ is an equation containing the variables $x$ and $h$. If it were true for all $h$, then subtraction of $(3)$ from the correct equation $(2)$ would give $r(h)= \rho(h)/\lVert h \rVert = 0$ for all $h$. This is true if and only if $f(x + h) = f(x) + T(h)$ which is a very special case ($f$ is an affine map). In other words, $(3)$ and $(4)$ are in general false. This does not matter, you do not need $(4)$. Since $r(h) \to 0$ as $h \to 0$, we see that $\lim_{h \to 0} f(x+h) = f(x)$ if and only if $\lim_{h \to 0} T(h) = 0$. But $\lim_{h \to 0} f(x+h) = f(x)$  means that $f$ is continuous at $x$ and $\lim_{h \to 0} T(h) = 0$ means that $T$ is continuous at $0$ which is equivalent to the continuity of $T$ (since $T$ is linear).


text:
Q: SQL query fails when username variable is added to array I have this array which holds the columns and the data to be inserted into said columns:
if($this->_insert(array(
'name'=>$fileName,
'size'=>$fileSize,
'ext'=>$fileExt,
'artist'=>$username
))){

It works fine when artist is not there, or when artist equals a string.
So for example if artist equals:
$username = $user_data['username'];

It does not work. (I have checked if that echos out the correct data and it does)
But if artist equals:
$username = "test";

It will then submit the correct data with the artist and everything correct.
This is the _insert function:
public function _insert($array)
{
    $this->_database=new UploadDatabase();
    $this->_database->connect();
    $values = array_values($array);
    //format fields string
    $fields = implode(',', array_keys($array));
    //$fields = array("name","size", "path", "ext");
    return $this->_database->insert('audio',$values,$fields);
}

To sum up, the username breaks the sql when It is the real username variable but not when its a hard-coded string. The problems been annoying me all day and I've tried countless methods but i am close to giving up!

A: As john stated:
$array = array( 'name'=>$fileName, 'size'=>$fileSize, 'ext'=>$fileExt, 'artist'=>$username ); print_r($array);

Did the trick.


text:
Q: Computing the negative log likelihood with numpy I am trying to implement only with Numpy the following formula for the negative log likelihood

However I am getting two vastly different results between the sum formulation or the matrix formulation (in comment in the bellow code block).
def log_likelihood(y, tx, w):
s = 0

for i in range(len(y)):
    s += np.log(1+np.exp(tx[i,:].T@w))-y[i]*tx[i,:].T@w

return s
#return np.sum(np.log(1+np.exp(tx@w))-y@tx@w)

Any idea what's wrong with my matrix formulation?


text:
Q: OleDbDataReader query syntax error in asp.net i trying to execute a query that link different databases OleDbDataReader, but i am getting error in query string, note that this query is correct and running successfuly in sql studio manager
but in .Net i am getting this error in
OleDbDataReader reader = myCommand.ExecuteReader();

the error message:

Incorrect syntax near 'PR1'.

my code "long query string"
protected void Page_Load(object sender, EventArgs e)
{
    string strConString=System.Configuration.ConfigurationManager.ConnectionStrings["WorkflowConnStr"].ConnectionString.ToString();

    string sqlstr = "select coalesce(engdir ,'Total') [engdir]," +
    "SUM(case when a.Status = 'Delivered' then Total else 0 end) as [Delivered],"+
    "SUM(case when a.Status = 'Completed' then Total else 0 end) as [Completed],"+
    "SUM(case when a.Status = 'Pending' then Total else 0 end) as [Pending],"+
    "SUM(case when (a.Status ='Rejected') then Total Else 0 end) as [Rejected],"+
    "COUNT(*) as Total from "+
    "(select count(*) as Total, CurrentActorUID,ReferenceNo, Status,RequestedDate from tbl_ServiceTracking "+
    "where CurrentActorUID is not null and CurrentActorUID <> '' and "+
    "(Status='rejected' or  Status='Completed' or Status='Pending' or Status='Delivered' )and (ServiceNo is not null )"+
    "group by CurrentActorUID,Status,RequestedDate,ReferenceNo) a"+
    "JOIN PR1.dbo.GetUserDetailsE AS b "+
    "ON a.CurrentActorUID = b.PERUserName"+
    "WHERE --b.DirCode=@DirCode "+
     "(CAST(a.RequestedDate AS DATETIME)>='1/1/2014' AND CAST(a.RequestedDate AS DATETIME)<='4/30/2014') "+
    "GROUP BY b.engdir "+
    "WITH ROLLUP HAVING engdir IS NOT NULL OR GROUPING(b.engdir) = 1 ORDER BY "+
    "CASE WHEN b.engdir IS NULL THEN 1 ELSE 0 END ,b.engdir ";

    OleDbConnection myConnection = new OleDbConnection(strConString);
     try {myConnection.Open();}
     catch (Exception err) { System.Diagnostics.Debug.WriteLine(err.Message); }

    OleDbCommand myCommand = new OleDbCommand(sqlstr, myConnection);
    OleDbDataReader reader = myCommand.ExecuteReader();
    myCommand.ExecuteReader(CommandBehavior.CloseConnection);

    Chart1.DataBindCrossTable(
        reader,
        "Excellent",
        "Satisfied",
        "Not Satisfied",
        "Total");
}

any suggestion ?

A: you missed a space here:
"group by CurrentActorUID,Status,RequestedDate,ReferenceNo) a"+

should be:
"group by CurrentActorUID,Status,RequestedDate,ReferenceNo) a "+

Additionally, you can use literal '@' instead of using concatenation, something like this:
string sqlstr = @"SELECT COALESCE(engdir, 'Total') [engdir],
                SUM(case when a.Status = 'Delivered' then Total else 0 end) as [Delivered],
                SUM(case when a.Status = 'Completed' then Total else 0 end) as [Completed],
                SUM(case when a.Status = 'Pending' then Total else 0 end) as [Pending],
                SUM(case when (a.Status ='Rejected') then Total Else 0 end) as [Rejected],
                COUNT(*) as Total from
                (select count(*) as Total, CurrentActorUID,ReferenceNo, Status,RequestedDate from tbl_ServiceTracking
                where CurrentActorUID is not null and CurrentActorUID <> '' and
                JOIN PR1.dbo.GetUserDetailsE AS b
                ON a.CurrentActorUID = b.PERUserName
                WHERE --b.DirCode=@DirCode
                (CAST(a.RequestedDate AS DATETIME)>='1/1/2014' AND CAST(a.RequestedDate AS DATETIME)<='4/30/2014')
                GROUP BY b.engdir
                WITH ROLLUP HAVING engdir IS NOT NULL OR GROUPING(b.engdir) = 1 ORDER BY
                CASE WHEN b.engdir IS NULL THEN 1 ELSE 0 END ,b.engdir";

Run the query in your sql platform and from there you can easily check where the error came from. And just copy the query inside the literal string @"";


text:
Q: Use MySQL output as input for BASH function in a loop Let's say I have a MySQL table animals with columns id, name and 3 rows:
1, Mountain Goat
2, Angry Chicken
3, Weird Llama

If I run the command animals=$(mysql -u root -e 'SELECT name FROM animals'), I get the result Mountain Goat Angry Chicken Weird Llama.
If I hard code the animals into the array animals=("Mountain Goat" "Angry Chicken" "Weird Llama"), and then try to access the second entry of the array with the command echo ${animals[1]}, I get the output Angry, not "Angry Chicken".
Ultimately what I want is the pass each value animals.name into a function in BASH. See the sample script below.
#!/bin/bash
animals=$(mysql -u root -e 'SELECT name FROM animals')
function showAnimal {
    echo "Wow, look at the "$1"!";
}
for i in $animals; do
    showAnimal ${animals[$i]}
done
showAnimal

And get the following results:
Wow, look at the Mountain Goat!
Wow, look at the Angry Chicken!
Wow, look at the Weird Llama!

A: The problem is that you're trying to (incorrectly) treat animals as an array when it is a simple variable.
If you run the script with bash -x you will see that you are calling the showAnimal function with all of the animals as parameters, instead of passing the animals to the function one by one.
All you need to do is to fix the parameter you pass to the showAnimal function in your loop:
#!/bin/bash
animals=$(mysql -u root -e 'SELECT name FROM animals')
function showAnimal {
    echo "Wow, look at the "$1"!";
}
for i in $animals; do
    showAnimal $i
done


text:
Q: Android studio flutter app doesn't run on my android device or an emulator when i run the app nothing happens and then it just says timeout waiting for app to start

A: I think that you have to keep patience despite of terminate app building. i faced same issue and waited for around 15-20 minutes and finally app is install.


text:
Q: best practice tuple, dynamic or model When are good places to use a Tuple instead of some kind of model class? Isn't it just lazy to use Tuples?
I'm using Tuples or sometimes dynamics in various places in my projects and I'm asking myself if creating a model class for each would be a good practice.
Events
I'm using Tuples as a payload for some events I write in my PRISM applications because the class PubSubEvent only takes one generic type argument.
Solution:

*

*Create a model class and use it instead

is it a good practice to do so?
JSON argument parsing
When I have a web API access point where I expect a json string as argument, I sometimes cast the string to a dynamic type and read properties out of it and pass it to my managers.
Solution:

*

*Edit the json in the web client and just send the needed data

*Create a argument parser (or however they are called again) and except a model as argument

is it a good practice to do so?
Temporary data storage in algorithms
In some algorithms I use Tuples to store my data temporary. I think in this context Tuples are a good thing.
More?
Are there more places Tuples are useful? When should they be used and when not?
MSDN

Tuples are commonly used in four ways:

*

*To represent a single set of data. For example, a tuple can
  represent a database record, and its components can represent
  individual fields of the record.

When working with an database framework I think this is not a good practice?

*To provide easy access to, and manipulation of, a data set.

Ok in algorithms where the code sometimes is hard to read anyway.

*To return multiple values from a method without using out parameters
  (in C#) or ByRef parameters (in Visual Basic).

Isn't this just lazy and hard to read?

*To pass multiple values to a method through a single parameter. For
  example, the Thread.Start(Object) method has a single parameter that
  lets you supply one value to the method that the thread executes at
  startup time. If you supply a Tuple<T1, T2, T3> object as the method
  argument, you can supply the thread's startup routine with three
  items of data.

Again Lazy? Can be done with any other model class too?
In my opinion with this knowledge I would say Tuples are bad practice. Can somebody show me an good way to use them?


text:
Q: Why Is This Searching Algorithm Bizarrely not Working for this Case? I am somewhat new to Java, and I was learning the concept of recursion. I was creating a recursive algorithm that checks if an element exists in a Comparable array by using the compareTo method. Although the algorithm works in most cases, for some reason it does not seem to find an element in the second half. For example, if the array is {3, 5, 1, 9, 11}, calling the method on 3, 5, 1 successfully returns true, but calling the method on 9, 11 returns false. Attached is the code, any help would be greatly appreciated!
  @SuppressWarnings ("unchecked")
  public boolean searchItem (Comparable[] arr, Comparable searchValue)
  {
    if (arr.length == 1 && arr[0].compareTo (searchValue) == 0)
      return true;
    else if (arr.length == 1)
      return false;
    return arr[0].compareTo (searchValue) == 0 || searchItem (Arrays.copyOfRange (arr, 1, arr.length - 1), searchValue);
  }

A: The 3rd param of copyOfRange is the copyTo index exclusive of the element - i.e. the element at the copyTo index is not copied. So you need arr.length there & not arr.length - 1
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange(boolean[],%20int,%20int)
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**.
     (This index may lie outside the array.)

So you need searchItem (Arrays.copyOfRange (arr, 1, arr.length), searchValue)
A much more simple recursive program is this
if(arr.length == 0)
    return false;

if(arr[0].compareTo(searchValue) == 0)
    return true;

return searchItem(Arrays.copyOfRange(arr, 1, arr.length), searchValue);


text:
Q: SQL Syntax Error in Java I am developing an application with java on netbeans/windows 7. I was trying to insert data to database with PreparedStatement using SQL. So this is my code;
private void addInfoActionPerformed(java.awt.event.ActionEvent evt) {
    Connection conn;
    PreparedStatement pst;
    String url = "jdbc:derby://localhost:1527/records";
    String SQL_INSERT = "INSERT INTO records"+
                "VALUES(?,?,?)";
    String name, surname, number;
    try {
        conn = DriverManager.getConnection(url, "system", "app");
        System.out.println("connected to db");
        pst = conn.prepareStatement(SQL_INSERT);
        name = nameField.getText();
        surname = surnameField.getText();
        number = numberField.getText();
        System.out.println("got data from textfields");
        pst.setString(1, name);
        pst.setString(2, surname);
        pst.setString(3, number);
        System.out.println("variables set");
        pst.executeUpdate();
        System.out.println("sql command executed");
        pst.close();
        conn.close();
    } catch (SQLException ex) {
        Logger.getLogger(addition.class.getName()).log(Level.SEVERE, null, ex);
    }

}

But I got an error like this;

java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at
  line 1, column 27.

Name of my table is records and it has three coloumns named; name, surname and number. As I can understand from the println lines, there is a problem with that line;
pst = conn.prepareStatement(SQL_INSERT);

or maybe I created SQL_INSERT string and SQL code wrong. I couldn't figure out what is the problem exactly.

A: You're missing a space in
String SQL_INSERT = "INSERT INTO records"+
            "VALUES(?,?,?)";

When you do the concatenation, it produces "INSERT INTO recordsVALUES(?,?,?)"
Change it to
String SQL_INSERT = "INSERT INTO records"+
            " VALUES(?,?,?)";


text:
Q: How to prove that $87!<16! \left(52^{71}\right)$ Prove that
$$87!<16! \left(52^{71}\right)$$
I do not how can i compare between the factorials or what the procedure to solve such questions?

A: Note that
$$87!<16! \left(52^{71}\right)\iff \frac{87!}{16!}<52^{71}\iff\binom{87}{71}<\frac{52^{71}}{71!}$$
which is true from $\ { n \choose k} \leq \frac{n^k}{k!}. ( \, 1-\frac {k}{2n} ) \,^{k-1}   $ since
$$\binom{87}{71}\le \frac{87^{71}}{71!}\cdot\left(1-\frac{71}{2\cdot 87}\right)^{70}=\frac{52^{71}}{71!}\cdot \frac{87^{71}}{52^{71}}\cdot \frac{103^{71}}{174^{71}}\cdot\frac{174}{103}=\frac{174}{103}\cdot\left(\frac{87\cdot103}{52\cdot 174}\right)^{71}\cdot \frac{52^{71}}{71!}$$
$$=\frac{174}{103}\cdot \left(\frac{103}{104}\right)^{71}\cdot \frac{52^{71}}{71!}<0.851\cdot \frac{52^{71}}{71!}$$

A: You know that $87!=16! \cdot 17 \cdot 18 \dots 87$, hence you want to show that
$$17 \cdot 18\cdot 19 \dots 87 < 52^{71}$$
Now notice that on the left hand side you have $71$ terms with $52$ being the middle one. Hence you can group that in pairs (first with last, second with second last etc. and finally leave $52$ alone). You can say the following:
$$(52-x)(52+x)=52^2-x^2<52^2$$
Hence the product in each pair is less than $52^2$
Do this for all $x$'s between $1$ and $35$ to get that the product is less than $52^{71}$ since you have $35$ pairs for which it holds and then you add the $52$ factor
QED

A: AM-GM gives:
$$\frac1{71}\sum_{i=1}^{71}(i+16)>\sqrt[71]{\prod_{i=1}^{71}(i+16)}$$
So:
$$\frac1{71}\left(\frac{71(71+1)}{2}+71\cdot 16\right)>\sqrt[71]{\frac{87!}{16!}}$$
or:
$$52^{71}>\frac{87!}{16!}\implies 16!(52^{71})>87!$$


text:
Q: Closing css dropdown using jquery Sorry for the vague project title but I'm not having a great idea about how to explain this.
So, let's dive in to it. I was in need of a dropdown list with multiple select options to select recipients from.
I've started my search on Codepen and came across this: https://codepen.io/MaartenTe/pen/mXYLXj
I've forked it so I could tweak it myself. The snippets works perfect. The only thing missing is the ability of closing the dropdownlist when clicking outside of it.
So I started to approach it using javascript. So far I got following code:
$(document).click(function(e) {
  var target = e.target; //target div recorded
  if (!$(target).is('.multi-select ') ) {
    $('.multi-select-options span').css('display', 'none');
    $('.multi-select-options label').css('display', 'none');
  }
});

Although this isn't working the way I want, I think it's the right approach?

A: Looking at how that works, its a checkbox that causes the toggle so you need to clear that when you click out the box.
$('.multi-select').on('click', function(e){
  e.stopPropagation()
});

$(window).on('click', function(e) {
 $('#toggle-open').attr({checked: false})
});

The stopPropagation will stop the window click even firing. https://codepen.io/anon/pen/rdwrya?editors=1111

A: What works in the given codepen:
var toggle = document.getElementById('toggle-open');
document.addEventListener('click', function(event) {
  if (['INPUT', 'LABEL', 'SPAN'].indexOf(event.target.nodeName) + 1) return;
  if (toggle.checked)    toggle.checked = false;
});

Just handle click, exclude the relevant elements and uncheck if needed.


text:
Q: How to return from bash functions the right way? This script, which i source in my terminal, offers the function _cphetzner, that is used to create a git repository. This function uses another function _feed_variable that prompts user for missing variables.
My questions at this point are:

*

*Is this the right way to return from functions - by using return 1?

*If set -o errexit is uncommented, does the script abort on any return 1 (e.g. from function _feed_variable or only the one that return to the shell?

*If set -o errexit is uncommented, what is the right way to exit the function without closing the terminal?

*I feel like i am not designing the script in a way that it cleans up on errors. Any recommendations?

#!/usr/bin/env bash

# +---------------+
# | Bash settings |
# +---------------+
# abort on nonzero exitstatus
# set -o errexit
# abort on unbound variable
# set -o nounset
# don't hide errors within pipes
# set -o pipefail

# +----------------+
# | Bash Variables |
# +----------------+

# +----------------+
# | Script Content |
# +----------------+

function _feed_variable() {

  local prompt_msg=$1
  local var_to_set=$2

  echo "$prompt_msg"

  read answer

  case $answer in
    [Yy]*)
      echo "Enter $2: "
      read new_value
      eval $var_to_set="'$new_value'"
      return 0
      ;;
    [Nn]*)
      echo "Clearing up and quitting ..."
      return 1
      ;;
  esac
}

function _cphetzner() {
    pushd $PWD > /dev/null
    POSITIONAL_ARGS=()

    REPO_NAME=
    # TARGET_FOLDER=$PWD/$REPO_NAME
    TARGET_FOLDER=
    SOURCE_TEMPLATE=

    while [[ $# -gt 0 ]]; do
        case $1 in
            -r|--repository)
                REPO_NAME="$2"
                shift
                shift
                ;;
            -s|--sourcetemplate)
                SOURCE_TEMPLATE="$2"
                shift
                shift
                ;;
            -t|--targetfolder)
                TARGET_FOLDER="$2"
                shift
                shift
                ;;
            -*|--*)
                echo "Unknown option $1"
                exit 1
                ;;
            *)
                POSITIONAL_ARGS+=("$1") # save positional arg
                    shift # past argument
                    ;;
        esac
    done

  #=====[ Print Info ]==================================

  echo "SOURCE_TEMPLATE is:\t" $SOURCE_TEMPLATE
  echo "TARGET_FOLDER is:\t" $TARGET_FOLDER
  echo "{POSITIONAL_ARGS is [@]}:\t" ${POSITIONAL_ARGS[@]}
  echo "REPO_NAME is:\t" $REPO_NAME

  set -- "${POSITIONAL_ARGS[@]}"

  if [[ -n $1 ]]; then
    echo "Last line of file specified as non-opt/last argument:"
      tail -1 "$1"
  fi

  #=====[ Create folder and initiate repository ]=======

  # Check if user input has repo name
  if [[ -z "$REPO_NAME" ]]; then
    _feed_variable "Do you want to feed me a repository name? [y/n]" "REPO_NAME" ||
    return 1
  fi

  # Check if repository in given path exists
  if [[ -z "$TARGET_FOLDER" ]]; then
    _feed_variable "Do you want to feed me a target name? [y/n]" "TARGET_FOLDER" ||
    return 1
  fi

  while [[ -d "${TARGET_FOLDER}/${REPO_NAME}" ]]
  do
    echo "Repository already exist in this folder" &&
    _feed_variable "Do you want to feed me another target name? [y/n]" "TARGET_FOLDER" ||
    return 1
  done

  # Create folder
  mkdir -p $TARGET_FOLDER/$REPO_NAME

  # # Check if template folder exists
  #   [[ -z $SOURCE_TEMPLATE ]] && echo "No template folder" ||
  #       cp -a $SOURCE_TEMPLATE/ $TARGET_FOLDER/$REPO_NAME

  #====[ Initiate Repo ]================================

  cd $TARGET_FOLDER/$REPO_NAME
    git init
    git remote add origin hetzner:/yolo/$REPO_NAME.git

    git add .
    git commit -m "Initial commit"

  echo -e "[DONE] Repo $REPO_NAME created successfully"
  echo -ne "Do you want to push repo to Hetzner now? [y/n]"

  read answer

    case $answer in
    [Yy]*)
          echo "Pushing to Hetzner ..."
      git push -u -f origin master
      ;;
    [Nn]*)
      ;;
    esac

    echo "Have a great day ..."

  return 0

    popd > /dev/null
}

A: The shell considers an exit status of zero as truthy/succesful, and a nonzero status as falsy/failing. So, if the function succeeds, return 0 would likely be considered more right than return 1.
As for set -e/set -o errexit, it doesn't trigger on just any command/function, e.g. it ignores those that are used as conditions or where the exit status is otherwise ignored, like the non-rightmost parts of a pipeline. It doesn't matter what nesting level the failure happens, though. But it does have some complications that make it hard to use.
fail() { return 1; }
# these won't trigger set -e
fail | cat
fail || true
if fail; then echo x; fi
# so this prints
echo one

# these also won't trigger it
try() {
    fail
    echo two
}

try || true
( fail; echo three ) || true

See https://mywiki.wooledge.org/BashFAQ/105 for the oddities of set -e.


text:
Q: java jersey exception interceptor I have the following Jersey endpoint:
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/sessionlog")
@Consumes(MediaType.APPLICATION_JSON)
public Response getSessionLog(@HeaderParam(CLIENT_HEADER_PARAM) String clientId,
                                  @QueryParam("sessionId") Long sessionId,
                                  @QueryParam("callback") String callback) {
}

And I want to create a handler that intercepts any exception that may occur inside this endpoint and all other endpoints over the application. I don't want to throw anything, wrap code in try...catch, I just want this handler to accept any exception and, ideally, respond with special response. How to achieve that?
I tried this
@Provider
public class  RestExceptionMapper implements ExceptionMapper<Exception> {

    public Response toResponse(Exception exception){

        return Response.status(Response.Status.NOT_FOUND).
                entity(new ErrorResponse(exception.getClass().toString(),
                        exception.getMessage()) ).
                build();
    }
}

But I want to create just try..catch...throw free code in my endpoints. Thanks


text:
Q: Fail to download repository information Why lately I've been getting this error when I try to update my computer?
Ubuntu 12.04
Kernel 3.5.2
Processor i386
W:Failed to fetch http://ppa.launchpad.net/kernel-ppa/ppa/ubuntu/dists/precise/main/source/Sources  404  Not Found,
W:Failed to fetch http://ppa.launchpad.net/kernel-ppa/ppa/ubuntu/dists/precise/main/binary-i386/Packages  404  Not Found,
E:Some index files failed to download. They have been ignored, or old ones used instead.


text:
Q: I don't know what to call it php/css error tho whats going on is everything is loading just fine url is deigned.sytes.net except for the links when i click about us or services or contact they look like there loading but the content in body.tpl doesn't change from default. maybe you can help me with this why the links are not changing. you u want  here are the ONLY php files
I have made phps files for view perpose's but if you insist on it i will post the require code.
designed.sytes.net/index.phps
designed.sytes.net/classes/file.class.phps

A: In the URLs you name the parameter p but in your files.class.php you actually test for $_GET['page']. So either change the URLs to use page as parameter or change the code to:
// in files.class.php instead of if(!isset($_GET['page']))
if(!isset($_GET['p'])){
    // your code here...
} else {
   // ...
}

In your original code, as $_GET['page'] does never exist, it always shows the index page.

Another thing that looks strange to me is the following (but maybe it is just how you set it up):
if(file_exists($_GET['page'].'.txt')){
    // and lets include that then:
    ob_start();
    include("contents/". $_GET['page'] . '.php');
    $content = ob_get_contents();
    ob_end_clean();
}

You first check whether the text file e.g. about.txt exists but then include a PHP file contents/about.php. Is this intended? Does the PHP always exist if the text file exists?

UPDATE:
Also make sure that you properly check the value that you get from $_GET['page'] or however you call it in the end.
E.g. this call http://designed.sytes.net/index.php?page=../index seems to kill your server (sorry it was unintentionally :( )
UPDATE 2:
In order to provide "some" security you could check whether $_GET['page'] is one of predefined values instead of checking whether a file with this name exists. E.g:
$valid_pages = array('home', 'about', 'services', 'contact');

if(isset($_GET['page']) && in_array($_GET['page'], $valid_pages) {
   // include page here
}
else {
    // redirect to home page
}

That makes sure that $_GET['page'] is not of form of relative pathes like ../index. If it is not one of those values in $valid_pages you redirect to the home page.

A: I see in your http://designed.sytes.net/classes/file.class.phps file you have $_GET['page'] but on the query string you have p=
an example of what does not work is:
http://designed.sytes.net/index.php?p=about

and then changed to:
http://designed.sytes.net/index.php?page=about

seems to show something different.


text:
Q: How to make dynamic labels from a spatial polygons dataframe for Polygons on a Leaflet map in R With this script, I am displaying a map with three isochrones. I would like the map to have labels containing the max time represented by each isochrone/polygon.
How should I reference the spatial data frames (iso1/2/3) in the addPolygons() section?
In each of the three addPolygons() bellow I tried a different approach but no luck :( (although the script still works).
library(osrm)
library(leaflet)
library(viridisLite)

# Making isochrones
iso1 = osrmIsochrone(loc = c(9.2,45.5),
                    breaks = seq(from = 0,
                                 to = 45,
                                 by = 5),
                    res=75)
iso2 = osrmIsochrone(loc = c(12.51182,41.92631),
                     breaks = seq(from = 0,
                                  to = 45,
                                  by = 15),
                     res=100)
iso3 = osrmIsochrone(loc = c(11.25581,43.76956),
                     breaks = seq(from = 0,
                                  to = 45,
                                  by = 15),
                     res=100)

# colors for leaflet
vir = viridis(9)

# palette
pal1 <- colorNumeric(
  palette = vir,
  domain = iso1@data$id)
pal2 <- colorNumeric(
  palette = "Blues",
  domain = iso2@data$id)
pal3 <- colorNumeric(
  palette = "Reds",
  domain = iso3@data$id)

# Plotting interactive map using spdf
leaflet()%>%
  addTiles("http://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", attribution = 'Google')%>%
  addPolygons(data = iso1,
              fill = TRUE,
              fillOpacity = 0.7,
              fillColor = ~pal1(id),stroke = FALSE, label = iso1@data$max)%>%
  addPolygons(data = iso2,
              fill = TRUE,
              fillOpacity = 0.7,
              fillColor = ~pal2(id),stroke = FALSE, label = ~max)%>%
  addPolygons(data = iso3,
              fill = TRUE,
              fillOpacity = 0.7,
              fillColor = ~pal3(id),stroke = FALSE, label = ~iso3@data$max)

A: It works if you provide the max values as.character to the label.
library(osrm)
library(leaflet)
library(viridisLite)

# Making isochrones
iso1 = osrmIsochrone(loc = c(9.2,45.5),
                     breaks = seq(from = 0,
                                  to = 45,
                                  by = 5),
                     res=75)
iso2 = osrmIsochrone(loc = c(12.51182,41.92631),
                     breaks = seq(from = 0,
                                  to = 45,
                                  by = 15),
                     res=100)
iso3 = osrmIsochrone(loc = c(11.25581,43.76956),
                     breaks = seq(from = 0,
                                  to = 45,
                                  by = 15),
                     res=100)

# colors for leaflet
vir = viridis(9)

# palette
pal1 <- colorNumeric(
  palette = vir,
  domain = iso1@data$id)
pal2 <- colorNumeric(
  palette = "Blues",
  domain = iso2@data$id)
pal3 <- colorNumeric(
  palette = "Reds",
  domain = iso3@data$id)

# Plotting interactive map using spdf
leaflet()%>%
  addTiles("http://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", attribution = 'Google')%>%
  addPolygons(data = iso1,
              fill = TRUE,
              fillOpacity = 0.7,
              fillColor = ~pal1(id),stroke = FALSE, label = as.character(iso1@data$max))%>%
  addPolygons(data = iso2,
              fill = TRUE,
              fillOpacity = 0.7,
              fillColor = ~pal2(id),stroke = FALSE, label = as.character(iso2@data$max))%>%
  addPolygons(data = iso3,
              fill = TRUE,
              fillOpacity = 0.7,
              fillColor = ~pal3(id),stroke = FALSE, label = as.character(iso3@data$max))

A: leaflet()%>%
  addTiles("http://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", attribution = 'Google')%>%
  addPolygons(data = iso1,
              fill = TRUE,
              group = "label1",
              fillOpacity = 0.7,
              fillColor = ~pal1(id),stroke = FALSE, label = iso1@data$max)%>%
  addPolygons(data = iso2,
              fill = TRUE,
              group = "label2",
              fillOpacity = 0.7,
              fillColor = ~pal2(id),stroke = FALSE, label = ~max)%>%
  addPolygons(data = iso3,
              fill = TRUE,
              group = "label3",
              fillOpacity = 0.7,
              fillColor = ~pal3(id),stroke = FALSE, label = ~iso3@data$max)

Use the group argument to specify the label.


text:
Q: sizeof() not taking my type name I have a struct in my program for which I need to use the size to allocate managed memory for an instance of the struct. I've tried using sizeof(), but I get the following errors:
Cannot take the address of, get the size of, or declare a pointer to a managed type('StatusType')
'StatusType' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.RunTime.InteropServices.Marshal.SizeOf)
Why is this happening? I'm using sizeof() correctly (on a type name). Using Marshal.SizeOf() would be incorrect because I'm not working with unmanaged code. What is the correct approach?
My struct is as follows:
[StructLayout(LayoutKind.Sequential)]
struct StatusType
{
    ushort VehID;
    ushort Location;
    ushort Destination;

    // Note: the way Intel Byte-swaps, the 16-bit definition below is "backwards" from the way a human may view things
    [FlagsAttribute]
    enum firstByte : uint
    {
        Battery = 2,
        Reverse = 1,
        LiveDINO = 1,
        ActuallyCharging = 1,
        BothLoads = 2,
        AttemptingToCharge = 1
    };

    [FlagsAttribute]
    enum secondByte : uint
    {
        Manual = 1,
        AutoReady = 1,
        Released = 1,
        Unused1 = 1,
        CVS = 3,
        RequestStop = 1
    };
    // End byte-swap note

    [FlagsAttribute]
    enum thirdByte : ushort { CmdParsingError = 8 };
    [FlagsAttribute]
    enum fourthByte : ushort { Error = 8 };

    [FlagsAttribute]
    enum fifthByte : ushort
    {
        TagReadCycles = 4,
        Unused = 4
    };

    [FlagsAttribute]
    enum sixthByte : ushort { Condition = 8 };

    byte[] Tag;
    ushort CCUInputs;

    [StructLayout(LayoutKind.Sequential)]
    struct union
    {
        ushort ShortCheckSum;
        ushort DestParam;
    }

    ushort CurrentLiftHeight;
    ushort PCLInputs;

    [FlagsAttribute]
    enum seventhByte : ushort
    {
        Unused2 = 8
    };

    [FlagsAttribute]
    enum eigthByte : ushort
    {
        BatteryVoltage = 6,
        Unused3 = 2
    };

    ushort LongCheckSum;
}

A: I guess byte[] Tag; is your problem. Take a look at this MSDN article.
Especially this sentence:

One-dimensional arrays of blittable types, such as an array of integers. However, a type that contains a variable array of blittable types is not itself blittable.


text:
Q: how to reduce dataFrame wisely I want to  transform the following dataFrmae structure where we have details regarding each id and kpi couple of records one with the value_left and the 2nd for the value_right I want to group the 2 records into a single record (as you see in the expected results)
i want to reduce the fillowing dataFrame
+---+---+----------+-----------+
| id|kpi|value_left|value_right|
+---+---+----------+-----------+
|  1|sum|        10|       null|
|  1|sum|      null|         20|
|  2|avg|        15|       null|
|  2|avg|      null|         15|
+---+---+----------+-----------+

Expected output dataFrame
+---+---+----------+-----------+
| id|kpi|value_left|value_right|
+---+---+----------+-----------+
|  1|sum|        10|         20|
|  2|avg|        15|         15|
+---+---+----------+-----------+

expected dataFrame


text:
Q: Adapting images to different screen widths for faster loading time I have a website with slide show, and I'd like those slides to be high quality for somebody who views website on a large screen. But the problem is if I load images with 4096*1800px into my image folder it looks good on any device, but when I'm trying to load website on my phone I don't really need that high of an image quality, I'd rather load something like 400*180px, that image would be 10 times less in size.
So my plan is to have html load different images dependently on screen resolution.
I thought about writing a script that would make a change in a regular html like this:
Change this:

To this:

Or this:

and so on.
Is this the best way to do it, or are there better ways?
Thanks a lot

A: i think you are trying to find the best responsive image solution. I personally prefer the HISRC with a jQuery and Html approach using a html tag as shown below,

and a javaScript as shown below,
$(document).ready(function(){
  $(".hisrc").hisrc();
});

but there are many other type of solutions which you might be more prefered as shown here


text:
Q: marge swipe button with Google map markers I have a google map with markers, I wanted to intergrade it with ebanx
/swipe-button but When I try to swipe the button I get the following error

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ebanx.swipebtn.SwipeButton.setOnStateChangeListener(com.ebanx.swipebtn.OnStateChangeListener)' on a null object reference

Bellow is my Code
MapsActivity.java
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private List<LocationModel> mListMarker = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        getAllDataLocationLatLng();

        swipe(); // I call it from here

    }

    private void getAllDataLocationLatLng(){
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("Menampilkan data marker ..");
        dialog.show();

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<ListLocationModel> call = apiService.getAllLocation();
        call.enqueue(new Callback<ListLocationModel>() {
            @Override
            public void onResponse(Call<ListLocationModel> call, Response<ListLocationModel> response) {
                dialog.dismiss();
                mListMarker = response.body().getmData();
                initMarker(mListMarker);
            }

            @Override
            public void onFailure(Call<ListLocationModel> call, Throwable t) {
                dialog.dismiss();
                Toast.makeText(MapsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void initMarker(List<LocationModel> listData){

        for (int i=0; i<mListMarker.size(); i++){

            LatLng location = new LatLng(Double.parseDouble(mListMarker.get(i).getLatutide()), Double.parseDouble(mListMarker.get(i).getLongitude()));

            mMap.addMarker(new MarkerOptions().position(location).title(mListMarker.get(i).getImageLocationName()));

            LatLng latLng = new LatLng(Double.parseDouble(mListMarker.get(0).getLatutide()), Double.parseDouble(mListMarker.get(0).getLongitude()));

            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLng.latitude,latLng.longitude), 11.0f));
        }

    }
//ebanx /swipe-button code
    private void swipe(){

        SwipeButton swipeButton = (SwipeButton)findViewById(R.id.swipe_button);
        swipeButton.setOnStateChangeListener(new OnStateChangeListener() {
            @Override
            public void onStateChange(boolean active) {
                /*
                More code here*/
            }
        });
    }
}

Activity_Maps.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

    <com.ebanx.swipebtn.SwipeButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="18sp"
        android:layout_alignParentBottom="true"
        app:inner_text_background="@drawable/inner_text_shape"
        app:button_image_disabled="@drawable/ic_lock_open_black_24dp"
        app:button_image_enabled="@drawable/ic_lock_outline_black_24dp"
        app:button_background="@drawable/shape_button2"
        app:inner_text="Swipe to Unlock"
        app:inner_text_size="20sp"
        app:inner_text_bottom_padding="15dp"
        app:inner_text_top_padding="15dp"
        app:button_top_padding="15dp"
        app:button_right_padding="15dp"
        app:button_bottom_padding="15dp"
        app:button_left_padding="15dp"
        />

</RelativeLayout>


text:
Q: Angular Meteor 1.3 Ionic - how add ngCordova? I would like to add ngCordova in my Angular Meteor 1.3 Ionic Project.

*

*I based to the following example but without success (probably cause it's not Meteor 1.3) : https://github.com/netanelgilad/meteor-ionic-example

*I tested this package https://github.com/netanelgilad/meteor-ng-cordova but  it doesn't work (probably, its no work with meteor 1.3)

=> I've got this error on google chrome console :
partyAdd.js:30 Uncaught TypeError: _angular2.default.module(...).component is not a function
=> I've got this error on Ios Simulator console (on Safari) :
TypeError: _angular2['default'].module(name, [_angularMeteor2['default']]).component is not a function. (In '_angular2['default'].module(name, [_angularMeteor2['default']]).component', '_angular2['default'].module(name, [_angularMeteor2['default']]).component' is undefined)
Could you help me please to add ngCordova ?
from this tutoriel : http://www.angular-meteor.com/tutorials/socially/angular1/ionic
Thank you

A: I found a solution, see it fits for you:
First install angular-component

*

*meteor npm install --save angular-component

Then add in your main.js

*

*import 'angular-component';

A: npm install --save ng-cordova
Then, where you define your main app's angular module (in my case at the top of app.js) add:
import 'ng-cordova'
Of course, remove any Atmosphere package you might have had for ngCordova if you're upgrading from Meteor 1.2


text:
Q: In rabbitMQ management console, under connection section, what does the ip and port mean in connection name? I have this rabbitMQ docker container running:
version: '3'
services:
  rabbitmq:
    image: rabbitmq:3-management-alpine
    environment:
      - RABBITMQ_DEFAULT_USER=guest
      - RABBITMQ_DEFAULT_PASS=guest
    ports:
        - 5672:5672
        - 15672:15672
    volumes:
        - ./.rabbitmq/data/:/var/lib/rabbitmq
        - ./.rabbitmq/log/:/var/log/rabbitmq

and it runs well.
I have a nodejs script put_message_into_queue.ts, that connects to it and tries to put some message into a queue.
I also have some worker code in another script that consumes messages in the same queue.
As I check the management console:

I can see two connections, corresponding to the two scripts running different processes.
If I click one of the connections:

About the title:  Connection 172.21.0.1:56526 -> 172.21.0.2:5672:
172.21.0.1: what does this address mean?
56526:  what does this port mean?
172.21.0.2: this should be the ip address of the rabbitMQ docker container
5672: this is the port specified in the docker-compose
How is 172.21.0.1:56526 related to one of my running script?
When I run the script, it does not run on any port.
so what is 172.21.0.1:56526?

A: Those connections are coming from somewhere outside of Docker; maybe another process on the host or a different system entirely.  It's hard to say more than this.
In TCP, both sides of the connection have an IP address and a port number.  If you're connecting to Stack Overflow, you're sending the HTTP request to some address (for me, it looks like 151.101.1.69) and port 443, but the response data goes back to your local IP address and a randomly assigned port.  RabbitMQ's wire protocol uses TCP as well, and the port 56526 is the randomly assigned port from the client.  You'd see the same random ports looking at a non-container RabbitMQ console.
Docker sets up a network address translation layer to provide container-private IP addresses.  In your example, it looks like the Docker network is the IPv4 network 172.21.0.0/16, and the RabbitMQ broker has an arbitrary access on that network.  A typical convention is for an external-facing router to have the first address on the network, and Docker sets this up as well; 172.21.0.1 is the address corresponding to the host, in this case.
The way Docker port mappings work internally tends to lose the actual origin address.  There's a connection from somewhere to the host at the first mapped port number, and a connection from Docker to the second port number, but the two connections lose a direct association.  This very occasionally matters for diagnostics and not-especially-secure IP ACLing; see for example How can I access (forward) the public HTTP request IP address inside a docker compose network?.
So those parts are:

*

*172.21.0.1 is the host's IP address on the Docker network

*56526 is the randomly-chosen TCP source port

*172.21.0.2 is the container-private IP address

*5672 is the TCP port on which the process listens, which should also be the second Compose ports: number


text:
Q: Rails Routing not passing ID In my rails app, my first, I am having issues with finding the right routing. The routing I have does not pass the variable @annotation nor the id.
Using
<%= link_to 'Annotate', annotate_path(@annotation), :class => "btn btn-default" %>

I want to open a page
Routes - amongst other, these are the routes I have tried for this resource:
resources :annotations do
    resources :comments
    get "annotate", on: :member

and
get "annotations/:id/annotate" => "annotations#annotate", as: 'annotate'

The later one opens the page, using url http://localhost:3000/annotations/7/annotate - yet I get an error message like undefined method 'name' for nil:NilClass when using <%= @annotation.name %>
In my controller, I have (not complete):
private

def annotate
  @annotation = Annotation.find(params[:id])
end

How to go about?


text:
Q: How to Select today's date from a calender using Protractor I'm writing a script in Protractor and I have a calendar in my angular application.
I used element(by.css('Today's date')).click(); to select today's date from the calender. But, I have to change the code everyday to select the today's date.
So, Is there a specific anyway to select the today's date from the calendar?
Thanks. :)

A: Use the following code.
 var pickerDue = element(by.model("supplier.enroll_date"));

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

if(dd<10) {
    dd='0'+dd
}

if(mm<10) {
    mm='0'+mm
}

today = yyyy+'-'+mm+'-'+dd;

pickerDue.clear();
pickerDue.sendKeys(today);

For more information look at alecxe's answer here.
Hope this helps. :)


text:
Q: Filling in the blank There is this sentence I wrote, yet I am struggling to find a fitting word for it to be complete.
The sentence is Family is the solid foundation on which the .... of society rests

A: A frequent phrase to convey this meaning is "X is the backbone of Y," so you could say "Family is the backbone of society." You could also simply say "Family is the foundation of society." Both of these simply state that family is integral to society's existence.
In the sentence "Family is the solid foundation on which the _ of society rests," the _ should be filled with an aspect of society that family is protecting. If you have a singular aspect of society that you believe family is specifically beneficial for, put it there. You could say "on which the structure of society rests," which could have two meanings: Either that the organizational structure of the way society is made up starts with the family, or it continues the metaphor started by "family is the solid foundation." The metaphor of "solid foundation" references the foundation of a building, so "structure," being a synonym for building, compliments the metaphor. However, because "structure" merely continues the "foundation" metaphor, you are using many words to say very little. You could simply say "Family is the foundation of society" and it would have the same meaning.
I don't want to give you many more examples, because this sentence introduces the idea behind your argument, so without knowing that I can't tell you what you should put there, but you could say something like "Family is the solid foundation on which the moral fiber of society rests." In this case, you are arguing that the family unit causes a moral society, and without the family society would be immoral. I would think about what you are trying to say in your essay, and pick one of the reasons family is important to society to fill in the blank.


text:
Q: How to align text to center with custom font-family applied to Textbox in winRT XAML app I am working on winRT C# app. I have Textbox with custom font-family. Due to custom font-family my text in Textbox is aligned to top of Textbox. I tried to set VerticalContentAlignment to "center" but it still not working.

A: I'm not so sure it's because of your font, and more likely expected behavior of the TextBox. I would take a look at the control template for your TextBox and check your Setter's and ContentPresenter to see if there isn't a property set to make it that way. Otherwise I think you can touch it via something like;
<TextBox>
  <TextBox.Resources>
      <Style TargetType="TextBlock">
         <Setter Property="VerticalAlignment" Value="Center"/>
      </Style>
  </TextBox.Resources>
</TextBox>


text:
Q: How can I get the content from a UIWebView? I need to get the first paragraph of each page from a UIWebView. How can I get this?
I have also one code for regular expression detection, but it gives the paragraph class name instead of paragraph contents:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<p\\s[\\s\\S]*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?"
                             options:NSRegularExpressionCaseInsensitive
                             error:&error];

[regex enumerateMatchesInString:html
                        options:0
                        range:NSMakeRange(0, [html length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSString *img = [html substringWithRange:[result rangeAtIndex:2]];
    NSLog(@"img src %@",img);
}];

NSString *classs=[webView stringByEvaluatingJavaScriptFromString:@"document.getElementbyClassName(img)"];

A: The most robust way to do this is to execute some javascript code in the context of the web view which locates the first paragraph element in the document and returns its text. You can do this using UIWebView's stringByEvaluatingJavaScriptFromString method.
The code below starts off by retrieving an array of all elements in the document with the tag name P (this assumes the text you are looking for is in these elements, if not you'll have more work to do). It then checks if there is at least one paragraph element, and if so, it returns its text content. Otherwise, it returns the empty string.
- (void)webViewDidFinishLoad:(UIWebView *)_webView
{
    NSString *code = @"var paragraphs = document.getElementsByTagName('P');"
                      "paragraphs.length > 0 ? paragraphs[0].innerText : '';";
    NSString *text = [_webView stringByEvaluatingJavaScriptFromString: code];
    // ... do something with text ...
}

You can run arbitrary javascript code in the context of the web view if you want to examine or change other aspects of the document.


text:
Q: Finding end of file in spreadsheets Is there an easy way to tell when youve reached the end of a spreadsheet file when working with openpyxl? Or does someone have an easy idea how to code this task in Python3? I'm working on a program that iterates through rows, selects & rewrites certain data. I want the program to be able to jump out of the loop on its own without having to input a number at the beginning.
Currently, I'm just using the following loop but it only works because I know the file ends at line 49:
while i <=50:

I was considering something that would check for several blank lines in a row, like this piece of code, to start the loop but it seems very imperfect:
while sheet["A"+str(i)].value!=0 and sheet["A"+str(i+1)].value!=0 and sheet["A"+str(i+2)].value!=0:

Any suggestions would be helpful.
Thanks

The easy answer is:
lastrow=sheet.max_row
The counter in the loop can then be set to terminate at lastrow.
Thanks for your input Roland.
Unfortunately the documentation for openpyxl I have been utilizing does not list this function, Charlie.

A: You can iterate over a worksheet with the openpyxl.worksheet.Worksheet.iter_rows() or openpyxl.worksheet.Worksheet.iter_columns() methods.
Alternatively you could use the openpyxl.worksheet.Worksheet.rows or openpyxl.worksheet.Worksheet.colums properties. Those are iterators that are supposed to work over the whole file.

But for my own limited purposes of reading xlsx files, I tend to just open them as a ZipFile and grab the data that I want from the individual sheets using regular expressions. Works fine for me.
Below is an example. It extracts the hours worked on different projects from an xlsx-file containing timesheets for an entire year. For every sheet (that represents a single workday) I need to extract the project numbers and hours from a specific range of cells.
from collections import defaultdict
from zipfile import ZipFile
import os.path
import re
import sys

__version__ = '1.1.0'

if len(sys.argv) == 1:
    binary = os.path.basename(sys.argv[0])
    print("{} ver. {}".format(binary, __version__), file=sys.stderr)
    print("Usage: {} [file ...]".format(binary), file=sys.stderr)
    sys.exit(0)
del sys.argv[0]  # delete the name of the script.
# Real work starts here.
projects = defaultdict(int)
wbre = re.compile('<sheet name="[0-9]{4}-?[0-9]{1,2}-?[0-9]{1,2}'
                '".*?"rId([0-9]{1,3})"/>')
Anum = re.compile('<c r="A([0-9]{1,2})" s="[^"]+"><v>(.*?)</v></c>')
Astr = re.compile('<c r="A([0-9]{1,2})" s="[^"]+" t="s"><v>(.*?)</v></c>')
shre = re.compile('<t[^>]*>(.*?)</t>')
Fre = re.compile('<c r="F([0-9]{1,2})" s="[^"]+"><f.*?><v>(.*?)</v></c>')
for fn in sys.argv:
    z = ZipFile(fn)
    # Create a list of the shared strings.
    with z.open('xl/sharedStrings.xml') as sstr:
        ssdata = sstr.read().decode('utf-8')
    shstr = shre.findall(ssdata)
    # Create a list of worksheet numbers. The name of the workheets matches
    # NNNN-NN-NN where N is in 0--9.
    with z.open('xl/workbook.xml') as wb:
        wbdata = wb.read().decode('utf-8')
    matches = wbre.findall(wbdata)
    for shnum in matches:
        with z.open('xl/worksheets/sheet{}.xml'.format(shnum)) as ws:
            wsdata = ws.read().decode('utf-8')
        # Extract the data from column A, rows 4 - 22.
        A = {int(k): v for k, v in Anum.findall(wsdata) if 3 < int(k) < 23}
        As = {int(k): shstr[int(v)] for k, v in Astr.findall(wsdata)
            if 3 < int(k) < 23}
        A.update(As)
        # Extract the data from column F, rows 4 - 22.
        F = {int(k): float(v) for k, v in Fre.findall(wsdata)
            if 3 < int(k) < 23}
        idxA, idxF = set(A.keys()), set(F.keys())
        # Cross-reference project numbers and hours.
        for k in idxA & idxF:
            projects[A[k]] += F[k]
        for k in idxF - idxA:
            projects['geen'] += F[k]
    z.close()
    t = sorted([(k, v) for k, v in projects.items()], key=lambda x: x[1],
            reverse=True)
    total = sum(d[1] for d in t)
    for k, v in t:
        print('{:5}: {:.1f} uur ({:.1f}%)'.format(k, v, 100*v/total))
    print('totaal: {:.0f} uur'.format(sum(projects.values())))

To develop this code, I unzipped an xlsx file and listed the xml files in it with xmllint --format to make them human-readable.

A: oneway to find end is to use dimension property:
import re
from openpyxl import load_workbook

def row_count(ws):
    return int(re.search('(\d+)$',ws.dimensions).group(1))

ws = load_workbook('your_spreadsheet.xlsx')
ws = ws.active
rows_num = row_count(ws)


text:
Q: equal() Method doesn't work in Java The following code snippet doesn't work. Why? They are objects of the same class, and they have same value of instance variable. What is the problem?
Pen bluePen = new Pen("Faber Castel");
Pen bluePen1 = new Pen("Faber Castel");

if( bluePen.equals(bluePen1) )
    System.out.println("They are equal");

The output is empty. When I did like that:
Pen bluePen = new Pen();
Pen varPen = bluePen;

if( bluePen == varPen)
    System.out.println("They are identical");

There is no problem. The output is "They are identical".
I was trying to understand the difference between == and equal() method. I read the differences of these two thing in this website. But I'm confused on account of the following code snippet not to work properly:
Pen bluePen = new Pen("Faber Castel");
Pen bluePen1 = new Pen("Faber Castel");

if( bluePen.equals(bluePen1) )
    System.out.println("They are equal");

Could anyone explain to me why the code above don't output "They are equal"?

A: From this question (Why do we have to override the equals() method in Java?), you can read that the default way Java compares two objects is through their memory address. If you create two instances, both instances will have a different memory address. Hence, they are not equal. (Bottom line is that the method does work, but not as you'd expected)
That is why you have to override the equals method in your Pen class in order to 'tell' Java that if Pen.Name equals, the object itself equals.

A: How do you define "equal"?
Java doesn't know anything intuitive about your objects.  It can compile and run the code, but it can't tell you which members are important when determining things like equality or sort order or anything like that.  That's logic that you need to define.  In the absence of that logic, the default implementation is reference equality.
In your first example, the variables refer to two different object instances.  So they're not equal.  In your second example, the variables refer to the same object instance.  So they are equal.
In order to define equality, you need to override equals() (and hashcode()) in your class.  Something like:
@Override
public int hashCode() {
    // TODO: compute and return a hash code
}

@Override
public boolean equals(Object obj) {
   // TODO: determine and return if the supplied instance is logically equal to the current instance
}

There are many good examples online of how to effectively implement these methods.  Effectively the logic is simple, though.  hashCode() should return a value which would be unique for any "non-equal" instance of the object, computed based on the fields used to determine equality.  And equals() should determine that equality from those fields.
The overall concept becomes semantically very important when you begin to consider what objects represent in various business logic domains.  For example, what makes two Person objects equal?  If their names are the same?  Clearly not, because two people can have the same name.  A combination of their name, address, and phone number?  Nope.  (My brother and my father shared all of those attributes for 20 years.)  What combination of attributes ensures that one Person is distinct from another Person?  The answer would likely differ vastly between business domains.

A: In Java, when the "==" operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
The equals() method actually behaves the same as the "==" operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory.
. You can even override the equals() method to define yourself when an object is equal to another


text:
Q: storing nsdictionay in nsarray using separator I want to display an image and some text under that image,, i was thinking of using NSDictionary :
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"Tree:shajrah", @"1",
                      @"Milk:haleeb", @"2",
                      nil];
NSString *sep = @":";

I want to know after this step how can I store it in NSArray using separator?
Thank you,
Dalal

A: This isn't very good design. Instead, you should create a new class that contains the UIImage and the text as properties (and anything else you need), and replace your NSDictionary with NSArray of your class.


text:
Q: What are the possible negative effects of reusing the same async callback for C# socket BeginReceive? I was wondering what the implications of using the same async callback as opposed to creating a new one each time BeginReceive is called. Can this produce exceptions, problems down the line, undesirable behavior?
For example:
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                     new AsyncCallback(ReceiveCallback), state);

AsyncCallback asyncCallback = new AsyncCallback(ReceiveCallback);
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, asyncCallback, state);

Pretend the creation of the new async callback is not right next to BeginReceive and only called once.

A: Look at the AsyncCallback docs and you will see that in the example they uses the same instance, so it should be fine.
If you think about it AsyncCallback is basically a delegate which is some kind of pointer to a method, the async operation needs to invoke something after completion and it really does not care if the delegate is reused or not, the delegate points to some code and this callback will be executed.

A: I've used the same one in the past and didn't experience any issues.  It shouldn't matter because it's just a delegate.


text:
Q: MySQL chain replication I have 3 servers A, B and C. What I want to do is replicate databases like this A->B->C, where A is replicating DB1 and DB2 to B and B is replicating those same databases to C, but I would also like to add an additional database from B that will replicated to C.
In other words, I want to replicate databases like this:
A (DB1, DB2) -> B (DB1, DB2) + DB3 -> C (DB1, DB2, DB3)

Is this possible?

A: Yes
ServerB will just replicate all databases to ServerC (ignoring replicate-ignore-db for now). There is no setting that limits ServerC to getting data that exists only on ServerA
That is,  A(master) ->B (slave) is unrelated to B(master) -> C(slave) and A and C have no knowledge or replication dependency on each other


text:
Q: Adding EXIF DateTime to a jpeg image Problem:
WebEye.WebCameraControl makes an excellent job to capture a picture (Bitmap) in a WinForm App.
When saving the image (Bitmap): image.Save("filename.jpg", ImageFormat.Jpeg) it will not add any
exif data, my need is just datetime.
There are many exampels how to read PropertyItems from an existing jpg, change attributes and save the image. But I cannot find any that adds new propertyItems to an "exif-empty" image.
There is image.SetPropertyItem(propItem) that looks promising but the propItem it self cannot be instantiated but retrieved from an image image.PropertyItems[x] Yes, I do miss something here but what?
Please save my day. This issue is driving me nutts.
Best regards
Stephan


text:
Q: Pass Linux variable in Oracle script How to pass Linux variable in Oracle code?
I need to pass it in below format and it should not ask for "enter a value for 1:"
Please advise.
mount='/u08/dbname/'
sqlplus -s "/ as sysdba" <<EOF
set serveroutput on;
set feedback off;
set verify off;
set heading off;
DECLARE
line varchar(100);
BEGIN
line := '&1';
if (5 > 0)then
dbms_output.put_line(line);
end if;
END;
/
$mount
EOF

A: export mount='/u08/dbname/'
sqlplus -s "/ as sysdba" <<EOF
set serveroutput on;
set feedback off;
set verify off;
set heading off;
DECLARE
line varchar(100);
BEGIN
line := '$mount';
if (5 > 0) then
dbms_output.put_line(line);
end if;
END;
/
$mount
EOF

You can assign the output of a Unix/Linux command to a variable too:
export SPACE=$(df --output=avail -m /dev/sda8 | tail -1)