text:
Q: Save image from mjpeg stream
I'm trying to capture image(jpeg) from MJPEG stream. According to this tutorial http://www.walking-productions.com/notslop/2010/04/20/motion-jpeg-in-flash-and-java/
I should just save date starting from Content-Length: and ending at –myboundary. But for some reason when I open a saved file I get this message Can't open this picture because the file appears to be damaged, corrupted or is too large.
public class MJPEGParser{

    public static void main(String[] args){
        new MJPEGParser("http://192.168.0.100/video4.mjpg");
    }

    public MJPEGParser(String mjpeg_url){
        try{

            URL url = new URL(mjpeg_url);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while((line = in.readLine()) != null){
                System.out.println(line);
                if(line.contains("Content-Length:")){
                    BufferedWriter out = new BufferedWriter(new FileWriter("out.jpeg"));
                    String content = in.readLine();
                    while(!content.contains("--myboundary")){
                        out.write(content);
                        System.out.println(content);
                        content = in.readLine();

                    }
                    out.close();
                    in.close();
                    System.exit(0);
                }
            }

            in.close();

        }catch(Exception e){
            e.printStackTrace();
        }
      }
}

I will be really grateful for any tips.

A: There are many things which might cause your code to fail for you:

*

*Not all MJPEG streams are encoded in the MIME-like fashion your tutorial suggests.
Quoting Wikipedia:

[…] there is no document that defines a single exact format that is universally recognized as a complete specification of "Motion JPEG" for use in all contexts.

For example, one may use MJPEG as the video codec of an AVI (i.e. RIFF) file. So make sure your input file is in the format the tutorial describes.

*The text --myboundary is almost certainly a placeholder. In a typical multipart MIME message, the global MIME header will provide a boundary attribute, indicating what string is actually used to delimit parts. You'll have to prepend -- to the string given there.

*As you are using Reader and Writer, you are operating on characters, not bytes. Depending on your locale, there might not be a 1:1 correspondence between these two, thus breaking the binary format of the data in the process. You should either operate on byte streams, or explicitely use some character encoding like ISO-8859-1 which does have such a 1:1 correspondence.

A: I was trying to solve this issue recently, and my google research brought me here multiple times. I eventually solved the problem. The key part is using BufferedInputStream and FileOutputStream to read and write jpeg bytes, while also concatenating byte buffers into a string to read and identify headers between frames:
int inputLine;
String s="";
byte[] buf = new byte[1]; //reading byte by byte

URL url = new URL("http://127.0.0.1:8080/?action=stream");
BufferedInputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new FileOutputStream("output.jpg");

while ((inputLine = in.read(buf)) != -1) {

    s= s+ new String(buf, 0, inputLine);

    if (s.contains("boundarydonotcross")){
        System.out.println("Found a new header");
        s="";
    }

The complete code is here if anybody needs it:
https://github.com/BabelCoding/MJPEG-to-JPG


text:
Q: Form of Matrix for Reflection about a Line I've seen a bunch of variations on the wonderful properties of this specific matrix. My textbook gives one algebraic form in particular that I'm having a bit of trouble verifying:

Any help here? I feel like factoring out $\frac{1}{u_1^2+u_2^2}$  might be the way to start. Thanks!

A: Since $\left[\begin{matrix}u_1\\u_2\end{matrix}\right]$ is a unit vector, we know $u_1^2+u_2^2=1$. We have a couple things to prove: first that $2u_1^2-1=-(2u_2^2-1)$ (that is the claim that we have $a$ as the top left entry $-a$ as the bottom right entry), and second that $1=a^2+b^2=(2u_1^2-1)^2+(2u_1u_2)^2$.
Part $1$:
$$u_1^2+u_2^2=1\implies u_1^2-1=-u_2^2\implies2u_1^2-2=-2u_2^2\implies 2u_1^2-1=-(2u_2^2-1)$$
as desired.
Part $2$:
$$\begin{align}(2u_1^2-1)^2+(2u_1u_2)^2&=-(2u_1^2-1)(2u_2^2-1)+4u_1^2u_2^2
\\&=-(4u_1^2u_2^2-2(u_1^2+u_2^2)+1)+4u_1^2u_2^2
\\&=-(4u_1^2u_2^2-2+1)+4u_1^2u_2^2
\\&=-4u_1^2u_2^2+1+4u_1^2u_2^2
\\&=1\end{align}$$
as desired.
Pretty much any reasonable algebra manipulation should work out, just some ways are faster than others.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error at creating new Fragment on compileSdkVersion 22 on Android App : onAttach() method fails I just use the menu to create new fragment and by default it's throwing an error with the fragment generated file, I did not add any code. The problem is in the onAttach() method
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

It says: "onAttach(android.app.Activity) in fragment cannot be applied to (android.content.Context)"
My imports on the fragment file:
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

My gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "license.j4ftech.com.mapevents"
        minSdkVersion 19
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.android.support:support-v4:22.2.0'
}

My gradle file:
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "license.j4ftech.com.mapevents"
        minSdkVersion 19
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.android.support:support-v4:22.2.0'
}

How can I solve this issue?

A: The method onAttach(Context context) was introduced in API level 23. Your compile/target SDK version is 22 which is why the project cannot find the method definition. You can either switch back to using the old deprecated method onAttach(Activity a) or change the appcompat version to the latest (23.1.1) to be able to use the new method.
Use the latest support library:
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'

in your gradle file and set compileSdkVersion/targetSdkVersion to 23.


text:
Q: Best practice of error handling on controller and interactor # users_show_controller.rb
class Controllers::Users::Show
  include Hanami::Action

  params do
    required(:id).filled(:str?)
  end

  def call(params)
    result = users_show_interactor(id: params[:id])

    halt 404 if result.failure?
    @user = result.user
  end
end

# users_show_interactor.rb
class Users::Show::Interactor
  include Hanami::Interactor

  expose :user
  def call(:id)
    @user = UserRepository.find_by(:id)
  end
end

I have a controller and a interactor like above.
And I'm considering the better way to distinguish ClientError from ServerError, on the controller.
I think It is nice if I could handle an error like below.
handle_exeption StandardError => :some_handler

But, hanami-interactor wraps errors raised inside themselves and so, controller receive errors through result object from interactor.
I don't think that re-raising an error on the controller is good way.
result = some_interactor.call(params)
raise result.error if result.failure

How about implementing the error handler like this?
I know the if statement will increase easily and so this way is not smart.
def call(params)
  result = some_interactor.call(params)
  handle_error(result.error) if result.faulure?
end

private

def handle_error(error)
  return handle_client_error(error) if error.is_a?(ClientError)
  return server_error(error) if error.is_a?(ServerError)
end

A: Not actually hanami-oriented way, but please have a look at dry-monads with do notation. The basic idea is that you can write the interactor-like processing code in the following way
def some_action
  value_1 = yield step_1
  value_2 = yield step_2(value_1)
  return yield(step_3(value_2))
end

def step_1
  if condition
    Success(some_value)
  else
    Failure(:some_error_code)
  end
end

def step_2
  if condition
    Success(some_value)
  else
    Failure(:some_error_code_2)
  end
end

Then in the controller you can match the failures using dry-matcher:
matcher.(result) do |m|
  m.success do |v|
    # ok
  end

  m.failure :some_error_code do |v|
    halt 400
  end

  m.failure :some_error_2 do |v|
    halt 422
  end
end

The matcher may be defined in the prepend code for all controllers, so it's easy to remove the code duplication.

A: Hanami way is validating input parameters before each request handler. So, ClientError must be identified always before actions logic.
halt 400 unless params.valid? #halt ClientError
#your code
result = users_show_interactor(id: params[:id])
halt 422 if result.failure? #ServerError
halt 404 unless result.user
@user = result.user

A: I normally go about by raising scoped errors in the interactor, then the controller only has to rescue the errors raised by the interactor and return the appropriate status response.
Interactor:
module Users
  class Delete
    include Tnt::Interactor

    class UserNotFoundError < ApplicationError; end

    def call(report_id)
      deleted = UserRepository.new.delete(report_id)

      fail_with!(UserNotFoundError) unless deleted
    end
  end
end

Controller:
module Api::Controllers::Users
  class Destroy
    include Api::Action
    include Api::Halt

    params do
      required(:id).filled(:str?, :uuid?)
    end

    def call(params)
      halt 422 unless params.valid?

      Users::Delete.new.call(params[:id])
    rescue Users::Delete::UserNotFoundError => e
      halt_with_status_and_error(404, e)
    end
  end
end

fail_with! and halt_with_status_and_error are helper methods common to my interactors and controllers, respectively.
# module Api::Halt
def halt_with_status_and_error(status, error = ApplicationError)
  halt status, JSON.generate(
    errors: [{ key: error.key, message: error.message }],
  )
end

# module Tnt::Interactor
def fail_with!(exception)
  @__result.fail!
  raise exception
end


text:
Q: How would it be a good way to keep the title of the notification and the date separate? In both orientations of the device

*

*Title: app_nome -> TWW / SALDO - HOSPITAL... (Example)

*Time: dt_cadastro_hora -> 08:56 (Example)

NotificationsPage.xaml
<RefreshView x:DataType="local:NotificacoesViewModel"
                                 Command="{Binding LoadItemsCommand}"
                                 IsRefreshing="{Binding IsBusy, Mode=TwoWay}"
                                 Padding="0,15,0,0">
                        <CollectionView x:Name="ItemsListView"
                                        ItemsSource="{Binding Notificacoes}"
                                        SelectionMode="None"
                                        ItemsUpdatingScrollMode="KeepItemsInView"
                                        VerticalScrollBarVisibility="Never"
                                        HorizontalScrollBarVisibility="Never"
                                        IsGrouped="True">
                            <CollectionView.GroupHeaderTemplate>
                                <DataTemplate x:DataType="model:NotificacaoGrupoData">
                                    <Label Text="{Binding Data_agrupada}"
                                           FontSize="20"
                                           FontAttributes="Bold"
                                           HorizontalTextAlignment="Center"
                                           Padding="0,15,0,15"
                                           Style="{StaticResource LabelDataAgrupadaStyle}"/>
                                </DataTemplate>
                            </CollectionView.GroupHeaderTemplate>

                            <CollectionView.ItemTemplate>
                                <DataTemplate>
                                    <StackLayout x:DataType="model:Notificacao">
                                        <StackLayout Orientation="Horizontal">
                                            <StackLayout.GestureRecognizers>
                                                <TapGestureRecognizer NumberOfTapsRequired="1"
                                                              Command="{Binding Source={RelativeSource AncestorType={x:Type local:NotificacoesViewModel}},
                                                                        Path=NotificacaoSelecionada}"
                                                              CommandParameter="{Binding .}"/>
                                            </StackLayout.GestureRecognizers>
                                            <Image Source="logo"
                                                   HeightRequest="40"
                                                   Margin="0,0,5,0"
                                                   VerticalOptions="CenterAndExpand"/>

                                            <StackLayout VerticalOptions="CenterAndExpand"
                                                         Margin="0,0,10,0">
                                                <FlexLayout JustifyContent="SpaceBetween"
                                                            AlignItems="Center">
                                                    <Label Text="{Binding app_nome}"
                                                           Style="{StaticResource LabelStyle}"
                                                           FontSize="20"
                                                           WidthRequest="230"
                                                           LineBreakMode="TailTruncation"
                                                           FontAttributes="Bold"/>

                                                    <Label Text="{Binding dt_cadastro_hora}"
                                                           Style="{StaticResource LabelStyle}"
                                                           FontSize="13"
                                                           LineBreakMode="NoWrap"
                                                           MinimumWidthRequest="50"
                                                           FontAttributes="Bold"/>
                                                </FlexLayout>

                                                <Label Text="{Binding mensagem}"
                                                       TextType="Html"
                                                       LineBreakMode="TailTruncation"
                                                       Style="{StaticResource LabelStyle}"/>
                                            </StackLayout>

                                            <Label Text=""
                                                   FontFamily="FontAwesomeBold"
                                                   TextColor="#ACACAC"
                                                   FontSize="24"
                                                   HorizontalOptions="EndAndExpand"
                                                   VerticalOptions="CenterAndExpand"
                                                   Style="{StaticResource LabelStyle}">
                                            </Label>
                                        </StackLayout>

                                        <BoxView HeightRequest="1"
                                                 BackgroundColor="#DDDDDD"
                                                 Margin="0,5,0,5"/>
                                    </StackLayout>
                                </DataTemplate>
                            </CollectionView.ItemTemplate>
                        </CollectionView>
</RefreshView>

A: You can try replace
<FlexLayout JustifyContent="SpaceBetween"
            AlignItems="Center">
    <Label Text="{Binding app_nome}"
           Style="{StaticResource LabelStyle}"
           FontSize="20"
           WidthRequest="230"
           LineBreakMode="TailTruncation"
           FontAttributes="Bold"/>

    <Label Text="{Binding dt_cadastro_hora}"
           Style="{StaticResource LabelStyle}"
           FontSize="13"
           LineBreakMode="NoWrap"
           MinimumWidthRequest="50"
           FontAttributes="Bold"/>
</FlexLayout>

By (notice the HorizontalOptions)
<StackLayout Orientation="Horizontal">
    <Label Text="{Binding app_nome}"
           Style="{StaticResource LabelStyle}"
           HorizontalOptions="StartAndExpand"
           FontSize="20"
           WidthRequest="230"
           LineBreakMode="TailTruncation"
           FontAttributes="Bold"/>

    <Label Text="{Binding dt_cadastro_hora}"
           Style="{StaticResource LabelStyle}"
           HorizontalOptions="End"
           FontSize="13"
           LineBreakMode="NoWrap"
           MinimumWidthRequest="50"
           FontAttributes="Bold"/>
</StackLayout>


text:
Q: LINQ method syntax for multiple left join Three tables are needed to be joined together.
Table [Package]

ID (int)
ContainerID (int)
Code (string)
Code2 (string)

Table [UserHasPackages]

UserID (Comes from Identity tables) (string)
PackageID (int)

Table [Container]

ID (int)
Name (string)
Description (string)

Into a viewmodel that represents an object I'd like to display in my view:
public class CustomViewModel
{
    public int ID { get; set; }
    public string Name { get; set; } // Container.Name
    public string Code { get; set; } // Package.Code
    public string Code2 { get; set; } // Package.Code2
}

But I'm having problems doing the join:
List<CustomViewModel> list = new List<CustomViewModel>();

        list = context.Packages.Join(
            context.Containers,
            p => p.ContainerID,
            c => c.ID,
            (p, c) => new { p, c})
        .Join(                                 //error is here
            context.UserHasPackages,
            a => a.p.ID,
            b => b.ApplicationUserId,
            (a, b) => new { a, b })
        .Select(f => new CustomViewModel
        {
            ID = f.p.ID,
            Name = f.c.Name,
            Code = f.p.Code,
            Code2 = f.p.Code2
        }).ToList();

Type arguments for method cannot be inherited from the usage. Try specifying the type arguments explicitly.

Is there another way to do two joins (as described) that's the more-proper way?

SOLUTION
Method based syntax is a no-go here, had to go with query syntax:
var query = (from package in context.Packages
        join container in context.Containers on package.ContainerID equals container.ID
        join userHasPackage in context.UserHasPackages on package.ID equals userHasPackage.PackageID
        where userHasPackage.UserID == "SomeUser"
        select new CustomViewModel
        {
            ID = package.ID,
            Name = container.Name,
            Code = package.Code,
            Code2 = package.Code2
        }).ToList();

A: I'm assuming that you want to join the UserHasPackages table because you wanted to filter the results for a specific user (I just put in a 'SomeUser' because I'm not sure where the 'UserHasPackages.ApplicationUserId' came from) since it is not included on the view model.
I believe something like the following should work:
var list = context.Packages
    .Join(context.Containers, p => p.ContainerID, c => c.ID, (p, c) => new { p, c })
    .Join(context.UserHasPackages, pc => pc.p.ID, u => u.PackageID, (pc, u) => new { pc.p, pc.c, u })
    .Where(pcu => pcu.u.UserID == "SomeUser")
    .Select(pcu => new
    {
        pcu.p.ID,
        pcu.c.Name,
        pcu.p.Code,
        pcu.p.Code2
    });

You could also do this using the query syntax:
var query = from package in context.Packages
            join container in context.Containers on package.ContainerID equals container.ID
            join userHasPackage in context.UserHasPackages on package.ID equals userHasPackage.PackageID
            where userHasPackage.UserID == "SomeUser"
            select new
            {
                package.ID,
                container.Name,
                package.Code,
                package.Code2
            };


text:
Q: How to change a pure (ideal) differentiator system into a practical one using MATLAB/Simulink? A pure/ideal integrator has transfer function H(s)= s.  If we try to get its step response in MATLAB we get the error "Cannot simulate the time response of models with more zeros than poles".
Similarly, if we try to get a step response in Simulink, we get a sharp (very thin) vertical line, which apparently goes to infinity.
How can we convert this ideal (pure) differentiator into a practical one?
I have placed my MATLAB code below:
clc
clear
close all
den=[1]%denominator of transfer function
num=[1 0]%numerator of transfer function
sys=tf(num,den)%transfer function expression of ideal(pure) differentiator system
step(sys)%step response

I am also attaching a snapshot of the Simulink model:

Update: based upon recieved comment & answer, i updated my question and also included snapshot of simulink model where low pass filter transfer function is used in place of derivative block, i also placed snapshot of simulink model where high pass filter transfer function is used in place of derivative block. But i am still confused,which one(Low pass filter or high pass filter) will be better replacement of pure(ideal)derivative block as asked in main question title

A:
How can we convert this ideal (pure) differentiator into a practical
one?

You prevent the anomaly of infinite rise/fall time by using a low-pass filter after your infeasible and impractical step input so that the rise and fall time are quite small but not zero.


text:
Q: How to not be able to access manually /login after you logged in - VueJS? I'm learning VueJS from an Udemy course. In the module about authentication, the instructor didn't make the whole process, so I had to try it by my self for 2 days but I succeeded 90%.
The backend is on firebase, so after login with correct data, I get back a token that I send it to local storage.
With the code that I make it, you can't see the dashboard if you are not authenticated(even you try the route manually), but what I don't like is that you can see the login page after you are authenticated(if you type /signin).
This last part is not normal to be. So if you are authenticated, when you try manually to go to /signin, you can.
In the router.js:
const routes = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: WelcomePage },
    { path: '/signup', component: SignupPage },
    { path: '/signin', component: SigninPage },
    { path: '/dashboard', component: DashboardPage}
  ]
});

routes.beforeEach((to, from, next) => {
  // redirect to login page if not logged in and trying to access a restricted page
  const publicPages = ['/signin', '/signup'];
  const authRequired = !publicPages.includes(to.path);
  const loggedIn = localStorage.getItem('token');
  console.log(loggedIn);
  if (authRequired && !loggedIn) {
    return next('/signin');
  }
  next();
});

And in store.js, inside login action:
if (localStorage.getItem('token')) {
  router.replace("/dashboard");
}

Any idea what to do to /login and /register routes after login so to not be able to see them, even you manually try these routes?
If the user will try manually /signin or /signup, I want to be redirected to /dashboard.

A: In my vue application I just use the router.beforeEach method with meta data plus the state of my token which I pull from my store.
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
      var token = store.getters.loggedIn;
      if (!token ) {
        next({
          path: '/login',
        })
      } else {
        next()
      }
    }else if (to.matched.some(record => record.meta.requiresVisitor)) {
      if (token) {
        next({
          path: '/',
        })
      } else {
        next()
      }
    }
})

It checks each time the route changes.
The requiresVisitor meta is something I placed in my router object
{
    // this is can only be viewed if not logged in.
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ './views/Login.vue'),
    props: true,
    meta: {
      requiresVisitor: true,
      layout: "landing",
    },
  },
{
  // this can only be viewed if logged in.
  path: '/',
  name: 'dashboard',
  component: () => import(/* webpackChunkName: "dashboard" */ './views/Dashboard.vue'),
  props: true,
  meta: {
    requiresAuth: true,
    layout: "default",
   },
  },

you can read more about route guards Here
theses methods are typically used in the entry point to the app main.js or in your router.js file.

A: You can add a per-route guard (https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard) to make the logic only run when /signin and /signup is matched, but if you want to keep it in the loop that runs over all routes you're on the right track -- you just need to invert your logic.
So what you want do is to add another if statement, checking if isLoggedIn is true, and that you're trying to access a public page, and in that case redirect the user to the /dashboard route.
if (!authRequired && loggedIn) {
  next('/dashboard');
  return;
}

A:
Best example of redirection using beforeEach

const routes = [
      {
        path: "/",
        name: "login",
        component: Login,
        meta:{requiresVisitor: true},
      },
      {
        path: "/dashboard",
        name: "dashboard",
        component: Dashboard,
        meta:{requiresVisitor: false},
      }];

    const router = new VueRouter({
      mode: "history",
      base: process.env.BASE_URL,
      routes
    });

export default router;

//Check the user is loged in If yes then move to next url.If not loged
  in so move in else and check the meta and move into next other wise is
  redirect my index url

router.beforeEach((to, from, next) => {
  const isLogged = JSON.parse(localStorage.getItem('username'));
    if (isLogged) next()
    else{
      if(to.meta.requiresVisitor) next()
      else next('/')
    }
})


text:
Q: permissão de pasta php Tenho um sistema open source chamado NOVOSGA funcionando na minha máquina local, mas no servidor de hospedagem não funciona, quando eu tento rodar ele me dá um erro do próprio sistema:
Diretório temporário    /tmp
Permissão requerida: Escrita
Permissão atual: Somente leitura

Session Save Path   /var/lib/php/session/www.painel.sitepainel.com.br/
Permissão requerida: Escrita
Permissão atual: Somente leitura

Entrei em contato com a hospedagem, e eles juram de pé junto que essas permissões já estão de escrita.
Eu vi no código que essas duas pastas podem ser acessadas com estes comandos no php: sys_get_temp_dir() e session_save_path()
É possível eu rodar algum comando em php que me diga a permissão atual destas pastas para eu enviar para o servidor de hospedagem?


text:
Q: How run task asynchronously whith Celery in Django App? My settings.py
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'FBIsystem',
    'mathfilters',
    #'background_task',
    'celery',
    'widget_tweaks',
)

CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ALWAYS_EAGER = 'False'

my celery.py
from __future__ import absolute_import
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_try.settings')

from django.conf import settings
from celery import Celery

app = Celery('celery_try',
             backend='amqp',
             broker='amqp://guest@localhost//')

app.config_from_object('django.conf:settings')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)

@app.task(bind=True)
def debug_task(self):
    print("Request: {0!r}".format(self.request))

i have a view:
def home(request):
    try:
        return render(request, 'app/home.html')
    finally:
        print '1'
        mytask.delay()

and I have a script:

from celery import shared_task

@shared_task()
def mytask():
    time.sleep(10)
    print("Test 1234!")

Actually it render home.html after 10 seconds and then print Test 1234!
My goal is render home.html and AFTER 10 seconds run mytask()
Any solution?

A: The simplest thing you can do is to call asynchronously (as you already do) mytask right before you return the rendered HTML. Something like:
def home(request):
    mytask.apply_async()  # delay() is just apply_async() with *args and *kwargs
    return render(request, 'app/home.html')


text:
Q: Javascript won't display? This is probably a silly question, but for some reason I can't get Javascript to display on my pages. I'm trying it on both notepad and Dreamweaver, and testing them using localhost in XAMP but can't get it to display to test it.
I've tried it also with some very basic code just to see if it works, something like:

A: Use firebug. I typed
now = new Data();

in the console, and I got:

ReferenceError: Data is not defined

Then,
utctime = now.toGMTSTring();

yields this response:

TypeError: now.toGMTSTring is not a function

Final observation: use var when declaring your variables. Most browsers will work with it, but I've had a hard time tracing this error when a script turned out to refuse to work in IE (don't remember which version).


text:
Q: What is SVN snapshot? In the last lines of website http://gfs.sourceforge.net/wiki/index.php/Mac_OSX_Installation
it says
Optional tools
Download the latest SVN snapshot from http://ffmpeg.org/releases/
Unpack and install it.
tar -xvjf ffmpeg-export-snapshot.tar.bz2
cd ffmpeg-export-<insert date here>
./configure --prefix=/opt/gerris
make && make install

i enter this website http://ffmpeg.org/releases/ but there are lots of releases . Which one is SVN snapshot?

A: The svn-snapshot is availible for download, use http://ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2

A: A snapshot, in this sense, is the state of the source code at a point in time. It isn't a release, where the developers decide that this is a good point to package and distribute a nice, tested version software. A snapshot is whatever is there at this point in time, with the latest features and the latest bugs. Many open source projects provide daily snapshots.
You'll find CVS snapshots, svn (Subversion) snapshots, Git snapshots, Mercurial (hg) snapshots, Bazaar (bzr) snapshots, etc. The qualifier is the version control system used by the developers. Some projects use other adjectives like "nightly snapshot", and for the result of building that source code, "nightly build".


text:
Q: Custom function inside controller not found I created a controller with resource. I made a custom function inside it however when I use it as a route in my blade.php it says that it is not defined.
Any help with the error and explanation about it is highly appreciated!!
Blade

Modal title

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
            </button>

            <form action="{{route('inventory.deduct')}}" method="post">

                <button type="button" class="btn btn-primary">Save changes</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

            </form>

custom function inside controller
public function deduct(Type $var = null)
{
    dd("test");
}

Route
Route::resource('inventory', 'InventoryController');

A: Route::post('/inventory/deduct', 'InventoryController@deduct')->name('inventory.deduct');

Add this to your Routes in Web.php file.
Resource only creates the default routes for controller, not the custom ones.

A: Resource route is for index, create, store, show, edit, update and destroy. Your new route is not defined in a resource route. So you have to create a new route to use it. Add this route above your resource route in web.php file
Route::post('inventory/deduct', 'InventoryController@deduct')->name('inventory.deduct');

This will make your route and you can use it in your form and you can make the function to your controller to do what you want to do.


text:
Q: Python3 asc desc sorting Lets assume I've got a following python list(this is only example):
my_list = [{'user': 'Joe', 'score': 14},
           {'user': 'Foo', 'score': 12},
           {'user': 'May', 'score': 12},
           {'user': 'Kat', 'score': 12},
           {'user': 'Doe', 'score': 13}]

I need to sort this list in ascending order by score and descending order by a username.
Expected sort result:
my_list = [{'user': 'May', 'score': 12},
           {'user': 'Kat', 'score': 12},
           {'user': 'Foo', 'score': 12},
           {'user': 'Doe', 'score': 13},
           {'user': 'Joe', 'score': 14}]

So, I could do something like this if I want everything to be in ascending order:
my_list.sort(key=lambda x: (x['score'], x['user']))

For integers it is easy to solve this problem just adding - in front of it:
my_list.sort(key=lambda x: (-x['score'], x['user']))

Unfortunately, strings can not be negative :-|
I need a generic solution that doesn't involve 'reverse=True'. Lambda function is dynamically generated based on a user config.
Thoughts?

A: Your current solution will work fine if you set the reverse parameter of list.sort to True:
>>> my_list = [{'user': 'Joe', 'score': 14},
...            {'user': 'Foo', 'score': 12},
...            {'user': 'May', 'score': 12},
...            {'user': 'Kat', 'score': 12},
...            {'user': 'Doe', 'score': 13}]
>>> my_list.sort(key=lambda x: (-x['score'], x['user']), reverse=True)
>>> pprint(my_list) # pprint makes the nice output
[{'score': 12, 'user': 'May'},
 {'score': 12, 'user': 'Kat'},
 {'score': 12, 'user': 'Foo'},
 {'score': 13, 'user': 'Doe'},
 {'score': 14, 'user': 'Joe'}]
>>>

This will sort the list in reverse order.

Edit:
Since the names and scores have two different sort orders, you will need to use two separate sorts to achieve your desired output:
>>> my_list = [{'user': 'Joe', 'score': 14},
...            {'user': 'Foo', 'score': 12},
...            {'user': 'May', 'score': 12},
...            {'user': 'Kat', 'score': 12},
...            {'user': 'Doe', 'score': 13}]
>>> my_list.sort(key=lambda x: x['user'], reverse=True)
>>> my_list.sort(key=lambda x: x['score'])
>>> pprint(my_list)
[{'score': 12, 'user': 'May'},
 {'score': 12, 'user': 'Kat'},
 {'score': 12, 'user': 'Foo'},
 {'score': 13, 'user': 'Doe'},
 {'score': 14, 'user': 'Joe'}]
>>>

A: The ord of a string can be negative:
my_list.sort(key=lambda x: (x["score"],[-ord(x) for x in x["user"]])))

In [50]:  my_list.sort(key=lambda x: (x["score"],[-ord(x) for x in x["user"]]))

In [51]: my_list
Out[51]:
[{'score': 12, 'user': 'May'},
 {'score': 12, 'user': 'Kat'},
 {'score': 12, 'user': 'Foo'},
 {'score': 13, 'user': 'Doe'},
 {'score': 14, 'user': 'Joe'}]

A: you need to add the reverse=True keyword for descending order.
>>> my_list.sort(key=lambda x: (-x['score'], x['user']),reverse=True)
>>> my_list
[{'score': 12, 'user': 'May'}, {'score': 12, 'user': 'Kat'}, {'score': 12, 'user': 'Foo'}, {'score': 13, 'user': 'Doe'}, {'score': 14, 'user': 'Joe'}]


text:
Q: Navigator Plugin development - Session expiration I'm working on a plugin for ICN and I've managed to have it log in automatically retrieving the username/password from a file by an id which is passed as a parameter in the url. Once a user has logged in there will be no need to relog, however after some time the 'session expiration' will kick in and even after reloading I can't get it to log in again. This might be due to the fact that I'm basing my decision on a single javascript object: ecm.model.desktop.connected.
Right now if ecm.model.desktop.connected is false it will try to log in, this works well until the session expiration, which apparently does not set the ecm.model.desktop.connected to false, it's still set to true. So I'm hoping to learn a way to tell if the session has expired.
This here is my login code:
if (ecm.model.desktop.connected == false || ecm.model.desktop.userId != loginConfig[loginID].username) {
     var http2 = new XMLHttpRequest();
     var url2 = "/navigator/logon.do";
     var params2 = "userid=" + loginConfig[loginID].username + "&password=" + loginConfig[loginID].password;
     http2.open("POST", url2, false);
     http2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     http2.onreadystatechange = function() {//Call a function when the state changes.
          if (http2.readyState == 4 && http2.status == 200) {

          }
     };
     http2.send(params2);
     window.location.reload();
}

A: I managed a workaround avoiding session expiration entirely using a cookie set to expire in 'x' minutes making a sort of session of my own.
First I check if the cookie is created, if it's not it means it either expired or was never created in the first place, so I create it and make a synchronous POST call to logoff.do and reload() the site.
Once created and after reloading I check if the cookie exists once again, since it does I check if ecm.model.desktop.connected is false or the user is trying to log in with a different ID. If that occurs I'll have it log in making a synchronous POST call to logon.do with the proper username/password and then reload().
All done the user has now access to the features offered by my plugin.


text:
Q: Mongo Scala Async Client not writing trying to upsert with the new Scala Async Driver using this code, but the DB never gets created even though this is called many times:
override def insertOrUpdateOne(user: UserNew): Future[Unit] = {
  users.replaceOne(equal("_id", user._id), user)
    .toFuture
    .map(_ => ())
}

mongo client created fine, collection created fine, but the above causes no write to be performed in fact the db is never created (which should happen on the first write). I have other code that uses casbah and that is working synchronously.
users is the Mongo collection with no syntactic sugar from me. (edited)
toFuture seems to do the subscribe (which should trigger the write?) but it still doesn't work. I'm mixing some collections with casbah and one with the async client, the casbah ones work but not the one above using async.
Any ideas?

A: it should be
override def insertOrUpdateOne(user: UserNew): Future[Unit] = {
  users.replaceOne(equal("_id", user._id), user, UpdateOptions().upsert(true))
    .toFuture
    .map(_ => ())
}

Nothing in the docs but when I read the code I see it defaults upsert to false.
BTW this allows us to ignore all the Observable and subscribe stuff and setup of callbacks. Just process the results in a Scala idiomatic someFuture.map() This makes the UsersDaonon-Mongo specific code as an interface. This in turn allows all code in the UsersDaoImplto handle Mongo specific stuff, which enables the Impl to be injected so a runtime choice can be made about which Impl to use. Mongo can be replaced without dependent code caring or knowing about the Impl.


text:
Q: Polyfill for IE background-blend-mode multiply Is there a polyfill / method to make "background-blend-mode: multiply" work on IE browsers?
I found this CodePen: http://codepen.io/brav0/pen/bJDxt but it's not working.
In short what blend does:
with some CSS like this:
.blend {
  background-image: url('mountains.jpg');
  background-color: #5ece7f;
  background-blend-mode: multiply;
}

You can create cool filters that look like this:

A: Looks like this polyfill is trying to use
context.globalCompositeOperation = 'multiply'

and as fas as I know, IE doesn't support this either.
documentation
So, it's a pity, but I don't know of any easy way to polyfill blend modes in IE


text:
Q: FFMPEG returns negative values and stops rendering While trying to get a 16:9 aspect output from any resolution input, I keep running into errors.
This is, what I prompt:
ffmpeg -i "input.mp4" -i "overlay.png" -strict -2 -vcodec h264 -aspect 16:9 -filter_complex "[0]scale=604:-2,pad=604:340:(604-iw)/2:(340-ih)/2[v];[v][1]overlay=x=W-w-5:y=H-h-5" -an "output.mp4"

Errors are:
[0] => [Parsed_pad_1 @ 0xeffca0] Negative values are not acceptable.
[1] => [Parsed_pad_1 @ 0xeffca0] Failed to configure input pad on Parsed_pad_1
[2] => Error configuring complex filters.
[3] => Invalid argument

I'm happy for any help.

A: If your input dimensions are larger than the pad target, then filter setup will fail. The error message should be improved.
As a workaround, use
pad=604:max(340\,ih):-1:-1

The -1 tells the filter to centre the input in the padded frame along that dimension.


text:
Q: Cannot modify header information , cannot redirect i have an error Cannot modify header information - headers already sent , i already check out the answer though ,
no space before the beginning php , and using ob_start and flush ..
its worked on my other php file (insert , edit ) , but its not working only on delete script , but actually the line i want to delete is deleted ..
this is my page to call the code

<?php
        $query = "SELECT * FROM truk";
        $sql=mysql_query($query);
    ?>

                Truk ID
                Tipe
                images
                Deskripsi
                jumlah
                 Delete/Edit

            <?php
                while($fetch=mysql_fetch_array($sql)){
            ?>

                <?php echo $fetch['trukid']; ?>
                <?php echo $fetch['tipe']; ?>
                <?php echo $fetch['images']; ?>
                <?php echo substr($fetch['deskripsi'],0,50); ?>
                <?php echo $fetch['jumlah']; ?>

                <input type="image" class="icon" src="images/asset/delete.jpg" onClick="confirmation('<?php echo $fetch['trukid']; ?>') ">
                <a href="index.php?edit_truk=<?php echo $fetch['trukid']; ?>">

            <?php } ?>

        Tambah Truk

here is the code
<?php
$id = $_GET['delete_truk'];
$sql="DELETE FROM `truk` WHERE `trukid` = '$id' ";
$query = mysql_query($sql);
header('Location:index.php?truck');
?>

and it cannot redirect instead Warning: Cannot modify header information - headers already sent by (output started
thanks for your help ,,
sorry for bad english

A: You cannot redirect if you start writing to the page
$id = $_GET['delete_truk'];
$sql="DELETE FROM `truk` WHERE `trukid` = '$id' ";
//echo $sql;  <-- don't echo
$query = mysql_query($sql);
header('Location:index.php?truck');


text:
Q: fire a popup when ApplicationBarMenuItem clicked I need to fire a popup when ApplicationBarMenuItem clicked. but nothing happen when I click MenuItem. here is my code;
<shell:ApplicationBar.MenuItems>
     <shell:ApplicationBarMenuItem Text="Go by date" Click="GoByDate_Click" />
</shell:ApplicationBar.MenuItems>

private void GoByDate_Click(object sender, EventArgs e)
{
     Popup popup = new Popup();
     popup.Height = 480;
     popup.Width = 480;
     popup.VerticalOffset = 100;
     DatePopupControl datePopup = new DatePopupControl(); // just a user control comes when add new
     popup.Child = datePopup;
     popup.IsOpen = true;
}

A: Something is wrong with your DatePopupControl, because your code worked fine for my own test control. Can you provide DatePopupControl source code?
Alright, let me try to guess. My first theory is: there is nothing to show in this popup.
For example, if you add a userControl, which has only Grid tag inside without anything, you will see in the editor in Visual Studio, but it won't be visible as a popup child. But if you add a single textblock, it will be.


text:
Q: Over releasing or not? Sorry I am a newbie.  Is this over releasing the OverlayviewController?  Since it's autorelease and release again at dealloc.  Or it doesn't matter? Thank you for helping out.
@implementation ViewController

@synthesize imageView, overlayViewController, cameraBtn;

#pragma mark -
#pragma mark View Controller

- (void)viewDidLoad

{
    [super viewDidLoad];

// Sharekit Logout button
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:SHKLocalizedString(@"Logout") style:UIBarButtonItemStyleBordered target:self action:@selector(logout)] autorelease];

    self.overlayViewController =
    [[[OverlayViewController alloc] initWithNibName:@"OverlayViewController" bundle:nil] autorelease];

// as a delegate we will be notified when pictures are taken and when to dismiss the image picker
    self.overlayViewController.delegate = self;
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        cameraBtn.hidden = YES;
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}

- (void)viewDidUnload
{
    self.imageView = nil;
    self.overlayViewController = nil;
}

- (void)dealloc
{
    [imageView release];
    [overlayViewController release];
    [super dealloc];
}

A: The one part that is missing is the definition of the property overlayViewController. If it's got the retain option then everything is fine.
In your viewDidLoad, your allocating and then autoreleasing, so this is balanced. But you also assign it to the property overlayViewController, and if it has the retain option (which it should in this case), then your call will retain the allocated OverlayViewController. That's exactly what you want.
In dealloc, you are releasing the variable that backs the property. This is OK and correct, your controller will get released correctly. However, it will get released even earlier: in viewDidUnload, you assign nil to the property. This will already release the controller. So by the time dealloc is called the overlayViewController variable will most likely be nil (but it may also still contain the controller, depending on how your object was used, that is, depending on whether viewDidUnload was called or not.
So the code as presented here is correct if the property overlayViewController has the retain option.


text:
Q: Error is java.sql.SQLSyntaxErrorException: Schema 'ROOT' does not exist i am creating desktop application which uses derby embedded database, although when i use derby as a client database then it works fine, but i want to embed this database with my desktop application then it throws error
below is the code for help, check it out
public class TaxInvoice extends javax.swing.JFrame {

 //String connectionurl = "jdbc:derby://localhost:1527/embdIDA1db";

 String connectionurl = "jdbc:derby:embdIDA1db;create=true;user=root;password=root";

 Connection conn = null;

 ResultSet rs;

 String po_no = null;

/**
 * Creates new form TaxInvoice
 */
public TaxInvoice() {
    initComponents();
    String dt = sdf.format(cal.getTime());
    cur_date.setText(dt);
    try{
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        conn = DriverManager.getConnection(connectionurl,"root","root");
        String sql="Select * from IMPORTED_CSV";
        Statement s = conn.createStatement();
        s.executeQuery(sql);
        rs = s.getResultSet();
        while(rs.next()){
            po_no = rs.getString("PO_NO");
            jTextField1.setText(po_no);
        }
        rs.close();
        s.close();
    }
    catch(Exception e){
        System.out.println("Error is"+e);
    }
}

and the error is
Error isjava.sql.SQLSyntaxErrorException: Schema 'ROOT' does not exist

A: Your connectionURl should be jdbc:derby://localhost:1527/embdIDA1db which seems to be commented out in your code.
Your are passing username and password explicitly so there is no need to include them in url.
DriverManager.getConnection(connectionurl,"root","root");

A: Can you please try this.
private static String dbURL = "jdbc:derby://localhost:1527/embdIDA1db;create=true;user=root;password=root";

A: To make this work,
use default schema for derby
i.e. user="App" password = ""
eg :
       try
        {
            // Configures and loads Database
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
            Connection conn = DriverManager.getConnection("jdbc:derby:myDB;create=true", "APP" , "");

        } catch (Exception ex)
        {
            System.out.println(ex);
        }

or you can create schema using
CREATE SCHEMA <schema name>


text:
Q: Alternative to cron jobs for browser type game I have some question concerning databases and cron jobs for repeated actions. My objective is to update some values in the database every 5 minutes. The idea is to have a classic ressource system that increases over time even when users are offline. I can't figure out the best or safest way to achieve this in terms of performance. It looks like there are 3 different ways to make this :

*

*1st/ Create a cron job to launch a script every hour. Since I can't have cron every 5 minutes with my hosting package, I figured I would have a loop inside the file that would repeat the action 12 times with in each loop a sleep(300) taking a total amount of one hour. Basically when this one finishes, the cron launches another one for another hour. This method would be quite expensive since the server would pretty much run on that file all the time. I don't even know if it would work out well with the loop inside the cron script...

*

*2nd/ Another way would be to have a routine set directly on the database, but I don't have experience with the language. I don't know if it's worth learning to do that... This way the SQL script would run every 5 minutes, no need for cron. jobs.

*

*3rd/ Last idea is I think the cheapest of the three but it's also quite risky I think. Instead of updating the databases every 5 minutes even when the user is not online, it would update it only when the user makes an action or connects. This would minimize drastically the amount of scripts running. However I found a little problem with that, if one user is to interact with another and that he disconnects the second user will not have the information since the first hasn't updated. Therefore if the second user wants the information it will have to update every user that is currently in interaction with him. I saw that topic discussed on another topic recently. I think it's the solution but it's also quite a challenge...

What are your thoughts on that?


text:
Q: GET Api response using Go Lang's GIN I'm newbie to go lang and gin framework.
I'm trying to get a response of the code below.
Can someone pls guide me what mistake I'm doing?
func main() {
router := gin.Default()
router.GET("/foo", func(c *gin.Context) {
    response, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil || response.StatusCode != http.StatusOK {
        c.Status(http.StatusServiceUnavailable)
        return
    }
    reader := response.Body
    fmt.Println("Test", reader)

    c.JSON(200, reader)
})
router.Run("")
}

Response is empty.
This is the actual response
curl -X GET "https://jsonplaceholder.typicode.com/posts/1"
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"

}

A: Depending on what you are doing, you may be better of using httputil.ReverseProxy. But that only works if you don't need to work with the upstream response or manipulate it. Otherwise, you need to read the body with something like ioutil.ReadAll or even decode it into a struct.
router.GET("/foo", func(c *gin.Context) {
    response, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil {
        c.Status(http.StatusServiceUnavailable)
        return
    }

    // if there was no error, you should close the body
    defer response.Body.Close()

    // hence this condition is moved into its own block
    if response.StatusCode != http.StatusOK {
        c.Status(http.StatusServiceUnavailable)
        return
    }

    // use a proper struct type in your real code
    // the empty interface is just for demonstration
    var v interface{}
    json.NewDecoder(response.Body).Decode(&v)
    fmt.Println("Test", v)

    c.JSON(200, v)
})


text:
Q: When bijective morphism become ismorphism? Epi and mono morphism(morphism means here the morphism in the category)is not always isomorphism.
For example, in a category of topological space, bijection continuous map is not always homeomorphism.
But like in a category of group or formal group, we can declare that bijection hom is always isomorphism.
This can be proved easily by definition.
My question is : Are there any list or characterization of such (bijective morphism is always ismorphism)category? Are there known results?
Thank you in advance.

A: Here is a result that I think is interesting.  In order to talk about some morphism $f : x \to y$ in an arbitrary category $\mathcal{C}$ as being a bijection, we need some way to interpret $f$ as a set function.  This is because the definition of "bijection" refers to how $f$ acts on elements.  One way we could interpret $f$ as a set function is if we had a functor $U : \mathcal{C} \to \mathrm{Set}$, for then any morphism $f : x \to y$ in $\mathcal{C}$ would give us a set function $Uf : Ux \to Uy$, and we could ask if $Uf$ is a bijection.  Many categories of interest "come equipped" with such an underlying set functor $U : \mathcal{C} \to \mathrm{Set}$.  Your example of topological spaces is one, posets are another, groups are another.  Algebra is full of examples.
If we have a functor $U : \mathcal{C} \to \mathrm{Set}$, then we can think of any morphism $f : x \to y$ in $\mathcal{C}$ as a set function, but it's usually only helpful to think this way if $U$ preserves and reflects things we care about.  For example, a group homomorphism $f : G \to H$ is monic/epic/iso (in $\mathrm{Grp}$) if and only if it's injective/surjective/bijective (in $\mathrm{Set}$).  So in this case we usually just think of a group homomorphism as a special kind of set function between the underlying sets of the groups.  Any functor $U : \mathcal{C} \to \mathrm{Set}$ sends isomorphisms to bijections, so there's always some connection.  But for an arbitrary functor $U : \mathcal{C} \to \mathrm{Set}$ there's no guarantee that monic/epic morphisms in $\mathcal{C}$ have anything to do with injective/surjective functions in $\mathrm{Set}$, and bijections in $\mathrm{Set}$ don't always give isos in $\mathcal{C}$.
So the natural question is: what conditions on $U$ ensure that monic/epic/iso morphisms in $\mathcal{C}$ have some relation to injective/surjective/bijective functions in $\mathrm{Set}$?  One direction of each case is often satisfied because $U$ is faithful: that is, if $f, g : x \to y$ are two morphisms such that $Uf = Ug$, then $f = g$.  This happens for topological spaces, groups, and lots of other examples.  This means, for example, that we can think of a continuous function as a set function that satisfies a certain property—in this case, continuity.  If $U$ is faithful, then we have one direction of each case: for any $f : x \to y$ in $\mathcal{C}$,

*

*If $Uf : Ux \to Uy$ is injective, then $f : x \to y$ is monic

*If $Uf : Ux \to Uy$ is surjective, then $f : x \to y$ is epic

*If $f : x \to y$ is an isomorphism, then $Uf : Ux \to Uy$ is a bijection

It is not too hard to look up examples where $U$ is faithful but the converses of the first two don't hold (the third, recall, holds for any functor $U$).  The converse holds in the third case if $\mathcal{C}$ is balanced, in the sense introduced in the comments.  For whatever reason, the converse fails for the second property much more often than for the first, in nature.
One natural question now is: what conditions can we put on a faithful functor $U : \mathcal{C} \to \mathrm{Set}$ such that $f : x \to y$ is iso when $Uf : Ux \to Uy$ is bijective?  Everything I've said so far has been pretty elementary, but for this question there's an interesting theorem.  A functor $U : \mathcal{C} \to \mathrm{Set}$ is monadic if there's an appropriate kind of "free" functor $F : \mathrm{Set} \to \mathcal{C}$.  Examples of monadic functors include the "underlying set" functor for groups, rings, modules, and the category of compact Hausdorff topological spaces.  Examples of nonmonadic functors include the "underlying set" functors for posets, fields, and the category of all topological spaces.  Monadic functors are interesting for our question because:

*

*There are lots of examples.  The category-theoretic approach to universal algebra is essentially the study of monads.

*There are various effective recognition results for monadic functors, usually called "monadicity" or "tripleability" theorems.  So it's easy to spot a monad when you meet it on the street.

*Suppose $U : \mathcal{C} \to \mathrm{Set}$ is monadic and $f : x \to y$ is a morphism in $\mathcal{C}$.  If $Uf : Ux \to Uy$ is a bijection, then $f$ is an isomorphism.  This is because any monadic functor is equivalent to the underlying set functor for the category of algebras for its monad, and this functor clearly reflects isomorphisms.

So this is one result of the kind you ask for.  If we're in a situation where we can talk about a morphism in a category $\mathcal{C}$ being bijective then we have a functor $U : \mathcal{C} \to \mathrm{Set}$, and if $U$ is monadic then any bijective morphism in $\mathcal{C}$ is iso.  Moreover, any monadic functor is faithful, so we get one nice connection between monos/epis and injections/surjections.  I think this is a nice sort of explanation for why bijections do coincide with homeomorphisms when we're talking about compact Hausdorff spaces, even though they don't coincide for general topological spaces.  That said, checking whether a functor reflects isomorphisms is usually easier than checking whether it's monadic—and indeed, it's usually part of checking that it's monadic.
This definitely isn't the only class of categories in which every bijection is an isomorphism.  In fact, let $\mathcal{C}$ be a category that is locally small—that is, such that for all objects $x$ and $y$, the class $\mathcal{C}(x, y)$ of morphisms from $x$ to $y$ is a mere set, rather than a proper class.  Then there is a functor $U : \mathcal{C} \to \mathrm{Set}$ such that if $Uf : Ux \to Uy$ is a bijection, then $f : x \to y$ is an isomorphism.  This illustrates one reason to be careful about how you're interpreting a morphism in $\mathcal{C}$ as a set function: it is very often possible to find some functor $\mathcal{C} \to \mathrm{Set}$ that makes isomorphisms the same thing as bijections.


text:
Q: There has vs. There have Which is the correct form of the sentence?

There has been many instances of outbreaks in vaccinated populations

vs.

There have been many instances of outbreaks in vaccinated populations?

The question that this is supposed to be a duplicate of does not mention there has or there have. We have many learners here who are not going to be able to deduce much of anything from it.

A: The correct one is:

There have been many instances of outbreaks in vaccinated populations.

This is because of instances/outbreaks being plural and have is the correct plural form. Has is singular.

A: The most formal version of this sentence is:

*

*There have been many instances of outbreak in vaccinated populations.

In existential constructions like this, it is common for the verb to take its agreement from the noun phrase after the verb.
However! This is not always the case. When the auxiliary is contracted with the word there, we often see no agreement between the auxiliary verb and the noun phrase after it. This happens most often in speech and semi-formal or informal writing. In this case we have the verb BE appearing in a present perfect construction with the auxiliary verb HAVE:

*

*There's been many instances of outbreaks in vaccinated populations.

In the example above we see a contraction of there and the auxiliary has. It does not matter that the following noun phrase instances of outbreaks is plural, we can still use the singular form has.
Notice, however, that is not usually considered grammatical if the words there and has are separate:

*

**There has been many instances of outbreaks in vaccinated populations. (X)

There are some very special cases, however, where we might be able to have a plural noun after the verb phrase has been:

*

*There has been one funeral, two weddings, an earthquake and a change of government since you left.

In the sentence above, we see a co-ordination of noun phrases which would normally be considered plural. However, we see a singular verb form, has in this example.
If you are doing a test at school, it is probably better to make the auxiliary verb agree with the following noun phrase. But if you want to know what native speakers actually do, and what is actually grammatical, the answer is that both there have and there's are perfectly grammatical in this sentence. We do not often find there's with a plural noun phrase in formal writing though.
Hope this is helpful!

A: The logical subject of the statement is "instances of outbreaks", which is plural. If there were only one instance of outbreaks, it would be singular.
"There" as a pronoun is a dummy subject, which takes its number from the logical subject (in this case, "instances").
Therefore, the correct form of the sentence begins with "There have been..." or "There've been".


text:
Q: Appolonius three circles problem, finding centre of tangent circle (analytic geometry) Given 3 circles:

*

*$C_1$ centered at $(0,0)$ with radius 1

*$C_2$ centered at $(a,0)$ with radius $a+1$

*$C_3$ centered at $(-a,0)$ with radius $a+1$

(so $C_1$ is internaly tangent to both $C_2$ and $C_3$ )
Question:
What are the centres of circle $C_4$ and $C_5$ that are tangent to all three circles?
I know they are on the $x=0$ axis but what is their $y$ coordinate?

A: WOLOG, we will assume $C_4$ / $C_5$ are lying in upper / lower half-plane respectively.
Let $c_i$ and $r_i$ be the center and radius for circle $C_i$ where $i = 1,\ldots,5$.
By symmetry, $r_4 = r_5$. Let us call this common value $r$. In term of $r$,
$$c_4 = (0,1+r)\quad\text{ and }\quad c_5 = (0,-1-r)$$
Since $C_4$ is inside and tangent to $C_2$, we have
$$|c_4 - c_2| = r_2 - r_4
\implies  (r+1)^2 + a^2 = (a+1-r)^2
\implies r = \frac{a}{a+2}
$$
This leads to $c_4 = -c_5 = \left( 0, 2\left(\frac{a+1}{a+2}\right)\right)$.


text:
Q: GCP: How to access VM in shared VPC by Hostname I have HostProject & Service Project
I have done network peering using shared VPC.
I'm able to access my Host Project VM from Service Project by Internal IP address.
How can I access by hostname instead of IP address.

A: There is only two type of internal DNS names Zonal DNS and Global (project wide) DNS.
I think this is what you are looking for, you can use a Private DNS zone with shared VPC, see the Google Public Documentation on how to do it.


text:
Q: Is it same number of candies for any stage of evolution while transferring pokemon to professor? I was just wondering if the number of candies we get while transferring the pokemon to professor is same for any stage of evolution ?
For example, you would get a pidgey candy for transferring a pidgey. Is it same number of candies for transferring pidgey, pidgeotto or pidgeot ?

A: YES.
The number is 1 candy per transfer to the Professor regardless of the position in the evolution chain.
Source: Personal experience. Tested it with exactly your example (pidgey, pidgeotto or pidgeot) and others. And I also tested it with high CP evolutions (e.g. Raticate for which I need 2 candies for Power-Up also gives only 1 candy at transfer.) What isn't secure: A Gyarados - to give an example - might bring more than one as it needs 400 (!) candies to evolve and seems to follow no rule in this regard.


text:
Q: When to call SSL_set_verify vs SSL_CTX_set_verify According the OpenSSL documentation, both SSL_set_verify and SSL_CTX_set_verify appear to do pretty much the same thing.
Using the Boost libraries, I can't tell whether/when I need to call ssl::stream::set_verify_callback versus ssl::context::set_verify_callback, since the stream uses the context anyways. The functions call SSL_set_verify and SSL_CTX_set_verify, respectively, under the hood.
When do I need to set the verification callback for the context instead of the SSL stream?

A: Each connection can have its own ssl object while they all get inherited from one ctx object.  You can see the difference here. One generally tends to have one ctx created and use the same for all TLS connections. In this model you can control the verification options globally or at individual connection level with the two options.
Thus the difference is that SSL_CTX_set_verify sets the verification mode for all ssl objects derived from a given ctx whereas SSL_set_verify() only affects the ssl object it is called on.

A: Usually you have a common verification function in your code and not one specific for a single SSL sessions. And often you share the same SSL context between multiple SSL sessions. Therefore in most cases it makes more sense to set the verification callback only on the context.


text:
Q: symfony2 customize form select option I'm trying to do a simple form to add an activity with a name and a color.
So I want to make a list with some an array of color, for now it is working I have the name of the color, but what I want is to make something like :
<select id="a" name="select" style="width: 10%;">
    <option style="background-color: FF0;" value="FF0"></option>
    <option style="background-color: F0F;" value="F0F"></option>
    <option style="background-color: 0FF;" value="0FF"></option>
</select>

How can I add "style="background-color:"mycolor;" to my form ?
public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('name');
    $listColor;

    for($r = 0;$r < 255; $r = $r + 120)
    {
        for($g = 0;$g < 255; $g = $g + 120)
        {
            for($b = 0;$b < 255; $b = $b + 120)
            {
                $string = dechex($r).dechex($g).dechex($b);
                $listColor[$string] = $string;
            }
        }
    }
    $builder->add('color', 'choice', array(
        'choices' => $listColor));
}

Is there a trick to had some option int the array ? to put some html ?
The closest thing I found about it was to add a class name on your form to do something in css after it...
{{ form_widget(form, { 'attr': {'class': 'myclass'}}) }}

Thanx ;)
RaFF

A: You can use jquery  to Resolve this problem, try  this example :
JSBIN "style="background-color:"mycolor;"
$(document).ready(function(){
    $("#a option").each(function(index,value){
       var option = $(this);
       var bc= 'background-color:'+option.val()+';';
       option.attr('style',bc);
    });
});


text:
Q: Save User model in UserDefaults and append stored Users to array I have a User model declared like this:
struct User: Codable {
    let nickname : String
    let fullName: String
    let profilePicUrl: URL
}

Then I save the followed user like this
let followedUser = User(nickname: username, fullName: fullName, profilePicUrl: url)
UserDefaults.standard.set(try! PropertyListEncoder().encode(followedUser), forKey: "user")

Next, in the ViewController which should display the followed users count I retrieve the UserDefaults data like this
var followedUsers = [User]()

if let storedObject: Data = UserDefaults.standard.object(forKey: "user") as? Data {
    do {
        let storedUser: User = try PropertyListDecoder().decode(User.self, from: storedObject)
        followedUsers.append(storedUser)
    } catch {
        print(error)
    }
}

Now, my followedUsers array is being updated with the last stored user each time. How can I append my followedUsers array in a proper way?

A: If you use Codable , then it make sense to use JSONEncoder & JSONDecoder and store the users as an array
do {
      // How to save multiple records
      var followers = [User]() // Your array of users
      let data =  try JSONEncoder().encode(followers) //Convert to Data
      UserDefaults.standard.set(data, forKey: "data") // Save to User Default

     // How to fetch multiple records
     // Check If data available in user default
      if let da = UserDefaults.standard.data(forKey: "data") {
        // Convert Data back to your cod-able struct
        let stored = try JSONDecoder().decode([User].self, from: da)
      }

}
catch {
    print(error)
}

struct User: Codable {
    let nickname , fullName: String
    let profilePicUrl: URL
}

Don't encourage using userDefault , you can go with CoreData / Realm

A: As @Sateesh and @Sanjukta said, storing the users in an array and saving that to UserDefaults is one solution.
The reason why your followedUsers array is updated with only one user, is that when you create a new user, you update the same key in UserDefaults each time.
It should be noted that UserDefaults is mainly used to store small amounts of data. Depending on how many User objects you plan to store, UserDefaults might not be the best solution.
The two solutions for data storage that come to mind are Core Data and Realm. Core Data is an Apple framework with which you can storage data on device. You can read more about it here: Core Data
The second option is to use Realm. Realm is is an open source database management system and can be used for on-device data storage too.
If you are interested in the differences between Realm and Core Data, for starters I can recommend this article.
Personally I use Realm in my own projects because I find it easier to implement and faster than Core Data. Please note that this is just my personal preference and others might disagree. Make sure you listen to other opinions and experiment with both before picking sides.
So let's suppose you want to store the User in Realm, you would need to do the following:

*

*Install Realm for your project.

*

*In your podfile add the following: pod 'RealmSwift'.

*Run pod install in terminal and use the newly created .xcworkspace from now on.

*In Xcode, in AppDelegate import RealmSwift and insert the following code to the didFinishLaunchingWithOptions method:
    do {
    _ = try Realm()
} catch {
    print("Error initialising new Realm \(error)")
}

This initializes a new default Realm, where your User data will be saved.

*Create a new User.swift file. In that, import RealmSwift and insert the following:
class User: Object {
    @objc dynamic var nickName: String = ""
    @objc dynamic var fullName: String = ""
    @objc dynamic var profilePicURL: URL?
}
This creates a Realm object, which will contain the data for your users.

*Save the followed user like this:

*

*In the view controller where you want to save the user data import RealmSwift, and under the class declaration create a new instance of realm by let realm = try! Realm()

*When you have the user data, save to Realm with the following code:
:
let followedUser = User()
    do{
        try realm.write {
            followedUser.nickName = username
            followedUser.fullName = fullName
            followedUser.profilePicURL = url
            realm.add(followedUser)
        }
    } catch {
        print("Error saving to persistent container! \(error)")
    }

*In the view controller where you need the user data, create an instance of Realm just like before with let realm = try! Realm()
, retrieve users from Realm with the following code: let followedUsers = realm.objects(User.self)
This retrieves all Users from the default realm.
If you need to count the followedUsers you can do so by: followedUsers.count
Hopes this approach helps you to achieve what you wanted in the first place.

A: Please make the array of object then store the array in userDefaults.
After that you can easily retrive it.
It may help you. Thank you.


text:
Q: r Create measurement model lavaan using string formula I am trying to create a function to easily run multiple lavaan mediation models with both the measurement part and the structural part, so I would only need to pass the names of the latent variables to the function call. I came across this nice solution for building the measurement part:
Is there a way to create an R function using a string formula with ', and " =~"?
In my example, this looks like this (I later need the IV, mediator, and DV in the structural part):
model_lavaan <- function(IV, mediator, DV) {{
    measurement_part <- function(...) {
      params <- list(...)
      stopifnot(length(params)%%2==0)
      lefts = params[seq(1,length(params), by=2)]
      rights = params[seq(2,length(params), by=2)]
      rights <- Map(paste, rights, collapse="+")
      paste(paste0(lefts, " =~", rights), collapse="\n", "\n")
    }

      meas <- measurement_part(paste0(IV), c(paste0(IV,"_1"), paste0(IV, "_2"), paste0(IV,"_3")),
                               paste0(mediator), c(paste0(mediator,"_1"), paste0(mediator, "_2"), paste0(mediator,"_3")),
                               paste0(DV), c(paste0(DV,"_1"), paste0(DV, "_2"), paste0(DV,"_3")))
      meas
  }
}

My dataframe:
df <- data.frame(
         row.names = c("1","2","3","4","5",
                       "6","7","8","9","10","11"),
  T1finstrain_1 = c(5, 4, 5, 2, 3, 3, 3, 4, 5, 3, 5),
  T1finstrain_2 = c(4, 3, 1, 1, 3, 2, 2, 3, 5, 2, 2),
  T1finstrain_3 = c(5, 4, 1, 2, 3, 2, 2, 4, 5, 2, 4),
     T1concom_1 = c(2, 3, 4, 1, 3, 4, 3, 4, 4, 5, 2),
     T1concom_2 = c(3, 4, 2, 5, 3, 4, 3, 4, 4, 5, 5),
     T1concom_3 = c(2, 4, 1, 2, 4, 4, 5, 4, 4, 5, 5),
    T2lifesat_1 = c(NA, 4, 5, 3, 3, NA, 5, NA, 2, NA, NA),
    T2lifesat_2 = c(NA, 3, 5, 2, 4, NA, 5, NA, 3, NA, NA),
    T2lifesat_3 = c(NA, 4, 5, 2, 5, NA, 5, NA, 3, NA, NA),
     T2jobsat_1 = c(NA, 5, 6, 6, 5, NA, 2, NA, 3, NA, NA),
     T2jobsat_2 = c(NA, 5, 6, 6, 5, NA, 5, NA, 4, NA, NA),
     T2jobsat_3 = c(NA, 5, 6, 6, 5, NA, 4, NA, 4, NA, NA),
     T2jobsat_4 = c(NA, 5, 6, 6, 5, NA, 4, NA, 3, NA, NA)
   )

So this works very well if all latent variables have three indicators:
model_lavaan(IV = "T1finstrain", mediator = "T1concom", DV = "T2lifesat")

#> [1] "T1finstrain =~T1finstrain_1+T1finstrain_2+T1finstrain_3 \n\nT1concom =~T1concom_1+T1concom_2+T1concom_3 \n\nT2lifesat =~T2lifesat_1+T2lifesat_2+T2lifesat_3 \n"

But it does not work out anymore if one variable has more indicators:
model_lavaan(IV = "T1finstrain", mediator = "T1concom", DV = "T2jobsat")

#> [1] "T1finstrain =~T1finstrain_1+T1finstrain_2+T1finstrain_3 \n\nT1concom =~T1concom_1+T1concom_2+T1concom_3 \n\nT2jobsat =~T2jobsat_1+T2jobsat_2+T2jobsat_3 \n"

I want to print the correct measurement part depending on the number of indicators in the dataframe. So if the suffixes range from 1:4, I want all four indicators in the measurement part. If they range from 1:6, I want to have all six etc.
In the case of the example dataframe df, for DV = T2jobsat, this should look like this :
model_lavaan(IV = "T1finstrain", mediator = "T1concom", DV = "T2jobsat")

#> "T1finstrain =~T1finstrain_1+T1finstrain_2+T1finstrain_3 \n\nT1concom =~T1concom_1+T1concom_2+T1concom_3 \n\nT2jobsat =~T2jobsat_1+T2jobsat_2+T2jobsat_3+T2jobsat_4 \n"

So the dataframe needs to be added as an argument to the function. But I do not really know how to accomplish what I want. I hope I explained this okay. Please ask if you need additional info! Thank you!

A: One way to do that would be to pass the data frame to the function and access the variable names.
model_lavaan <- function(dat, IV, mediator, DV) {{
  measurement_part <- function(...) {
    params <- list(...)
    stopifnot(length(params)%%2==0)
    lefts = params[seq(1,length(params), by=2)]
    rights = params[seq(2,length(params), by=2)]
    rights <- Map(paste, rights, collapse="+")
    paste(paste0(lefts, " =~", rights), collapse="\n", "\n")
  }

  meas <- measurement_part(paste0(IV), grep(IV, names(dat), value = TRUE),
                           paste0(mediator), grep(mediator, names(dat), value = TRUE),
                           paste0(DV), grep(DV, names(dat), value = TRUE))
  meas
}
}

Then
cat(model_lavaan(df, IV = "T1finstrain", mediator = "T1concom", DV = "T2jobsat"))

gives
T1finstrain =~T1finstrain_1+T1finstrain_2+T1finstrain_3

T1concom =~T1concom_1+T1concom_2+T1concom_3

T2jobsat =~T2jobsat_1+T2jobsat_2+T2jobsat_3+T2jobsat_4


text:
Q: How would I put a closing quote image in the background of my style? I figured out how to add an opening quote marks on my quote (using a background), but how would I add a closing quote marks in my style. I'd like to add a closing quote marks image after the Russell Wilson is a great quarterback.
If I'm not doing it the preferred way, can you suggest the best practices for making this happen?
Jsfiddle

    Russell Wilson is a great quarterback
    Russell Carrington Wilson is an American football quarterback for the Seattle Seahawks of the National Football League. Wilson was selected by the Seahawks with the 12th pick in the third round of the 2012 NFL Draft.

.inline-quote {
    background: url('http://www.pearl-guide.com/forum/images/Eloquent/miscblue/quote_icon.png') left top no-repeat;
    background-position: 15% 5px;
}

A: You can only have one background per element. So make a pseudo-element!
.inline-quote { position: relative }
.inline-quote::after { /* Insert it after */
    content: ''; /* Required for it to show up */
    position: absolute; /* Stretch it */
    top: 0; right: 0; bottom: 0; left: 0;
    background: url('http://www.pearl-guide.com/forum/images/Eloquent/miscblue/quote_icon.png') left top no-repeat; /* Same background */
    background-position: 15% 90%; /* Position it in the lower right */
    transform: scaleX(-1); /* Flip it */
    -webkit-transform: scaleX(-1);
}

http://jsfiddle.net/bmj942y4/5/
You should also be using the blockquote element. http://jsfiddle.net/bmj942y4/7/

A: you can use :before and :after
Demo
.inline-quote:before, .inline-quote:after{
    display:inline-block;
    width: 20px;
    height:20px;
    background: url('http://www.pearl-guide.com/forum/images/Eloquent/miscblue/quote_icon.png');
    background-repeat: no-repeat;
    content: '';
}

.inline-quote:after{
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);
}

A: You can use multiples background-image
Example
background-image: url('img1.jpg'), url(img2.jpg);
background-position: 15% 5px, 85% 5px;

Work with

*

*Firefox 3.6+

*Safari 1+

*Chrome 1.3+

*Explorer 9+

*Opera 10.5+

More informations
http://www.css3.info/preview/multiple-backgrounds/


text:
Q: Ajax call to php curl produce undefined Api: http://api.geonames.org/findNearbyPlaceNameJSON?formatted=true&lat=47.3&lng=9&username=sherazzi403&style=full
files: index.html - simple 2 input #lat for &lng= and #lng for &lng= and the button is for ajax to run the post request to the findnearbyplacename.php.
script.js: ajax post call with 2 data fields.

  $('#btnRun').click(function() {

    // alert("Hello");
     lat = $('lat').val();
      lng = $('lng').val();
    $.ajax(
      {
        method: "POST",
        url: "libs/php/findnearbyplacename.php",
        data: {
          lat: $('#lat').val(),
          lng: $('#lng').val(),
        },
        success: function(result){
          console.log(result['data']);

          $('#div1').html(result['data'][0]['distance'])
        },
         error: function(jqXHR, textStatus, errorThrown){
          // error code
          console.log("we have reached error ");
          console.log(lat, lng);

         }
      });
  });
<!DOCTYPE html>

    <meta charset="utf-8">
    <title> Find Nearby Place Names </title>
    <meta name="author" content="Hafizullah Karim" >

    <input type="number" id="lat" name="lat">
    <input type="number" id="lng" name="lng">

    <button id="btnRun">Run</button>

findnearbyplacename.php - php curl to get a json object from the api mentioned above.
full code here
https://github.com/Connector403/stage4/tree/master
   <?php
$lat = $_REQUEST['lat'];
 $lng = $_REQUEST['lng'];
 $url = 'http://api.geonames.org/findNearbyPlaceNameJSON?formatted=true&lat'.$lat.'&lng='. $lng.'&username=sherazzi403&style=full';
 // initialize the resource
 $ch = curl_init();

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_URL, $url);

 // curl_setopt($ch, CURLOPT_POSTFIELDS)
 $result = curl_exec($ch);

 curl_close($ch);
 // api returns data as json
 // decode the json as an associative array so that we can append it to the $output
 $decode = json_decode($result,true);

 // the 'geonames' properrty from the serialized JSON is store into the 'data'
 // element of $output
 $output['data'] = $decode['geonames'];
 // the correct header information for json is set and $output is converted to jsobn before send it
 header('Content-Type: application/json; charset=UTF-8');
 echo json_encode ($output);

A: Your problems stem from a missing = in your lat parameter sent to the GeoNames API.
$url = 'http://api.geonames.org/findNearbyPlaceNameJSON?formatted=true&lat'.$lat.'&lng='. $lng.'&username=sherazzi403&style=full';
                                                                                ^
                                                                           = missing here

Using the Network tab of your browser's debugging tools you'll see that the response coming back from the API contains just a simple message: Missing parameter. Add the = and proper results come back.
Since you're not getting back the response you're expecting, the key you're looking for is absent, hence the undefined message. You should add some error checking here.
Also, as noted in the comments, you're missing a leading # on a couple of the jQuery calls but this isn't affecting the result because you have it correct where it matters.
There's also a trailing comma (,) in your data object, but that's not troubling Firefox.


text:
Q: Unable to connect producer/consumer to kafka cloud broker after deploy on k8s with strimzi I am unable to start a producer to write on a kafka topic. My kafka service has been deployed on k8s with strimzi. My k8s cluster has 2 nodes on google cloud service.
As I can see from the k8s config, all the services are on:

The kafka-cluster-kafka-external-bootstrap is a service (nodeport) for the communication with the kafka broker. Basically it forwards the requests from the external node to the internal broker service. Here some details:

Following the guide (which use minikube as cluster example) I extracted the nodes' ip:
kubectl get nodes --output=jsonpath='{range .items[*]}{.status.addresses[?(@.type=="ExternalIP")].address}{"\n"}{end}'
35.xxx.xxx.xxx
34.xxx.xxx.xxx

(the main difference with the guide here is that I am using "ExternalIP" instead of "InternalIP", because I am doing everything remotely)
Then I search for the port on which is exposed the service:
kubectl get service kafka-cluster-kafka-external-bootstrap -n xxxx-kafka -o=jsonpath='{.spec.ports[0].nodePort}{"\n"}'
30680

But when I try to start my producer, using a local bin of apache-kafka, I get this:
sh kafka-console-producer.sh --broker-list 35.xxx.xxx.xxx:30680 --topic test
>[2020-02-11 16:37:18,388] WARN [Producer clientId=console-producer] Connection to node -1 (/35.xxx.xxx.xxx:30680) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)

So I tried to ping the ip, to see if it is reachable:
ping 35.xxx.xxx.xxx
PING 35.xxx.xxx.xxx (35.xxx.xxx.xxx) 56(84) bytes of data.
64 bytes from 35.xxx.xxx.xxx: icmp_seq=1 ttl=54 time=63.4 ms
64 bytes from 35.xxx.xxx.xxx: icmp_seq=2 ttl=54 time=51.4 ms

It is reachable, but the port isn't:
telnet 35.xxx.xxx.xxx 30680
Trying 35.xxx.xxx.xxx...
telnet: Unable to connect to remote host: Connection timed out

This is my yaml configuration for the kafka cluster:
apiVersion: kafka.strimzi.io/v1beta1
kind: Kafka
metadata:
  creationTimestamp: "2020-02-10T15:04:38Z"
  generation: 1
  name: kafka-cluster
  namespace: xxxx-kafka
  resourceVersion: "5868409"
  selfLink: /apis/kafka.strimzi.io/v1beta1/namespaces/xxxx-kafka/kafkas/kafka-cluster
  uid: 93d0d9b6-7c88-4e01-af9c-49f9fcaac1d1
spec:
  entityOperator:
    topicOperator: {}
    userOperator: {}
  kafka:
    config:
      offsets.topic.replication.factor: 1
      transaction.state.log.min.isr: 1
      transaction.state.log.replication.factor: 1
    listeners:
      external:
        tls: false
        type: nodeport
      plain: {}
      tls: {}
    replicas: 1
    storage:
      type: jbod
      volumes:
      - deleteClaim: false
        id: 0
        size: 100Gi
        type: persistent-claim
  zookeeper:
    replicas: 1
    storage:
      deleteClaim: false
      size: 100Gi
      type: persistent-claim
status:
  conditions:
  - lastTransitionTime: 2020-02-11T15:33:50+0000
    status: "True"
    type: Ready
  listeners:
  - addresses:
    - host: kafka-cluster-kafka-bootstrap.xxxx-kafka.svc
      port: 9092
    type: plain
  - addresses:
    - host: kafka-cluster-kafka-bootstrap.xxxx-kafka.svc
      port: 9093
    type: tls
  - addresses:
    - host: <AnyNodeAddress>
      port: 30680
    type: external
  observedGeneration: 1

Does anyone know why this problem occurs and how to run the producer properly?
EDIT:
this is the yaml of the kafka-cluster-kafka-bootstrap
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2020-02-11T15:31:57Z"
  labels:
    app.kubernetes.io/instance: kafka-cluster
    app.kubernetes.io/managed-by: strimzi-cluster-operator
    app.kubernetes.io/name: strimzi
    strimzi.io/cluster: kafka-cluster
    strimzi.io/kind: Kafka
    strimzi.io/name: kafka-cluster-kafka-bootstrap
  name: kafka-cluster-kafka-bootstrap
  namespace: xxxx-kafka
  ownerReferences:
  - apiVersion: kafka.strimzi.io/v1beta1
    blockOwnerDeletion: false
    controller: false
    kind: Kafka
    name: kafka-cluster
    uid: 93d0d9b6-7c88-4e01-af9c-49f9fcaac1d1
  resourceVersion: "5867902"
  selfLink: /api/v1/namespaces/xxxx-kafka/services/kafka-cluster-kafka-bootstrap
  uid: 3dfdbd89-fc97-43d3-8e10-4f6a23eae20e
spec:
  clusterIP: 10.0.2.111
  ports:
  - name: replication
    port: 9091
    protocol: TCP
    targetPort: 9091
  - name: clients
    port: 9092
    protocol: TCP
    targetPort: 9092
  - name: clientstls
    port: 9093
    protocol: TCP
    targetPort: 9093
  selector:
    strimzi.io/cluster: kafka-cluster
    strimzi.io/kind: Kafka
    strimzi.io/name: kafka-cluster-kafka
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}

I also tried to connect internally from the GCP node, but I get the same problem. I extracted the internal Ips:
kubectl get nodes --output=jsonpath='{range .items[*]}{.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}'
10.132.0.4
10.132.0.5

Then I tried to connect the producer from the GCP node and this is what I got:
sh kafka-console-producer.sh --broker-list 10.132.0.4:30680 --topic test_topic
>hello
[2020-02-12 15:31:15,033] ERROR Error when sending message to topic test_topic with key: null, value: 4 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Topic test_topic not present in metadata after 60000 ms.
>[2020-02-12 15:32:24,629] WARN [Producer clientId=console-producer] Connection to node 0 (/34.xxx.xxx.xxx:30350) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)

Now, before getting the connection error I got also this one:
[2020-02-12 15:31:15,033] ERROR Error when sending message to topic test_topic with key: null, value: 4 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
    org.apache.kafka.common.errors.TimeoutException: Topic test_topic not present in metadata after 60000 ms.

This is the kafka-cluster-kafka-brokers yaml:
apiVersion: v1
kind: Service
metadata:
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
  creationTimestamp: "2020-02-11T15:31:57Z"
  labels:
    app.kubernetes.io/instance: kafka-cluster
    app.kubernetes.io/managed-by: strimzi-cluster-operator
    app.kubernetes.io/name: strimzi
    strimzi.io/cluster: kafka-cluster
    strimzi.io/kind: Kafka
    strimzi.io/name: kafka-cluster-kafka-brokers
  name: kafka-cluster-kafka-brokers
  namespace: xxxx-kafka
  ownerReferences:
  - apiVersion: kafka.strimzi.io/v1beta1
    blockOwnerDeletion: false
    controller: false
    kind: Kafka
    name: kafka-cluster
    uid: 93d0d9b6-7c88-4e01-af9c-49f9fcaac1d1
  resourceVersion: "5867905"
  selfLink: /api/v1/namespaces/xxxx-kafka/services/kafka-cluster-kafka-brokers
  uid: 42d7fa08-cf52-47e1-9746-89a45d65351b
spec:
  clusterIP: None
  ports:
  - name: replication
    port: 9091
    protocol: TCP
    targetPort: 9091
  - name: clients
    port: 9092
    protocol: TCP
    targetPort: 9092
  - name: clientstls
    port: 9093
    protocol: TCP
    targetPort: 9093
  publishNotReadyAddresses: true
  selector:
    strimzi.io/cluster: kafka-cluster
    strimzi.io/kind: Kafka
    strimzi.io/name: kafka-cluster-kafka
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}


text:
Q: CORS - HARN transformations - what is the most accurate method This may not be an issue for many GIS-ers but has anyone else had experiences transforming from modern NAD83 (CORS) to HARN coordinates and vice versa? I realize the discrepancy might be something like 10 cm but for sources like low-level aerial, mobile lidar or ground surveys, this is still a big deal. What is the best practice? Most states still require HARNs as a deliverable coordinate system, and many companies survey tied to the latest realization of the CORS network.
An ArcGIS implementation would be appreciated.
Also this might lead to an interesting discussion for those who think the NAD83 -> HARN transformation in ArcGIS is the right thing to do with modern GPS-derived survey data (it's not!).

A: From the NGS which established the HARN's, the CORS and the NSRS2007 (which is the current nationwide re-adjustment of the coordinates of traditional geodetic monumentation using the CORS as control):

ANNOUNCEMENT
The Products and Services Committee of NGS voted to rescind the 1998 NGS policy which stated that a transformation would be provided between older versions of NAD 83 and NAD 83(NSRS2007). Initial tests indicated that the shifts were too small, the accuracy of the shifts too large, and sparseness of the data too great to produce a useful transformation.
Users who wish to transform existing surveys from an older version of NAD 83 into NAD 83(NSRS2007) are urged to recompute coordinates using original observations and newly published NAD 83(NSRS2007) coordinates.

Retrieved from: http://www.ngs.noaa.gov/NationalReadjustment/PSCannounce.html

A: I don't think you'll get an authoritative answer here, this requires someone with a deep knowledge of geodesy to answer precisely. From what I've read, CORS to HARN can be done down to about a 6cm accuracy, beyond which I'm guessing you'll need a professional surveyor to get an authoritative response. I would NOT use ArcGIS for such a transformation, if you're talking about accuracy to this level, but instead try the NGS tools directly.


text:
Q: How to assign values to the variables in MATLAB? I have created a variable vector of 2*2 size and i am trying to assign some values to them and use them further in my programme, but i am not sure how to do it
Rho= sym('Rh0',[2,2]);
abc= [1 2; 5 6];

what i expect in the out put is
Rho1_1=1
Rho1_2=2
Rho2_1=5
Rho2_2=6

can some one help me to solve this ?

A: The following works; using num2cell to convert the array to a cell array, and then use multiple indexing to 'deal' the variables with the content of the cell array:
clear
clc

abc= [1 2; 5 6];

abcCell = num2cell(abc'); %// Note the transpose; needed to get correct order.

[Rho1_1, Rho1_2,Rho2_1,Rho2_2] = abcCell{:}

Giving this:
Rho1_1 =

     1

Rho1_2 =

     2

Rho2_1 =

     5

Rho2_2 =

     6

A: rho = sym('r',[2,2]);
r1_1 = 1;
r1_2 = 2;
r2_1 = 5;
r2_2 = 6;
subs(rho)

spits out
ans =

     1     2
     5     6


text:
Q: ASP.Net: 301 Redirects I have the bellow code to redirect but it does not seem to work well
<configuration>
    <location path="article.aspx">
        <system.webServer>
            <httpRedirect enabled="true" destination="http://www.newsite.co.uk/new-page-a/" httpResponseStatus="Permanent" />
        </system.webServer>
    </location>

    <location path="old-page-2.html">
        <system.webServer>
            <httpRedirect enabled="true" destination="http://www.newsite.co.uk/new-page-b/" httpResponseStatus="Permanent" />
        </system.webServer>
    </location>

    <system.webServer>
        <httpRedirect enabled="true" exactDestination="true" destination="http://www.newsite.co.uk/" httpResponseStatus="Permanent" />
    </system.webServer>
</configuration>

I am not sure what is wrong here. Any help


text:
Q: SQL - max 255 length unique index - Hash Solution We have table where we store tokens for users (i.e. accessTokens).
The problem is, sometimes tokens can have more than 255 length and MySQL/MariaDB is unable to store it into table that have unique index on this column.
We need unique indexes, therefore one solution is to add additional column with hash of token which has max 255 length and put unique index to it. Any search/save will go through this hash, after match, we select the whole token and send it back. After a lot of thinking and googling this is probably the only viable solution for this use-case (but you can try to give us another one).
Every single token we generate right now is at least partially random, therefore slightly chance of hash collision is "ok", the user is not stucked forever in next request, it should pass.
Do you know any good modern method in 2017? Having some statistical data about hash collision for this method would be appreciated.
The hash is only for internal use - we dont need it to be secure (fast insecure hash is best for us), it should be long enough to have low chance of collision but must never ever pass the 255 length limit.
PS: Setting up special version of database/table that allows more length is not viable, we need it also in some older system without migration.

A: Are these access tokens representable with 8-bit characters? That is, are all the characters in them taken from the ASCII or iso-8859-1 character sets?
If so, you can get a longer unique index than 255 by declaring the access-token column with COLLATE latin1_bin. The limit of an index prefix is 767 bytes, but utf8 characters in VARCHAR columns take 3 bytes per character.
So a column with 767 unique latin1 characters should be uniquely indexable. That may solve your problem if your unique hashes all fit in about 750 bytes.
If not ...
You've asked for a hash function for your long tokens with a "low" risk of collision. SHA1 is pretty good, and is available as a function in MySQL. SHA512 is even better, but doesn't work in all MySQL servers.  But the question is this: What is the collision risk of taking the first, or last, 250 characters of your long tokens and using them as a hash?
Why do I ask? Because your spec calls for a unique index on a column that's too long for a MySQL unique index. You're proposing to solve that problem by using a hash function that is also not guaranteed to be unique. That gives you two choices, both of which require you to live with a small collision probability.

*

*Add a hash column that's computed by SHA2('token', 512) and live with the tiny probablility of collision.

*Add a hash column that's computed by LEFT('token', 255) and live with the tiny probability of collision.

You can implement the second choice simply by removing the unique constraint on your index on the token column. (In other words, by doing very little.)
The SHA has family has well-known collision characteristics. To evaluate some other hash function would require knowing the collision characteristics of your long tokens, and you haven't told us those.

A: Comments on HASHing
UNHEX(MD5(token)) fits in 16 bytes - BINARY(16).
As for collisions:  Theoretically, there is only one chance in 9 trillion that you will get a collision in a table of 9 trillion rows.
For SHA() in BINARY(20) the odds are even less.  Bigger shas are, in my opinion, overkill.
Going beyond the 767 limit to 3072
⚈  Upgrade to 5.7.7 (MariaDB 10.2.2?) for 3072 byte limit -- but your cloud may not provide this;
   ⚈  Reconfigure (if staying with 5.6.3 - 5.7.6 (MariaDB 10.1?)) -- 4 things to change: Barracuda + innodb_file_per_table + innodb_large_prefix + dynamic or compressed.
Later versions of 5.5 can probably perform the 'reconfigure'.
Similar Question: Does MariaDB allow 255 character unique indexes?