text:
Q: Mojolicious app using google authentication, plugin OAuth2 I am using Mojolicious::Plugin::OAuth2 to build a simple app where you can log in using your google+ credentials, and I am having trouble with the syntax.
My code is very close to the example they give:
use Mojolicious::Lite;
use Mojolicious::Plugin::OAuth2;

plugin 'OAuth2' => {
  google => {
    key => 'xxxxxx.apps.googleusercontent.com',
    secret => 'xxxxxxxx',
  },
};

get "/auth" => sub {
  my $self = shift;
  $self->delay(
    sub {
      my $delay = shift;
      $self->get_token(google => $delay->begin, scope->profile)
    },
    sub {
      my($delay, $token, $tx) = @_;
      return $self->render(text => $tx->res->error) unless $token;
      $self->session(token => $token);
      $self->render(text => $token);
    },
  );
};

 app->start;

The problem area being the scope->profile. Without specifying the scope, I get an error from google saying "400: Error: invalid_request Missing required parameter: scope" but I can't quite get it right and now receive syntax errors.
The documentation says to do it like this $token = $c->get_token($provider_name => \%args); So how do I write that args hash so that it makes sense?

A: This syntax is what worked for me
  $self->get_token('google', scope => 'profile', $delay->begin);

I had to put $delay->begin at the end and google in quotes.


text:
Q: login with google plus using javascript I want to login with google plus using javascript,below is my code
index.html
Here i placed all scripts,html code

      <title>Login With google plus</title>
      <meta name="google-signin-client_id"
      content="aaaaaaaaaaa.apps.googleusercontent.com ">

but when i want to login this error will show.

*That's an error.

Error: invalid_client
The OAuth client was not found.

I can't get this error, please help me to solve this error.

A: You have to register your application with google console to be able to use the OAuth, You will have to specify the return url after OAuth is granted by the client

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ubuntu 12.10 and Lenovo X1 HDMI output I'm trying desperately to output HDMI from my laptop to my Samsung 40EH6030 LED TV.
I connected the HDMI1 on the TV to the computer, it shows that it detects the TV (40" Samsung Electric..) in the "Displays" section, on the TV I select that HDMI1 and I get "No signal".
It worked on the same computer while running Windows 7.
Any idea???

A: Bring up the unity Dash and type Displays. Click on the icon for Displays and you should be able to choose your display from there.


text:
Q: how to skip unzipping a file that already exists in google colab I have a very large 7z file in google drive.
When I use Google Colab to unzip it, It took me too much time and sometimes runtime is out
so I can not unzip the whole file successfully.
How can I skip unzip a file that already exists in google colab?

A: I have used this code:
main_path = "path_to_your_dir" # Specify the path

# Check whether the specified path exists or not
if os.path.exists(main_path)== False :
  !unzip your_zip_file.zip


text:
Q: SSH connection with Java How can I connect to an SSH server in Java? I don't need/want a shell. I just want to connect to the SSH server and get the content of, say, file.txt. How can I do that?

A: Use JSch
import com.jcraft.jsch.*;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * @author World
 */
public class SSHReadFile {

    public static void main(String args[]) {
        String user = "john";
        String password = "mypassword";
        String host = "192.168.100.23";
        int port = 22;
        String remoteFile = "/home/john/test.txt";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            System.out.println("Establishing Connection...");
            session.connect();
            System.out.println("Connection established.");
            System.out.println("Crating SFTP Channel.");
            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();
            System.out.println("SFTP Channel created.");

            InputStream inputStream = sftpChannel.get(remoteFile);

            try (Scanner scanner = new Scanner(new InputStreamReader(inputStream))) {
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    System.out.println(line);
                }
            }
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }
}

output:
Establishing Connection...
Connection established.
Crating SFTP Channel.
SFTP Channel created.
This is content from file /home/john/test.txt

A: Java doesn't support that natively, but you can use a library like JSch to do it

A: You must use a third-party library - JSch is one of them. Google with "Java ssh" and you will get plenty of other options.

A: You could check JSSH, which is a Java SSH library.

A: http://www.ganymed.ethz.ch/ssh2/ implements a ssh2 client in Java.  I use it for port forwarding.

A: Take a look at Jaramiko.

A: Not 100% sure but I believe that the sockets have a great deal to do with ssh connections unless you are attempting to do a pre-installed command manipulation application. There are numerous outside packages that you can use to achieve this goal, but if you want to do your own socket creation, it's going to take a large amount of reading and deciphering/encrypting to get this done.
Also creating your own socket is dangerous if not done correctly with the right protocols and security specifications, so be wary about doing so until you are 100% sure you're capable of committing to learning enough.

A: I used this and worked for me
Channel channel=session.openChannel("exec");
String command = "Your Command here";
((ChannelExec)channel).setCommand(command);

InputStream in=channel.getInputStream();
((ChannelExec)channel).setErrStream(System.err);
channel.connect();


text:
Q: DDD: Can application services throw domain errors? I'm new to DDD and I trying to create an API using DDD concepts for study purposes. Today, I faced a scenario where I've to create an Application Service to expose a functionality to be cosumed from the external world. The scenario that I came across is to consult in the repository some Domain Entity informations by its id and if the Entity does not exists it should throw a Domain Error to the client, informing that the Entity does not exists. Therefore, my questions are:

*

*Should I throw Domain Errors in Application Services?

*Should this scenario be converted to a Domain Service that is called by the Application service, where the Domain Service treats the repository's response and throws the Error? If yes, how can I nominate this service?

My code looks like this:
import { CostumerRepository } from '@/main/com/acme/sales/domain/repositories';
import { CostumerNotFound } from '@/main/com/acme/sales/domain/errors';
import { GetCostumerHistoryInputDTO } from './dtos/inputs';
import { CostumerHistoryOutputDTO } from './dtos/output';

export class GetCostumerHistory {
  constructor(private readonly costumerRepository: CostumerRepository) {}

  execute(input: GetCostumerHistoryInputDTO): CostumerHistoryOutputDTO {
    const costumer = this.costumerRepository.getById(input.costumerId);

    if (costumer == null) throw new CostumerNotFound();

    return new CostumerHistoryOutputDTO({ costumer });
  }
}

A:
Should this scenario be converted to a Domain Service that is called by the Application service, where the Domain Service treats the repository's response and throws the Error?

Yes, this is probably the better path to take.
In Domain-Driven Design, the responsibility of throwing Domain Errors should be delegated to the Domain layer; This knowledge comes from the Domain after all. So it would be better to implement the logic of checking if the Entity exists in a Domain Service and throw the Domain Error from there.

If yes, how can I nominate this service?

Here's an example of how you could refactor your code to delegate the error handling to a Domain Service:
import { CustomerRepository } from '@/main/com/acme/sales/domain/repositories';
import { CustomerNotFound } from '@/main/com/acme/sales/domain/errors';
import { GetCustomerService } from '@/main/com/acme/sales/domain/services';
import { GetCustomerHistoryInputDTO } from './dtos/inputs';
import { CustomerHistoryOutputDTO } from './dtos/output';

export class GetCustomerHistory {
  constructor(
    private readonly customerRepository: CustomerRepository,
    private readonly getCustomerService: GetCustomerService,
  ) {}

  execute(input: GetCustomerHistoryInputDTO): CustomerHistoryOutputDTO {
    const customer = this.getCustomerService.getById(input.customerId);
    return new CustomerHistoryOutputDTO({ customer });
  }
}

import { CustomerRepository } from '@/main/com/acme/sales/domain/repositories';
import { CustomerNotFound } from '@/main/com/acme/sales/domain/errors';

export class GetCustomerService {
  constructor(private readonly customerRepository: CustomerRepository) {}

  getById(id: string): Customer {
    const customer = this.customerRepository.getById(id);
    if (customer == null) throw new CustomerNotFound();
    return customer;
  }
}

The GetCustomerHistory class is an Application Service that provides the external API for retrieving a customer's history. It relies on the GetCustomerService class, which is a Domain Service responsible for retrieving a customer by their id and throwing the CustomerNotFound error if the customer does not exist.
Hope this helps!


text:
Q: Connecting to uefi PXE server with virtualbox, using a VPN connection I am on a Windows PC running VirtualBox with nothing installed in.
My PXE server is in UEFI mode. I changed the option in VirtualBox to UEFI boot and the only supported card type is the "paravirtualized network".
Now I need to connect my HOST computer to a VPN server (that is in another subnet where the PXE server is - but has access to it), bridge the connection to my guest PC and somewhat make the PXE client reach the PXE server.
I tried using NAT and Bridged connection for this, but without success.
I think the problem is in the DHCP server that serves the VPN subnet. Is there any way to solve this ? (eg. some modified PXE client that supports direct input of PXE IP address)
I cannot change settings in PXE server nor the VPN server.


text:
Q: Mas de un LineRenderer en un bucle for Estoy desarrollando un videojuego en donde el player, tiene un selector de tiro, uno de sus selectores es una Escopeta, yo lo que quiero es que cuando disparo, me renderize un Linerenderer por cada proyectil que suelta. Me explico:
Se que suelta los 6 proyectiles que he puesto, ya que el daño por disparo que he puesto es 30, y los enemigos tienen una vida de 90 y cuando disparo con el selector de escopeta, los enemigos mueren al instante, pero sin embargo solo se ve 1 Line renderer que entiendo será el ultimo proyectil del que sale.
Y yo lo que quiero es que haga un Line Renderer por cada proyectil que dispara
public void Escopeta() {
        if (balasActuales <= 0) return;
        for (int i = 0; i < 6; i++) {
            dispersor.transform.rotation = gunBarrelEnd.transform.rotation;
            dispersor.transform.Rotate(Random.Range(-factorDispersion, factorDispersion), Random.Range(-factorDispersion, factorDispersion), 0);

            balasActuales--;
            ammoSlider.value = balasActuales;

            timer = 0f;

            armaAudio.Play();
            armaLuz.enabled = true;
            puntoLuz.enabled = true;

            armaParticulas.Stop();
            armaParticulas.Play();

            armaLinea.enabled = true;
            armaLinea.SetPosition(0, transform.position);

            tiroRayo.origin = transform.position;
            tiroRayo.direction = transform.forward;

            if (Physics.Raycast(tiroRayo, out hitDisparo, rango, mascaraDisparable)) {
                vidaEnemigo enemyHealth = hitDisparo.collider.GetComponent<vidaEnemigo>();
                if (enemyHealth != null) {
                    enemyHealth.TenerDamage(damagePorTiro, hitDisparo.point);
                    imagenEnemigo.enabled = true;
                    imagenEnemigo.sprite = enemyHealth.icon;
                    vidaEnemigoSlider.gameObject.SetActive(true);
                    vidaEnemigoSlider.value = enemyHealth.consigueLaVidaDelBicho();
                    StopCoroutine("OcultarVidaEnemigo");
                    StartCoroutine("OcultarVidaEnemigo");
                }
                else {
                    OcultaEnemigoUI();
                }
                armaLinea.SetPosition(1, hitDisparo.point);
            }
            else {
                armaLinea.SetPosition(1, tiroRayo.origin + tiroRayo.direction * rango);
            }
        }
    }

Alguien con un poco de caridad y conocimientos podría echarme una mano?
Sea como sea, muchísimas gracias

A: Problema arreglado, despues de darle muchas vueltas,lo que habia que hacer era, crear un array de line renderes , otro array de Ray's y un ultimo de Raycast's, hice publica el array del LIne renderers, previamente cree, 5 gameobjects vacios , y le añadi un line renderer a cada uno en el inspector, paso el codigo correcto
un saludo, espero que le sirva algun dia a alguien
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class DisparoJugador : MonoBehaviour
{
    public int damagePorTiro = 30;
    public float tiempoEntreBalas = 0.15f;
    public float rango = 100f;
    public Slider ammoSlider;
    public int municionMax = 100;
    public Image imagenEnemigo;
    public Slider vidaEnemigoSlider;
    public Light puntoLuz;

    public GameObject gunBarrelEnd;
    public GameObject dispersor;

    public float factorDispersion = 0.10f;

    float timer;
    Ray tiroRayo;
    RaycastHit hitDisparo;
    int mascaraDisparable;

    Ray[] tiroRayoEscopeta = new Ray[7];
    RaycastHit[] hitDisparoEscopeta = new RaycastHit[7];
    public LineRenderer[] linerenderArray = new LineRenderer[7];

    ParticleSystem armaParticulas;
    LineRenderer armaLinea;

    AudioSource armaAudio;
    Light armaLuz;
    float efectoDisplayTiempo = 0.2f;
    int balasActuales;
    bool escopeta = false;

    private void Awake()
    {
        mascaraDisparable = LayerMask.GetMask("Shootable");
        armaParticulas = GetComponent<ParticleSystem>();
        armaLinea = GetComponent<LineRenderer>();
        linerenderArray[6] = GetComponent<LineRenderer>();
        armaAudio = GetComponent<AudioSource>();
        armaLuz = GetComponent<Light>();
        balasActuales = municionMax;
        StartCoroutine(CargarAmmo());
        imagenEnemigo.enabled = false;
        vidaEnemigoSlider.gameObject.SetActive(false);
    }

    IEnumerator CargarAmmo()
    {
        float recargarTiempo = tiempoEntreBalas * 2;
        while (true)
        {
            yield return new WaitForSeconds(recargarTiempo);
            if (balasActuales<municionMax)
            {
                balasActuales++;
                ammoSlider.value = balasActuales;

            }
        }

    }

    IEnumerator OcultarVidaEnemigo()
    {
        yield return new WaitForSeconds(2);
        OcultaEnemigoUI();
    }

    void OcultaEnemigoUI()
    {
        imagenEnemigo.enabled = false;
        vidaEnemigoSlider.gameObject.SetActive(false);
    }

    private void Update()
    {
        timer += Time.deltaTime;
        SwitchWeapon();

        if (Input.GetButton ("Fire1")  && timer >= tiempoEntreBalas && Time.timeScale !=0 && !EventSystem.current.IsPointerOverGameObject(-1) && escopeta == false)
        {
            Dispara();
        }
        else if (Input.GetButton("Fire1") && timer >= tiempoEntreBalas && Time.timeScale != 0 && !EventSystem.current.IsPointerOverGameObject(-1) && escopeta == true)
        {
            Escopeta();
        }
        if (timer>= tiempoEntreBalas * efectoDisplayTiempo)
        {
            ApagarEfectos();
        }
    }

    void Dispara()
    {

        if (balasActuales <= 0) return;

        balasActuales--;
        ammoSlider.value = balasActuales;

        timer = 0f;

        armaAudio.Play();
        armaLuz.enabled = true;
        puntoLuz.enabled = true;

        armaParticulas.Stop();
        armaParticulas.Play();

        armaLinea.enabled = true;
        armaLinea.SetPosition(0, transform.position);

        tiroRayo.origin = transform.position;
        tiroRayo.direction = transform.forward;

        dispersor.transform.rotation = gunBarrelEnd.transform.rotation;
        dispersor.transform.Rotate(Random.Range(-factorDispersion, factorDispersion), Random.Range(-factorDispersion, factorDispersion), 0);

        if (Physics.Raycast(tiroRayo,out hitDisparo,rango,mascaraDisparable))
        {
            vidaEnemigo enemyHealth = hitDisparo.collider.GetComponent<vidaEnemigo>();
            if (enemyHealth!=null)
            {
                enemyHealth.TenerDamage(damagePorTiro, hitDisparo.point);
                imagenEnemigo.enabled = true;
                imagenEnemigo.sprite = enemyHealth.icon;
                vidaEnemigoSlider.gameObject.SetActive(true);
                vidaEnemigoSlider.value = enemyHealth.consigueLaVidaDelBicho();
                StopCoroutine("OcultarVidaEnemigo");
                StartCoroutine("OcultarVidaEnemigo");
            }
            else
            {
                OcultaEnemigoUI();
            }
            armaLinea.SetPosition(1, hitDisparo.point);
        }
        else
        {
            armaLinea.SetPosition(1, tiroRayo.origin + tiroRayo.direction * rango);
        }
    }

    void SwitchWeapon()
    {
        if (Input.GetKeyDown("1"))
        {
            //fusil
            escopeta = false;
            damagePorTiro = 30;
            tiempoEntreBalas = 0.15f;
            rango = 50;
            factorDispersion = 1f;
            efectoDisplayTiempo = 0.2f;
            efectoDisplayTiempo = efectoDisplayTiempo * 2;
        }
        else if (Input.GetKeyDown("2"))
        {
            //Escopeta
            escopeta = true;
            damagePorTiro = 30;
            tiempoEntreBalas = 0.8f;
            rango = 8;
            factorDispersion = 7f;
            efectoDisplayTiempo = 0.2f;
            efectoDisplayTiempo = efectoDisplayTiempo / 2 ;
        }
        else if (Input.GetKeyDown("3"))
        {
            //Sniper
            escopeta = false;
            damagePorTiro = 210;
            tiempoEntreBalas = 1.5f;
            rango = 100;
            factorDispersion = 0f;
            efectoDisplayTiempo = 0.2f;
            efectoDisplayTiempo = efectoDisplayTiempo / 4;
        }
    }

    public void Escopeta()
    {
        for (int i = 0; i < 6; i++)
        {
            dispersor.transform.rotation = gunBarrelEnd.transform.rotation;
            dispersor.transform.Rotate(Random.Range(-factorDispersion, factorDispersion), Random.Range(-factorDispersion, factorDispersion), 0);

            linerenderArray[i] = linerenderArray[i];

            if (balasActuales <= 0) return;

            balasActuales--;
            ammoSlider.value = balasActuales;

            timer = 0f;

            armaAudio.Play();
            armaLuz.enabled = true;
            puntoLuz.enabled = true;

            armaParticulas.Stop();
            armaParticulas.Play();

            //armaLinea.enabled = true;
            //armaLinea.SetPosition(0, transform.position);

            linerenderArray[i].enabled = true;
            linerenderArray[i].SetPosition(0, transform.position);

            tiroRayoEscopeta[i].origin = transform.position;
            tiroRayoEscopeta[i].direction = transform.forward;

            if (Physics.Raycast(tiroRayoEscopeta[i], out hitDisparoEscopeta[i], rango, mascaraDisparable))
            {
                vidaEnemigo enemyHealth = hitDisparoEscopeta[i].collider.GetComponent<vidaEnemigo>();
                if (enemyHealth != null)
                {
                    enemyHealth.TenerDamage(damagePorTiro, hitDisparoEscopeta[6].point);
                    imagenEnemigo.enabled = true;
                    imagenEnemigo.sprite = enemyHealth.icon;
                    vidaEnemigoSlider.gameObject.SetActive(true);
                    vidaEnemigoSlider.value = enemyHealth.consigueLaVidaDelBicho();
                    StopCoroutine("OcultarVidaEnemigo");
                    StartCoroutine("OcultarVidaEnemigo");
                }
                else
                {
                    OcultaEnemigoUI();
                }
                //armaLinea.SetPosition(1, hitDisparo.point);
                linerenderArray[i].SetPosition(1, hitDisparoEscopeta[i].point);
            }
            else
            {
                linerenderArray[i].SetPosition(1, tiroRayoEscopeta[i].origin + tiroRayoEscopeta[i].direction * rango);

            }
        }

    }

   public void ApagarEfectos()
    {

        linerenderArray[0].enabled = false;
        linerenderArray[1].enabled = false;
        linerenderArray[2].enabled = false;
        linerenderArray[3].enabled = false;
        linerenderArray[4].enabled = false;
        linerenderArray[5].enabled = false;

        armaLinea.enabled = false;
        armaLuz.enabled = false;
        puntoLuz.enabled = false;
    }

}


text:
Q: Ruby Chapter 8 tutorial partial file not found I am using Ruby on Rails Tutorial by Michael Hartl - Chapter 8 - Rails 3
In the file new.html.erb I have:

Sign up

<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>

I created the file app/views/shared/_error_messages.html.erb
When I run the test: bundle exec rspec spec/requests/users_spec.rb I get the following error messages:
Failures:

*

*Users signup failure should not make a new user
Failure/Error: visit signup_path
ActionView::Template::Error:
  Missing partial shared/error_messages with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths "/Users/username/rails_projects/my_sample_app/app/views"

*Users signup success should make a new user
Failure/Error: visit signup_path
ActionView::Template::Error:
  Missing partial shared/error_messages with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths "/Users/username/rails_projects/my_sample_app/app/views"

A: Thanks apneadiving. When I went to the folder app/views/shared and did an ls command it showed the file there. However, when I tried to cat the file it returned file not found. Doing an ls -al showed the file had a @ for extra attributes. I loaded the file in my editor and saved it under another name. Then recreated the original file and removed the old file. Everything worked then.


text:
Q: Cannot search regex in Tkinter Text Widget I'm trying to develop Find and Replace for my text editor. Unfortunately regex doesn't seem to work. This is very strange because I am searching the Text widget with the regex search in Python. I am suspecting the problem lies in incorrect lengths for the regex trem.
I get the following error:
_tkinter.TclError: bad text index ""

Below is my Python code:
import tkinter as tk
import tkinter.filedialog
import traceback
import tkinter.ttk as ttk

from pygments import lex
from pygments.lexers import PythonLexer

import sys
import os

import re

import time

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

        self.comment = False

    def highlight_pattern(self, pattern, tag, regex, start="1.0", end="end"):
        '''Apply the given tag to all text that matches the given pattern

        If 'regexp' is set to True, pattern will be treated as a regular
        expression.
        '''
        print(regex)
        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart", start)
        self.mark_set("matchEnd", start)
        self.mark_set("searchLimit", end)

        count = tk.IntVar()
        while True:
            index = self.search(pattern, "matchEnd","searchLimit",
                                count=count, regexp=regex)
            if index == "": break
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.tag_add(tag, "matchStart", "matchEnd")

class Tab:
    def __init__(self, parent, filename, parentwindow):
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.parentwindow = parentwindow
        self.language = "Python"

        self.row = "0"
        self.column = "0"
        self.startCol = 0

        self.parent = parent
        self.filename = filename
        self.tab1 = ttk.Frame(parent)
        self.text = CustomText(self.tab1, bd=0, font=("Tahoma", 9))

        self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.configure(command=self.text.yview)

        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.pack(side="right", fill="both", expand=True)

        parent.add(self.tab1, text=filename)

        self.text.bind("<KeyRelease>", self.keypress)
        self.text.bind("<Button-1>", self.keypress)

        self.parent = parent

        self.configureTags()

    def configureTags(self):
        self.text.tag_configure("Token.Keyword", foreground="#CC7A00")
        self.text.tag_configure("Token.Keyword.Constant", foreground="#CC7A00")
        self.text.tag_configure("Token.Keyword.Declaration", foreground="#CC7A00")
        self.text.tag_configure("Token.Keyword.Namespace", foreground="#CC7A00")
        self.text.tag_configure("Token.Keyword.Pseudo", foreground="#CC7A00")
        self.text.tag_configure("Token.Keyword.Reserved", foreground="#CC7A00")
        self.text.tag_configure("Token.Keyword.Type", foreground="#CC7A00")

        self.text.tag_configure("Token.Name.Class", foreground="#003D99")
        self.text.tag_configure("Token.Name.Exception", foreground="#003D99")
        self.text.tag_configure("Token.Name.Function", foreground="#003D99")

        self.text.tag_configure("Token.Operator.Word", foreground="#CC7A00")

        self.text.tag_configure("Token.Comment", foreground="#B80000")

        self.text.tag_configure("Token.Literal.String", foreground="#248F24")

    def deafultHighlight(self, argument):
        self.content = self.text.get("1.0", tk.END)
        self.lines = self.content.split("\n")

        if (self.previousContent != self.content):
            self.row = self.text.index(tk.INSERT).split(".")[0]
            self.column = self.text.index(tk.INSERT).split(".")[1]

            self.text.mark_set("range_start", self.row + ".0")
            data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def highlight(self, argument):
        self.content = self.text.get("1.0", tk.END)

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", "1.0")
            data = self.text.get("1.0", self.text.index(tk.INSERT))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def searchHighlight(self, term, color, regexOrNot):
        self.text.tag_configure("highlight", background=color)
        self.text.highlight_pattern(term, "highlight", regexOrNot)

    def individualHighlight(self, startPos, endPos, color):
        self.text.tag_configure("highlightedWord", background=color)
        self.text.tag_add("highlightedWord", startPos, endPos)

    def clearPreviousHighlight(self, startPos, endPos, color):
        self.text.tag_configure("clearHighlight", background=color)
        self.text.tag_add("clearHighlight", startPos, endPos)

    def clearAll(self, color):
        self.text.tag_delete("highlight")
        self.text.tag_delete("clearHighlight")
        self.text.tag_delete("highlightedWord")

    def getContent(self):
        return self.text.get(0.0, tk.END)

    def keypress(self, argument):
        self.deafultHighlight("argument")

    def replace(self, content):
        self.text.delete(1.0, tk.END)
        self.text.insert(1.0, content)

class Arshi(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.tabs = []

        self.notebook = ttk.Notebook(self)
        self.fileName = ""
        self.content = ""

        self.highlightColor = "#D2D2D2"
        self.standardSearchColor = "#ADDEAD"

        self.createtext()
        self.menubar()

        self.instance = 0

        self.bind_all("<Control-f>", self.search)

    def createtext(self):
        self.notebook.pack(fill=tk.BOTH, expand=True)
        t = Tab(self.notebook, "Untitled Document", self)
        self.tabs.append(t)

    def menubar(self):
        self.menu = tk.Menu(self)
        self.master.config(menu=self.menu)

        self.editMenu = tk.Menu(self.menu, font=("Tahoma", 9))
        self.editMenu.add_command(label="Find and Replace                    Ctrl+F", command=lambda: self.search("arg"))
        self.menu.add_cascade(label="Edit", menu=self.editMenu)

    def getColor(self):
        self.color = tkinter.colorchooser.askcolor(parent=self.searchMenu)[1]
        self.highlightLineEntry.insert(0, self.color)
        self.highlightColor = self.color

    def searchProtocol(self):
        self.instance = 0

        tabIndex = self.notebook.index(self.notebook.select())
        self.pos = '1.0'
        self.finalPos = '1.0'
        self.previousPos = self.pos
        self.previousFinalPos = self.finalPos

        self.tabs[tabIndex].clearAll("#FFFFFF")

        self.searchMenu.destroy()

    def search(self, arg):
        self.searchMenu = tk.Toplevel()
        self.searchMenu.title("Search and Replace")
        self.searchMenu.geometry("545x240")
        self.searchMenu.resizable(0, 0)

        self.searchDirection = tk.Label(self.searchMenu, text=" String to search:", anchor=tk.W, font=("Tahoma", 9))
        self.entry = tk.Entry(self.searchMenu, width=30, font=("Tahoma", 9))

        self.replaceDirection = tk.Label(self.searchMenu, text=" String to replace:", anchor=tk.W, font=("Tahoma", 9))
        self.replace = tk.Entry(self.searchMenu, width=30, font=("Tahoma", 9))

        self.searchOptions = tk.Label(self.searchMenu, text=" Search options:", anchor=tk.W, font=("Tahoma", 9))

        self.regex = tk.IntVar()
        self.regularExpression = tk.Checkbutton(self.searchMenu, text="Regex", variable=self.regex, anchor=tk.W, font=("Tahoma", 9))

        self.matchcase = tk.IntVar()
        self.matchCase = tk.Checkbutton(self.searchMenu, text="Match Case", variable=self.matchcase, anchor=tk.W, font=("Tahoma", 9))

        self.searchWay = tk.Label(self.searchMenu, text=" Search direction:", anchor = tk.W, font=("Tahoma", 9))

        self.direction = tk.IntVar()
        self.up = tk.Radiobutton(self.searchMenu, text="Up", variable=self.direction, value=1).place(x=175, y=75, width=140)
        self.down = tk.Radiobutton(self.searchMenu, text="Down", variable=self.direction, value=2).place(x=340, y=75, width=140)

        self.searchButton = tk.Button(self.searchMenu, text="Search", font=("Tahoma", 9), command=lambda: self.continueSearch(self.entry.get()))

        self.searchClose = tk.Button(self.searchMenu, text="Replace", font=("Tahoma", 9), command=lambda: self.replaceAll(self.entry.get(), self.replace.get()))

        self.searchRange = tk.Label(self.searchMenu, text=" Search range (line):", anchor = tk.W, font=("Tahoma", 9))
        self.rangeEntry = tk.Entry(self.searchMenu, width=30, font=("Tahoma", 9))

        self.highlightLine = tk.Label(self.searchMenu, text=" Search color (hex):", anchor=tk.W, font=("Tahoma", 9))
        self.highlightLineButton = tk.Button(self.searchMenu, text="Select", anchor=tk.W, font=("Tahoma", 9), command=self.getColor)
        self.highlightLineEntry = tk.Entry(self.searchMenu, width=30, font=("Tahoma", 9))

        self.occurenceLabel = tk.Label(self.searchMenu, text=" Search: {0} occurences, at occurence {1}".format("0", "0"), anchor=tk.CENTER, font=("Tahoma", 9))

        self.searchMenu.protocol("WM_DELETE_WINDOW", self.searchProtocol)

        self.searchDirection.place(x=0, y=0, width=200)
        self.replaceDirection.place(x=0, y=25, width=200)
        self.searchOptions.place(x=0, y=50, width=200)
        self.searchWay.place(x=0, y=75, width=200)
        self.searchRange.place(x=0, y=100, width=140)
        self.rangeEntry.place(x=220, y=100, width=325)
        self.highlightLine.place(x=0, y=125, width=145)
        self.highlightLineButton.place(x=145, y=125)
        self.highlightLineEntry.place(x=220, y=125, width=325)
        self.occurenceLabel.place(x =0, y=160)
        self.searchButton.place(x=20, y=195, width=200)
        self.searchClose.place(x=325, y=195, width=200)

        self.entry.place(x=220, y=0, width=325)
        self.replace.place(x=220, y=25, width=325)
        self.matchCase.place(x=220, y=50, width=140)
        self.regularExpression.place(x=375, y=50, width=140)

    def replaceAll(self, replaceTerm, newTerm):
        if len(replaceTerm) > 0:
            tabIndex = self.notebook.index(self.notebook.select())
            self.content = self.tabs[tabIndex].getContent().replace(replaceTerm, newTerm)
            self.tabs[tabIndex].replace(self.content)
            self.tabs[tabIndex].highlight("argument")

    def continueSearch(self, term):
        self.regexIndex = self.regex.get()
        self.regexOrNot = False

        if self.regexIndex == 1:
            self.regexOrNot = True

        self.hex = self.highlightLineEntry.get()
        self.validHex = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', self.highlightColor)

        if len(self.hex) == 0:
            self.validHex = False

        if len(term) > 0:
            tabIndex = self.notebook.index(self.notebook.select())

            if self.validHex:
                self.tabs[tabIndex].searchHighlight(term, self.hex, self.regexOrNot)
            else:
                self.tabs[tabIndex].searchHighlight(term, self.highlightColor, self.regexOrNot)

            numberOfInstances = self.tabs[tabIndex].text.get(0.0, tk.END).count(term)

            self.instance += 1

            if self.instance == 1:
                if self.regexOrNot == False:
                    self.pos = self.tabs[tabIndex].text.search(term, '1.0')
                    self.finalPos = '{}+{}c'.format(self.pos, len(term))
                else:
                    self.pos = self.tabs[tabIndex].text.search(term, '1.0', regexp=True)
                    self.finalPos = '{}+{}c'.format(self.pos, len(term))

                self.tabs[tabIndex].individualHighlight(self.pos, self.finalPos, "#ADDEAD")

            elif self.instance <= numberOfInstances:
                self.previousPos = self.pos
                self.previousFinalPos = self.finalPos

                self.pos = self.finalPos

                if self.regexOrNot == False:
                    self.pos = self.tabs[tabIndex].text.search(term, self.pos)
                    self.finalPos = '{}+{}c'.format(self.pos, len(term))
                else:
                    self.pos = self.tabs[tabIndex].text.search(term, '1.0', regexp=True)
                    self.finalPos = '{}+{}c'.format(self.pos, len(term))

                self.tabs[tabIndex].clearPreviousHighlight(self.previousPos, self.previousFinalPos, self.highlightColor)
                self.tabs[tabIndex].individualHighlight(self.pos, self.finalPos, "#ADDEAD")

            self.occurenceLabel["text"] = " Search: {0} occurences, selecting occurence {1}".format(self.tabs[tabIndex].getContent().count(term), str(min(self.tabs[tabIndex].getContent().count(term), self.instance)))

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Arshi")
    root.geometry("1024x600")
    window = Arshi(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

A: Try looking at How to use a regular expression in Tkinter text search method?. The problem may be with the way you are using the text.search feature for Text widgets


text:
Q: WPF и иконки Font Awesome Есть такой, весьма распространённый в web`е иконочный шрифт Font Awesome. По сути файл шрифтов + юникодовский символ дают на веб странице красивую иконку.
И вот я пытаюсь использовать такой же принцип в wpf приложении. По логике должно бы работать: c# вполне нормально дружит с юникодом, а начертание шрифта у него в файле. Но не работает.
Вот например стиль .fa-user-plus представляет собой символ f234
Делаю так:
FPInput.FontFamily = new FontFamily("file:///с:/fonts/#FontAwesome");
FPInput.Content =  "\uf234";

Собственно на форме вижу лишь пустой квадратик, то есть чего-то ему не хватает. Может кто понимает в чём тут проблема?


text:
Q: Using reflection on generics recursively I have the following classes:
public class BaseDataEntity
{
    private List<string> _Changes = new List<string>();

    public IEnumerable<string> GetChanges()
    {
        return _Changes;
    }

    public bool HasDataChanged
    {
        get { return (GetChanges().Count() > 0); }
    }

    public bool HasChildRecords
    {
        get { return (GetType().GetChildRecords().Count() > 0); }
    }
}

public class ChildRecords : IList<T> where T : BaseDataEntity
{

}

And a few helper methods:
public static PropertyInfo[] GetChildRecords(this Type aType)
{
    return aType.GetProperties().Where(pi => pi.IsChildRecords()).ToArray();
}

public static bool IsChildRecords(this PropertyInfo info)
{
    return (info.GetCustomAttributes(typeof(ChildRecordsAttribute), false).Length > 0);
}

What I'm trying to do is implement a property called HaveChildRecordsChanged using reflection. My question is how would I go about using reflection to check the HasDataChanged property of all ChildRecords of arbitrary depth?
I tried something like:
var isChanged = false;

foreach (var info in GetType().GetChildRecords())
{
    var childRecordObject = info.GetValue(this, null);
    var childRecords = childRecordObject as ChildRecords<BaseDataEntity>;   //cannot unbox this, it evaluates as null
    if (null != childRecords && childRecords.Any(x => x.HasDataChanged))
    {
        isChanged = true;   //never hit
    }
}

return isChanged;

A: ChildRecords<T> is generic so ChildRecords<Company> can't be cast to ChildRecords<BaseDataEntity>.
Since you already filter the property marked with the ChildRecordsAttribute the simplest solution would be to cast to IEnumerable and use OfType<BaseDataEntity>()
var childRecords = childRecordObject as IEnumerable; // IList<T> will be IEnumerable
if (null != childRecords && childRecords.OfType<BaseDataEntity>().Any(x => x.HasDataChanged))
{
    isChanged = true;
}


text:
Q: Explicit value must be specified when initialized replication from backup I have a big SQL Server database that I wan to replicate, I have try using snapshots but it takes so much time so I decided to initialized replication with a backup instead. The works for a period of time but at some point starts giving me this error:

Explicit value must be specified for identity column in table 'DocumentDetail' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column

The weird thing is that the table DocumentDetail is not in the Publication's database.
I have delete the subscriber and publisher and recreate them and after sometime it happen again.
Subscription on Publisher
EXEC sp_addsubscription
    @publication = N'Publication',
    @subscriber = N'SUBSCRIBER',
    @destination_db = N'ACCLTD',
    @sync_type = N'initialize with backup',
    @backupdevicetype='Disk',
    @backupdevicename='\\path\of\backup.bak',
    @subscription_type = N'pull',
    @update_mode = N'read only'
GO

On Subscriber
EXEC sp_addpullsubscription
    @publisher = N'VXACCPAC2',
    @publication = N'Publication',
    @publisher_db = N'DATABASE',
    @independent_agent = N'True',
    @subscription_type = N'pull',
    @description = N'',
    @update_mode = N'read only',
    @immediate_sync = 0
GO

Add the Pull Subscription Agent
EXEC sp_addpullsubscription_agent
    @publisher = N'DATABASE_SERVER',
    @publisher_db = N'DATABASE',
    @publication = N'Publication',
    @distributor = N'DISTRIBUTOR',
    @distributor_security_mode = 1,
    @distributor_login = N'domain\username',
    @distributor_password = N'password',
    @enabled_for_syncmgr = N'False',
    @frequency_type = 64,
    @frequency_interval = 0,
    @frequency_relative_interval = 0,
    @frequency_recurrence_factor = 0,
    @frequency_subday = 0,
    @frequency_subday_interval = 0,
    @active_start_time_of_day = 0,
    @active_end_time_of_day = 235959,
    @active_start_date = 20190827,
    @active_end_date = 99991231,
    @alt_snapshot_folder = N'',
    @working_directory = N'',
    @use_ftp = N'False',
    @job_login = N'domain\username',
    @job_password = N'password',
    @publication_type = 0
GO


text:
Q: Google Maps app crashes on open for iPad I'm traveling now and relying heavily on Google Maps on my iPad. with no warning, the app now crashes instantly when I click on it. no warning at all. I tap the icon, the default screen comes up, a second later the app closes.
Has anyone else experienced this problem? More imporrtantly, has anyone found a solution?
I tried restarting my iPad, as well as a hard reset. I do not have my laptop so I cannot sync. Since the app is one of the few default apps, I cannot delete and re-download it. I'm really at a loss here, so any suggestions are greatly appreciated.

A: Deleting a downloaded app does two things:

*

*Jettisons the data (like a reset for that app)

*Allows for a clean copy of the app to be downloaded again

You could restore the entire device and test maps before restring your backup or you could back it up and erase all content and settings and then test.
Flip a coin if one of those two options does not seem better to you and feel free to ask a follow on question if you find some more details to add to the question and don't want to edit them into the existing question.

A: I was about to say "Have you tried turning it on and off again" ;)
As an alternative to what you're experiencing whilst in your situation have you tried just using Safari and browsing to http://maps.google.com? Failing that you could download the National Geographic Map app. This uses some older-style-maps and if you zoom in far enough it revents to Bing Maps. I don't know why they didn't go for Google maps, probably a licensing thing as their app is a tidy $3.99.
The only real answer I can give you is update your iPad. Just think in a few months, with you'll be able to run updates without the need for a computer or iTunes.


text:
Q: do while loop won't run awk I am currently trying to get to grips with writing awk scripts, however, I'm running into issues with do...while loops.
    -bash-3.00$ cat basicloop.awk
    BEGIN { count = 1
            do {
            print "stuff"
            } while ( count != 1 )
    }

When I run it:
-bash-3.00$ awk -f basicloop.awk
awk: syntax error near line 3
awk: illegal statement near line 3
awk: syntax error near line 5
awk: bailing out near line 5
    {
        count=1
        do {
            print "I get printed at least once no matter what"
        } while ( count != 1 )
    }

awk: syntax error near line 3
awk: illegal statement near line 3
awk: syntax error near line 5
awk: bailing out near line 5
As you can see, these are both very simple do...while loops and I don't know why they're running into issues. The latter is taken directly from: http://www.ibm.com/developerworks/library/l-awk2/ and the former is my take on it.
    -bash-3.00$ nawk -f basicloop.awk
    stuff

Running the exact same files in nawk seems to get them to work fine, however, as can be seen above and below.
    I get printed at least once no matter what

The workaround is obviously to run them in nawk, but I'd sooner understand whatever the issue is and fix it (if possible) rather than simply ignore it.


text:
Q: Adjusting size of ListView according to objects in ListAdapter I have a listview which contents of different post. My current post limit per page load is 25. Each post is of different size. I want ListView size upto those 25 objects, i.e., it should accomodate all the objects from listadapter.
I have currently set my listview size as following.
<ListView
            android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="5000sp" >
</ListView>

My ListAdapter is set as:
ListAdapter adapter = new SimpleAdapter(NewsFeed.this, contactList,
                R.layout.list_item, new String[] { TAG_MESSAGE,
                        TAG_CREATETIME }, new int[] { R.id.message,
                        R.id.time });
        setListAdapter(adapter);

list_item.xml
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/time"
        android:gravity="right"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="#b1b1b1"
        android:background="#abc0e3" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/cover" />

    <TextView
        android:id="@+id/message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:text="TextView"
        android:linksClickable="true"
android:autoLink="web" />

    </LinearLayout>

A: see if this works for you, where you adjust the width then you can decide on what width to use based on the text length,
/* create an inline class that defines each item in the list
  private class Post
  {
    String time;
    String message;
    Bitmap bmp;
    public String getTime(){return time;}
    public String getMessage(){return message;}
    public Bitmap getBitmap(){return bmp;}
  }

  //** populate your array with each item in list
  ArrayList<Post> array = new ArrayList<Post>();
  Post p = new Post();
  //* ..............

  ListAdapter  adapter = new ListAdapter (this, array);
  listView.setAdapter(adapter);

  private class ListAdapter  extends BaseAdapter
  {
    Context context;
    ArrayList<Post> contactList;
    public ListAdapter(Context context, ArrayList<Post> contactList)
    {
      this.context = context;
      this.contactList = contactList;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
      try
      {
          if(convertView==null)
          {
            LayoutInflater inflater = getLayoutInflater();
            convertView = inflater.inflate(R.layout.list_item, parent, false);
          }
          ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
          TextView timeview = (TextView) convertView.findViewById(R.id.time);
          TextView msgview = (TextView) convertView.findViewById(R.id.message);

          Post  post = getItem(position);
          imageView.setImageBitmap(post.getBitmap());
          timeView.setText(post.getTime());
          messageView.setText(post.getMessage());

          int width = convertView.getWidth();
          int height = convertView.getHeight();

          int messageWidth = post.getMessage().length();

          //* adjust the width based on your message width
          //* width = ........ do something here
          //* set the desired width here
          convertView.setLayoutParams(new LayoutParams(width, height));

        return convertView;
      }
      catch(Exception e)
      {
      }
      return null;
    }
    @Override
    public int getCount()
    {
      return contactList.size();
    }

    @Override
    public Post getItem(int position)
    {
        return contactList.get(position);
    }

    @Override
    public long getItemId(int position)
    {
       return 0;
    }
  }

A: Change code in list_item.xml
android:layout_width="wrap_content"  to  fill_parent or match_parent


text:
Q: Setting variable to a return from a callback function getElementId function:
function getIdElements(idname, callback) {
    callback(document.getElementById(idname))
};

I want to use it like this but plLen gets undefined:
var plLen = getIdElements("length", function(e){return e.textContent});

I would love if someone could explain it as deep as possible. Thank you.

A: You can simply return the value the callback returns:
function getIdElements(idname, callback) {
     return callback(document.getElementById(idname));
}

which is pretty much the same as getting the return value from the callback, and return it. Here's a verbose version:
function getIdElements(idname, callback) {
     var element = document.getElementById(idname);
     var callbackRetrunValue = callback(element);
     return callbackRetrunValue;
}

In your code: with no return value, the value you read from your getIdElements is simply undefined: What does javascript function return in the absence of a return statement?


text:
Q: How to attach Pdf file to mail I am try to attach a ready pdf file to mail using java,so for that I have try below
String filename = "file.pdf";

 ByteArrayOutputStream bos = new ByteArrayOutputStream();
??.write(bos);

 DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/pdf");
 MimeBodyPart mbp2 = new MimeBodyPart();
 mbp2.setDataHandler(new DataHandler(fds));
 mbp2.setFileName(filename);

I am ot understand what  will be instead of '??'.
so please suggest me about that.

A: javax.mail.util.ByteArrayDataSource introduced in JavaMail 1.4 and following are some pointers on same

*

*ByteArrayDataSource API

*Java Mail API

*Official Page
If you use Spring's JavaMail API, you can do this sort of thing fairly easily (or at least, as easily as the JavaMail API allows, which isn't much).
The attachment data can be any of Spring's Resource abstractions, ByteArrayResource is just one of them.
Note that this part of the Spring API stands on its own, it does not require (but does benefit from) the Spring container.
JavaMailSenderImpl mailSender = ... instantiate and configure JavaMailSenderImpl here
final byte[] data = .... this holds my PDF data

mailSender.send(new MimeMessagePreparator() {
   public void prepare(MimeMessage mimeMessage) throws Exception {
      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
     // set from, to, subject using helper
     helper.addAttachment("my.pdf", new ByteArrayResource(data));
   }
});

A: Please refer the below code :
 if (arrayInputStream != null && arrayInputStream instanceof ByteArrayInputStream) {
    // create the second message part with the attachment from a OutputStrean
    MimeBodyPart attachment= new MimeBodyPart();
    ByteArrayDataSource ds = new ByteArrayDataSource(arrayInputStream, "application/pdf");
    attachment.setDataHandler(new DataHandler(ds));
    attachment.setFileName("Report.pdf");
    mimeMultipart.addBodyPart(attachment);
}


text:
Q: How to debug apache virtual hosts and domain conf? I have added a new domain to Amazon linux server running apache
<VirtualHost *:80>
    ServerName mydomain.com
    ServerAlias www.mydomain.com
    DocumentRoot /var/www/mydomain
    ErrorDocument 404 /index.html
    ErrorLog /var/log/mydomain.com-error_log
    CustomLog /var/log/mydomain.com-access_log common
    <Directory /var/www/mydomain>
       Options FollowSymLinks
       AllowOverride None
       Require all granted
    </Directory>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

Restarted the server
checked status
sudo systemctl restart httpd active (running) 1 min
But for whatever reason the default apache index.html is served
Directory exists for the new domain , index.html is there chmod 644 done
Error log for the new domain is empty.
Access log and error lod are empty
-rw-r--r--.  1 root   root           0 Dec 21 15:26 mydomain.com-access_log
-rw-r--r--.  1 root   root           0 Dec 21 09:50 mydomain.com-error_log

tail of host error_log is normal
AH00489: Apache/2.4.37 (Red Hat Enterprise Linux) OpenSSL/1.1.1c configured -- resuming normal operations
[Mon Dec 21 15:02:24.161922 2020] [core:notice] [pid 73594:tid 140519198484800]
AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'

I feel a permissions/cert problem. Or one more thing letsencrypt crt has been installed for the new domain probably successfully
[ec2-user@ip-xx-xx-xx-xx ~]$ wget mywwwdomain.com
--2020-12-21 15:57:26--  http://mywwwdomain.com/
Resolving mywwwdomain.com (mywwwdomain.com)... 55.55.55.55
Connecting to mywwwdomain.com (mywwwdomain.com)|55.55.55.55|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://mywwwdomain.com/ [following]
--2020-12-21 15:57:26--  https://mywwwdomain.com/
Connecting to mywwwdomain.com (mywwwdomain.com)|55.55.55.55|:443... connected.
ERROR: The certificate of 'mywwwdomain.com' is not trusted.
ERROR: The certificate of 'mywwwdomain.com' hasn't got a known issuer.
The certificate's owner does not match hostname 'mywwwdomain.com'
[ec2-user@ip-xx-xx-xx-xx ~]$

55.55.55.55 - my IP address
How to debug further and fix this?

A: If you added a new domain in a new file, make sure the new file is properly included in the main httpd config file.
You can get a list of the VHs apache is serving issuing the following command:
# apache2ctl -S (On Debian/Ubuntu), # apachectl -S (On CentOS/RHEL) or
# httpd -S.


text:
Q: Yaml/Jinja2/Ansible Processing dict list with jinja template How to process dict list like below, any method using jinja or ansible filter or any other way is welcome
From:
test_dict:
  USA:
    New York:
      - Alice
      - Bob
    Dallas:
      - James
      - Kim

  UK:
    London:
      - Johnson
      - Charles
    Leeds:
      - Clark
      - Geoge

To:
test_dict_processed:
  - {'country': "USA", 'city': "New York", 'name': "Johnson" }
  - {'country': "USA", 'city': "New York", 'name': "Alice" }
  - {'country': "USA", 'city': "New York", 'name': "Bob" }
  - {'country': "USA", 'city': "Dallas", 'name': "James" }
  ...
  - {'country': "UK", 'city': "London", 'name': "Charles" }

Below is my best approach, but generated in string, not list of dicts:
test_dict_processed:
  "
    {% set name_list_ = [] %}
    {% for country in names.keys() %}
      {% for city in names[country].keys() %}
        {% for name in names[country][city] %}
          - {'country': country, 'city': city, 'name': name } \n
        {% endfor %}
      {% endfor %}
    {% endfor %}
  "

A: An easy solution is to pass the text generated by your template through the from_yaml filter. For example, this playbook:
- hosts: localhost
  gather_facts: false
  vars:
    test_dict:
      USA:
        New York:
          - Alice
          - Bob
        Dallas:
          - James
          - Kim

      UK:
        London:
          - Johnson
          - Charles
        Leeds:
          - Clark
          - Geoge
  tasks:
    - set_fact:
        test_dict_processed_text: |
          {% for country in test_dict.keys() %}
          {% for city in test_dict[country].keys() %}
          {% for name in test_dict[country][city] %}
          - country: {{country}}
            city: {{city}}
            name: {{name}}
          {% endfor %}
          {% endfor %}
          {% endfor %}

    - set_fact:
        test_dict_processed: "{{ test_dict_processed_text|from_yaml }}"

    - debug:
        var: test_dict_processed|from_yaml

Results in this output:
PLAY [localhost] *****************************************************************************

TASK [set_fact] ******************************************************************************
ok: [localhost]

TASK [set_fact] ******************************************************************************
ok: [localhost]

TASK [debug] *********************************************************************************
ok: [localhost] => {
    "test_dict_processed": [
        {
            "city": "New York",
            "country": "USA",
            "name": "Alice"
        },
        {
            "city": "New York",
            "country": "USA",
            "name": "Bob"
        },
        {
            "city": "Dallas",
            "country": "USA",
            "name": "James"
        },
        {
            "city": "Dallas",
            "country": "USA",
            "name": "Kim"
        },
        {
            "city": "London",
            "country": "UK",
            "name": "Johnson"
        },
        {
            "city": "London",
            "country": "UK",
            "name": "Charles"
        },
        {
            "city": "Leeds",
            "country": "UK",
            "name": "Clark"
        },
        {
            "city": "Leeds",
            "country": "UK",
            "name": "Geoge"
        }
    ]
}

PLAY RECAP ***********************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


text:
Q: Please fix the 'sdk.dir' property in the local.properties file. Studio removed slashes in path. Import project error. How to solve, debug? I am trying to import a project. It gives an error for local.properties
Please fix the 'sdk.dir' property in the local.properties file.
Found one similar question here, but no solutions worked.
Error is:
The SDK directory C:\MyProject\C:AndroidSdk does not exists
I edit local.properties and set sdk.dir=C\:\\AndroidSdk and hit Try again, but it is showing the same error and also removed slashes and saved C:AndroidSdk as property value in newly generated local.properties.
I am Working on windows, Android Studio version : 3.3.1

A: When you import or try to open a dev to dev project, Android Studio try to sync the project SDK, showing a message informing a SDK error. Do not click on the OK button.
Just close the message and try to execute the project.

A: Instead of importing the project, try to open it as an existing project, then you will get a prompt from the android studio that it didn't find the default path so it chose one specific to your computer

A: Couldn't find what actual problem was. But upgrading Android Studio to 3.4 solved this problem.

A: If i delete the local.properties and rerun the build all works.
File --> Invalidate caches/restart


text:
Q: UnboundLocalError: Decorator with default parameters Here is my decorator code. I'm getting UnboundLocalError for some reason but I couldn't find it.
>>> def validate(schema=None):
        def wrap(f):
            def _f(*args, **kwargs):
                if not schema:
                schema = f.__name__
            print schema
            return f()
            return _f
        return wrap

>>> @validate()
    def some_function():
        print 'some function'

>>> some_function()
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    some_function()
  File "<pyshell#22>", line 4, in _f
    if not schema:
UnboundLocalError: local variable 'schema' referenced before assignment
>>>

So, I thought maybe it's better to post here. I might be missing something.
Thanks.

A: The compiler can't determine schema's proper scope. Either use nonlocal schema (3.x) within _f() or change the definition of _f() slightly:
def _f(self, schema=schema, *args, **kwargs):


text:
Q: How to return a sum of 0 for SQL Server case with no match I have a query that sums sales into case buckets, which works great, except that I need it to return 0 for buckets that have no sales.
This is for MS SQL Server 2016, i've searched and found some similar issues that recommended using Coalesce, but i can't figure out how to apply that to my query.
The table data looks like this:
surveyid, projid, surveyperiod, quartersold, averagebaseprice2
65374, 12079, 2018-12-01, 4, 301805
70641, 10366, 2018-12-01, 9, 584390
etc
select t.range, sum(s.quartersold) as qtrsold, surveydate
from (
  select concat(datepart(quarter,surveyperiod), datepart(year,surveyperiod)) as surveydate, quartersold, case
   when averagebaseprice2 between 0 and 199999.99 then 'Less than $200,000'
   when averagebaseprice2 between 200000 and 224999.99 then '$200,000 - $224,000'
   when averagebaseprice2 between 225000 and 249999.99 then '$225,000 - $249,999'
   when averagebaseprice2 between 250000 and 274999.99 then '$250,000 - $274,999'
   when averagebaseprice2 between 275000 and 299999.99 then '$275,000 - $299,999'
   when averagebaseprice2 between 300000 and 324999.99 then '$300,000 - $324,999'
   when averagebaseprice2 between 325000 and 349999.99 then '$325,000 - $349,999'
   when averagebaseprice2 between 350000 and 374999.99 then '$350,000 - $374,999'
   when averagebaseprice2 between 375000 and 399999.99 then '$375,000 - $399,999'
   when averagebaseprice2 between 400000 and 424999.99 then '$400,000 - $424,999'
   when averagebaseprice2 between 425000 and 449999.99 then '$425,000 - $449,999'
   when averagebaseprice2 between 450000 and 474999.99 then '$450,000 - $474,999'
   when averagebaseprice2 between 475000 and 499999.99 then '$475,000 - $499,999'
   when averagebaseprice2 between 500000 and 599999.99 then '$500,000 - $599,999'
   when averagebaseprice2 between 600000 and 699999.99 then '$600,000 - $699,999'
   when averagebaseprice2 between 700000 and 799999.99 then '$700,000 - $799,999'
   when averagebaseprice2 between 800000 and 899999.99 then '$800,000 - $899,999'
   when averagebaseprice2 between 900000 and 999999999.99 then '$900,000 and greater'
   end as range
  from surveys s
  where datepart(year,s.surveyperiod) = 2018
) t
group by t.range, surveydate

(Sorry i can't figure out how to format this better)
with the above query i'm getting:
        range                 qtrsold   surveydate
    $250,000 - $274,999 8   12018
    $275,000 - $299,999 8   12018
    $300,000 - $324,999 59  12018
    $325,000 - $349,999 22  12018
    $350,000 - $374,999 139 12018
    $375,000 - $399,999 82  12018
    $400,000 - $424,999 103 12018
    $425,000 - $449,999 92  12018
    $450,000 - $474,999 142 12018
    $475,000 - $499,999 144 12018
    $500,000 - $599,999 314 12018
    $600,000 - $699,999 64  12018
    $700,000 - $799,999 80  12018
    $800,000 - $899,999 18  12018
    $900,000 and greater    6   12018
i'd like to get:
    range                 qtrsold   surveydate
Less than $200,000      0       12018
        $200,000 - $224,000     0       12018
        $225,000 - $249,999     0       12018
    $250,000 - $274,999 8   12018
    $275,000 - $299,999 8   12018
    $300,000 - $324,999 59  12018
    $325,000 - $349,999 22  12018
    $350,000 - $374,999 139 12018
    $375,000 - $399,999 82  12018
    $400,000 - $424,999 103 12018
    $425,000 - $449,999 92  12018
    $450,000 - $474,999 142 12018
    $475,000 - $499,999 144 12018
    $500,000 - $599,999 314 12018
    $600,000 - $699,999 64  12018
    $700,000 - $799,999 80  12018
    $800,000 - $899,999 18  12018
    $900,000 and greater    6   12018
Thank you very much for any assistance.

A: You need to generate the ranges separately, and then use left join to bring in the data.  It is unclear where the columns are coming from, so the following is a guess:
select (datename(quarter, s.surveyperiod) + datename(year, s.surveyperiod)) as surveydate,
       v.range,
       coalesce(sum(?.quartersold), 0) as qtrsold
from (values ('Less than $200,000', 0 200000),
             ('$200,000 - $224,000', 0, 225,000),
             ('$225,000 - $249,999', 225000, 250000),
             . . .
     ) v(range, lo, hi) left join
     surveys s
     on s. averagebaseprice2 >= v.lo and s.averagebaseprice2 < v.hi left join
     projects p
     on s.projid = p.projid
where s.surveyperiod >= '2018-01-01' and s.surveyperiod < '2019-01-01'
group by (datename(quarter, s.surveyperiod) + datename(year, s.surveyperiod)) as surveydate,
         v.range  ;


text:
Q: Can i open Facebook app or new Chrome window from InAppBrowser? Is it possible to open new Chrome window from InAppBrowser when option _blank is used?
cordova.InAppBrowser.open(url, '_blank', 'location=no,hide=yes,zoom=no');

I added attribute target="_blank" to all links on the page, but this wouldn't open a new window.
Does anyone know if this is possible?

A: Try using window.open instead of cordova.InAppBrowser.open
I have been using window.open without issues in my Hybrid app
There is no need to add _blank as this is the default setting..

A: With the InAppBrowser you can call urls and you can show, depending of your platform, some files in there.
There is no way to just «start» another app, but you can:

*

*Open a file with another app. Therefore you need a plugin. An overview you can get here:

http://plugreg.com/search?q=open
http://cordova.apache.org/plugins/?q=intent
If you want to open an external url, read this:
http://cordova.apache.org/docs/en/latest/guide/appdev/whitelist/index.html

*You can share content out of your app. Therefore you also need a plugin, use this one:

http://plugreg.com/plugin/EddyVerbruggen/SocialSharing-PhoneGap-Plugin


text:
Q: What is the meaning of the following syntax: [increment]: () => {}? Here is the code snippet I am trying to understand.
import { increment } from '../features/counter/counterSlice'
const object = {
  [increment]: () => {}
}
console.log(object)
// logs { "counter/increment": Function}

Specifically what does the following syntax do?
[increment]: () => {}
Increment is a reducer function created by createSlice().

A: This
const object = {
  [increment]: () => {}
}

is identical in result to
const object = {};
object[increment] = () => {};

In other words creates an arrow function, named whatever the value of variable increment is, on object

A: const object = {
  [increment]: () => {}
}

This creates an object that has one property. The name of that property is defined by the string in the variable named increment. If increment had a value of "foo" then this would be equivalent to:
const object = {
  foo: () => {}
}

The value of that property is a function that does nothing.
An arrow function has this form
(...args) => { /* function body */ }

So () => {} is a function that takes no arguments, and has no statements in its function body.


text:
Q: Angular Controller error 'Argument 'MainCtrl' is not a function, got undefined' At some point this afternoon I suddenly got the following AngularJS error: Argument 'MainCtrl' is not a function, got undefined
I have a good version still running in Chrome without any errors, so I'm attempting to find the diffs - however to no avail.
I would appreciate any advice on how to fix the error Argument 'MainCtrl' is not a function, got undefined
I load the controllers.js file in index.html - within the body section:
 <!DOCTYPE html>
 <html ng-app="rage.ui">

 <head>
     <!-- loading css files here... -->
 </head>

 <body ng-controller="MainCtrl as main">

  <!-- Wrapper-->
  <div id="wrapper">
     <!-- Navigation -->
  </div>

  <script src="app/app.js"></script>
  <script src="app/config.js"></script>
  <script src="app/js/controllers.js"></script>

</body>

Here's the MainCtrl in my controllers.js file (also loaded in index.html) -
* MainCtrl - controller */

(function () {
 'use strict';
 angular.module('rage.ui')
    .controller('MainCtrl', ['$scope', '$interval', '$window', 'widgetDefinitions', main])
    .factory('widgetDefinitions', [widgetDefinitions])
    .value('defaultWidgets', [
    { name: 'random' },
    { name: 'time' },
    { name: 'datamodel' },
    {
        name: 'random',
        style: {
            width: '50%'
        }
    },
    {
        name: 'time',
        style: {
            width: '50%'
        }
    }
    ]);

function main($scope, $interval, $window, widgetDefinitions, defaultWidgets) {
    this.userName = 'Risk user';
    // ...
}
  function widgetDefinitions(RandomDataModel) {
    return [
      {
          name: 'random',
          directive: 'wt-scope-watch',
          attrs: {
              value: 'randomValue'
          }
      }
      {
          name: 'treegrid',
          templateUrl: 'app/views/templateGadget/treeGrid.html',
          title: "Tree Grid Report",
          attrs: {
              width: '50%',
              height: '250px'
          }
      }
    ];
  }

})();

in my attempt to add a new 'gadgetModelFactory' to the malhar Angular-Dashboard framework, I broke my system.
Here's the good version of my new factory, now fixed:
'use strict';

angular.module('rage').
factory('gadgetDataModel', function ($scope, WidgetDataModel) {
function gadgetDataModel() {
    var test = 123;
}

gadgetDataModel.prototype = Object.create(WidgetDataModel.prototype);
gadgetDataModel.prototype.constructor = WidgetDataModel;

angular.extend(gadgetDataModel.prototype = {
    init: function () {
        // to be overridden by subclasses
        var dataModelOptions = this.dataModelOptions;
    },

    destroy: function () {
        // to be overridden by subclasses
        WidgetDataModel.prototype.destroy.call(this);
        $interval.cancel(this.intervalPromise);
    }
});

});

and my app.config:
(function () {
angular.module('rage.ui', [
    'ui.router',
    'ui.bootstrap',
    'ui.dashboard'
])
})();

A: *

*Have a look at other posts (AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined')

*Check whether you defined ng-app properly

*Check whether you have listed the JS files properly in the index

*Try to rewrite your controllers to the more conventional way (see egghead.io tutorials)

A: Maybe you have two files .js with same module name. Eg.:
file1.js:
var appControllers = angular.module('appControllers', []);

file2.js:
var appControllers = angular.module('appControllers', []);


text:
Q: Redirect does nothing in react-router-dom import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";
class App extends Component {
  constructor(){
    super();
    this.state = {
      windowWidth: window.innerWidth,
      navOpen: true,
      user: {
        id: '',
        name: '',
        email: ''
      }
    };
  }

  signIn = (data) => {
    if(data){
      this.setState({user: {
        id: data.id,
        name: data.name,
        email: data.email
      }});
      return <Redirect to='/'/> /*Right here when it come to here the page does nothing and no errors?*/
    }
  }

render() {
    return(
      <div className='app'>
      <Router>
        <NavBar onNavClick={this.onNavClick} navOpen={this.state.navOpen}/>
        <Switch>
          <Route path="/" exact component={() => <Home />} />
          <Route path="/about" exact component={() => <About />} />
          <Route path="/contact" exact component={() => <Contact />} />
          <Route path='/catalogue' exact component={() => <Catalogue />} />
          <Route path='/login' exact component={() => <Login signIn={this.signIn} onRouteChange={this.onRouteChange}/>}/>
        </Switch>
      </Router>
      </div>
      );
  }
}
export default App;

I have tried again and again but it will not change the page to the root and will not come with any errors with it. I have looked everywhere but its just the same thing. The log in page just runs sign in function. What am I doing wrong?

A: Issues

*

*You can't just return JSX from a function callback like that and expect it to be rendered, you will need to use the history object and issue an imperative redirect, i.e. history.replace("/");.

*The redirect won't work from the signIn callback since the App component is outside the routing context provided by Router being rendered by App.

*You are using the Route's component prop to render components but you are using an inline function, this will actually unmount and remount the components anytime App rerenders.

Solution

*

*Move the Router component higher in the React tree in order for App to be able to access the same routing context the Routes are. You will need to also pass the history object to App. This would be trivial if App were a functional component where you could use the useHistory React hook, but since it isn't you will need to use the slightly less trivial withRouter Higher Order Component and inject the route props.
Access history from injected props:
signIn = (data) => {
  if (data) {
    this.setState({user: {
      id: data.id,
      name: data.name,
      email: data.email
    }});
    this.props.history.replace("/");
  }
}

Decorate App with withRouter HOC:
export default withRouter(App);

Wrap App in the Router.
<Router>
  <App />
</Router>

*Fix the routes by using the component prop correctly, and using the render prop when you need to pass additional props.
<Switch>
  <Route path="/about" component={About} />
  <Route path="/contact" component={Contact} />
  <Route path='/catalogue' component={Catalogue} />
  <Route
    path='/login'
    render={() => <Login signIn={this.signIn} onRouteChange={this.onRouteChange}/>}
  />
  <Route path="/" component={Home} />
</Switch>

A: for the / for the home you need to specify
<Route exact path="/" component={Home} />

A: Please take a look at the history https://reactrouter.com/web/api/history. For example, you can write history.push("/location"); the page will be redirected, and the states still don`t get lost. For me, it has been the easiest way to handle the redirecting in react.


text:
Q: Running artisan command from controller or route I use Spatie Laravel package I can take backup by running this command
php artisan backup:run

but I want to take back up form admin panel and running this command form controller, I create a route and controller and in the controller, I do this
public function backup(){
    \Artisan::call('backup:run');
    return "successfully!";
}

when I route to this finally I got the success message but in the backup file, nothing added.

A: You can put artisan command in sheduler. It will make back up for example every day at the same time. You do it in app/console/Kernel.php
$schedule->command('backup:run')->daily();

Remember to set your server for cron jobs:
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

Read more: https://laravel.com/docs/5.6/scheduling


text:
Q: Creating the converter bean I'm new to learning Spring. I use the built-in Spring converter in my application. But in the service layer, when creating the constructor, it does not see the converter bean.
How to transfer the converter bean to Spring?
My error code:

Parameter 1 of constructor in ru.web.service.ClientService required a
bean of type 'org.springframework.core.convert.converter.Converter'
that could not be found.
Action:
Consider defining a bean of type
'org.springframework.core.convert.converter.Converter' in your
configuration.

A: You have to define your class Converter as a bean and change your ClientService annotation to @Service.
Converter.java
@Component
public class Converter<M, D>

ClientService.java
@Service
public class ClientService


text:
Q: Calling function in API retrieves Failed to load resource: the server responded with a status of 500 () I'm working on a code with a stored procedure in mvc framework. I have a field WorkOverDate to pick a date and save it in Unit table. After it is saved I'm looking to add that date into another table called WorkOver.
The problem comes when I try to call the function with the stored procedure in the api that updated the info in the Unit and I get this:
Failed to load resource: the server responded with a status of 500 ()
I'm not sure what to do here. Everything I modify in the page, saves correctly, but the stored procedure doesn't work. Any suggestion is highly appreciated.
I have a UnitRepository file which has the following code:
public void UpdateWorkOver()
        {

            using (var cmd = _db.Database.GetDbConnection().CreateCommand())
            {

                cmd.CommandText = "dbo.WorkOverAddDate";
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                bool isOpen = cmd.Connection.State == ConnectionState.Open;
                if (!isOpen)
                {
                    cmd.Connection.Open();
                }

                cmd.ExecuteNonQuery();

                if (!isOpen)
                {
                    cmd.Connection.Close();
                }
            }

        }

The stored procedure for this is:
CREATE PROCEDURE [dbo].[WorkOverAddDate]

AS

INSERT INTO dbo.WorkOver
           (UnitID, WODate, CreatedBy, Created)

SELECT UnitID, WODate, CreatedBy, Created

FROM dbo.WorkOver

UNION

SELECT  ID, WorkOverDate, UpdatedBy, Updated

FROM dbo.Unit

Also, I have an API where I'm calling the function with the Stored Procedure when saving the page.
//Edit
                    unit.Updated = DateTime.Now;
                    unit.UpdatedBy = _securityHelper.CurrentUserID.ToString();
                    _auditHelper.After = unit;

                    _repoUnit.Edit(unit);
                    if (unit.WorkOverDate != null)
                    { ((UnitRepository)_repoUnit).UpdateWorkOver(); }

A: The problem was that I had to add in the stored procedure :
Where WorkOverDate IS NOT NULL

as a null parameter cannot be added to a column that is not nullable. Now it's working.


text:
Q: Update UI in android App without making users to update the App I am building an app using , so the first time I upload the app to playstore, it will go with pre-defined Menu options and other stuffs.
Now, suppose I want to add a menu option in the Header of the App for any festive seasons or some awesome offers, and on clicking the menu, I should display the latest offers.
Is there any way to implement this feature without having to go through the process of again uploading to appstore and making users to update the app??

A: There is a concept of Over The Air (OTA) updates which you are referring to here. This is provided by Expo (by default create-react-native uses expo), firebase and Microsoft code push. You can read about it more here on official expo docs. If you are not using Expo then i prefer Code Push

A: Build an api endpoint you call at the app startup seems to be the easiest way to do this. Take a look at firebase if you don't want to build a full api and server yourself. Cloud functions are easy to use and could do the job in your case.


text:
Q: Apache had been compromised or being used as a proxy to attack and other system I received a messages from Sony Interactive Entertainment LLC ("SIE") says my server is abusive to their services.
I checked and make sure:

*

*No one get remote access to my server except me. SSH and all other service only accept my IP, all other are being blocked by firewall

*Apache (httpd) not be hacked, no PHP and any active script is running on my server.

*All log (system, secure, message, ...) are empty or don't have any strange

Except apache access log I found:
77.38.177.177 - - [30/Jun/2017:19:21:48 +0000] "CONNECT auth.api.sonyentertainmentnetwork.com:443 HTTP/1.1" 400 226 "-" "-"
138.201.29.228 - - [30/Jun/2017:19:21:48 +0000] "CONNECT www.stoiximan.gr:443 HTTP/1.1" 200 - "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1409.70 Safari/537.36"
94.122.39.35 - - [30/Jun/2017:19:21:49 +0000] "A" 400 226 "-" "-"
77.108.80.2 - - [30/Jun/2017:19:20:48 +0000] "CONNECT artiwell.com:443 HTTP/1.1" 200 - "-" "-"
138.201.19.161 - - [30/Jun/2017:19:21:48 +0000] "CONNECT www.bet-at-home.com:443 HTTP/1.1" 200 - "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/17.0.1232.63 Safari/537.36"
77.108.80.2 - - [30/Jun/2017:19:21:48 +0000] "GET http://sea-tools.com.ua/oborudovanie/betonomeshalki/filter/287-k-werk HTTP/1.1" 200 25537 "-" "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36"
94.158.152.58 - - [30/Jun/2017:19:21:49 +0000] "A" 400 226 "-" "-"
138.201.19.161 - - [30/Jun/2017:19:21:48 +0000] "GET http://sports.titanbet.com/en/e/5260805/Ansan-Police-v-Ansan-Greeners?mkt_grp_code=TMWIN HTTP/1.1" 200 25023 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.604.118 Safari/537.36"
117.1.114.50 - - [30/Jun/2017:19:21:49 +0000] "GET http://static.doubleclick.net/instream/ad_status.js HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
94.158.152.58 - - [30/Jun/2017:19:21:49 +0000] "CONNECT static.doubleclick.net:443 HTTP/1.0" 200 - "-" "-"
185.71.186.147 - - [30/Jun/2017:19:21:49 +0000] "CONNECT static.sportsinteraction.net:443 HTTP/1.1" 200 - "-" "-"

I have to set firewall to reject every HTTP request to external server to terminate that attack.
By I still have some unanswerable questions are:

*

*Why some one can use my apache connect to external server?

*How can they do that? How to stop this issue without use firewall to block every thing?

Below are my apache virtual host configuration:
NameVirtualHost *:80

<Directory "/data/websource">
    DirectoryIndex index.html index.php
    AllowOverride All
    # Allow open access:
    Require all granted
</Directory>
<VirtualHost *:80>
    ServerName subdomain1.my.domain
    DocumentRoot "web_root/subdomain1/source/www"
    ServerAdmin postmaster@dummy-host2.localhost
    ErrorLog "logs/subdomain1-error.log"
    CustomLog "logs/subdomain1-access.log" combined

    #turn on proxy

    ProxyPreserveHost On
    ProxyRequests On

    ProxyPass /classroom1 http://xyz.my.other.ip/classroom1
    ProxyPassReverse /classroom1 http://xyz.my.other.ip/classroom1

    ProxyPass /bigbluebutton/ http://xyz.my.other.ip/bigbluebutton/
    ProxyPassReverse /bigbluebutton/ http://xyz.my.other.ip/bigbluebutton/

    ProxyPass /client/ http://xyz.my.other.ip/client/
    ProxyPassReverse /client/ http://xyz.my.other.ip/client/

    ProxyPass /bbb http://xyz.my.other.ip/
    ProxyPassReverse /bbb http://xyz.my.other.ip/

    ProxyPass /demo/ http://xyz.my.other.ip/demo/
    ProxyPassReverse /demo/ http://xyz.my.other.ip/demo/

    ProxyPass /streams.xml http://xyz.my.other.ip/streams.xml
    ProxyPassReverse /streams.html http://xyz.my.other.ip/streams.html

    ProxyPass /testjava.html http://xyz.my.other.ip/testjava.html
    ProxyPassReverse /testjava.html http://xyz.my.other.ip/testjava.html

    ProxyPass /myngleapi/ http://xyz.my.other.ip/myngleapi/
    ProxyPassReverse /myngleapi/ http://xyz.my.other.ip/myngleapi/

    ProxyPass /myngleapi http://xyz.my.other.ip/myngleapi
    ProxyPassReverse /myngleapi http://xyz.my.other.ip/myngleapi

    ProxyPass /help.html http://xyz.my.other.ip/help.html
    ProxyPassReverse /help.html http://xyz.my.other.ip/help.html

    ProxyPass /call.php http://www.source/mynglevline/call.php
    ProxyPassReverse /call.php http://www.source/mynglevline/call.php

</VirtualHost>
<VirtualHost *:80>
    ServerName subdomain2.my.domain
    DocumentRoot "web_root/subdomain1/source/admin"
    ServerAdmin postmaster@dummy-host2.localhost
    ErrorLog "logs/subdomain1-admin-error.log"
    CustomLog "logs/subdomain1-admin-access.log" combined

</VirtualHost>
<VirtualHost *:80>
    ServerName subdomain3.my.domain
    DocumentRoot "web_root/subdomain3/source/www"
    ServerAdmin postmaster@dummy-host2.localhost
    ErrorLog "logs/subdomain3-error.log"
    CustomLog "logs/subdomain3-access.log" combined

    #turn on proxy

    ProxyPreserveHost On
    ProxyRequests On

    ProxyPass /classroom1 http://xyz.my.other.ip/classroom1
    ProxyPassReverse /classroom1 http://xyz.my.other.ip/classroom1

    ProxyPass /bigbluebutton/ http://xyz.my.other.ip/bigbluebutton/
    ProxyPassReverse /bigbluebutton/ http://xyz.my.other.ip/bigbluebutton/

    ProxyPass /client/ http://xyz.my.other.ip/client/
    ProxyPassReverse /client/ http://xyz.my.other.ip/client/

    ProxyPass /bbb http://xyz.my.other.ip/
    ProxyPassReverse /bbb http://xyz.my.other.ip/

    ProxyPass /demo/ http://xyz.my.other.ip/demo/
    ProxyPassReverse /demo/ http://xyz.my.other.ip/demo/

    ProxyPass /streams.xml http://xyz.my.other.ip/streams.xml
    ProxyPassReverse /streams.html http://xyz.my.other.ip/streams.html

    ProxyPass /testjava.html http://xyz.my.other.ip/testjava.html
    ProxyPassReverse /testjava.html http://xyz.my.other.ip/testjava.html

    ProxyPass /myngleapi/ http://xyz.my.other.ip/myngleapi/
    ProxyPassReverse /myngleapi/ http://xyz.my.other.ip/myngleapi/

    ProxyPass /myngleapi http://xyz.my.other.ip/myngleapi
    ProxyPassReverse /myngleapi http://xyz.my.other.ip/myngleapi

    ProxyPass /help.html http://xyz.my.other.ip/help.html
    ProxyPassReverse /help.html http://xyz.my.other.ip/help.html

    ProxyPass /call.php http://www.source/mynglevline/call.php
    ProxyPassReverse /call.php http://www.source/mynglevline/call.php

</VirtualHost>
<VirtualHost *:80>
    ServerName subdomain4.my.domain
    DocumentRoot "web_root/subdomain3/source/admin"
    ServerAdmin postmaster@dummy-host2.localhost
    ErrorLog "logs/subdomain3-admin-error.log"
    CustomLog "logs/subdomain3-admin-access.log" combined

</VirtualHost>
<VirtualHost *:80>
    ServerName subdomain5.my.domain
    DocumentRoot "web_root/subdomain5/source/www"
    ServerAdmin postmaster@dummy-host2.localhost
    ErrorLog "logs/release-error.log"
    CustomLog "logs/release-access.log" combined

    #turn on proxy

    ProxyPreserveHost On
    ProxyRequests On

    ProxyPass /classroom1 http://xyz.my.other.ip/classroom1
    ProxyPassReverse /classroom1 http://xyz.my.other.ip/classroom1

    ProxyPass /bigbluebutton/ http://xyz.my.other.ip/bigbluebutton/
    ProxyPassReverse /bigbluebutton/ http://xyz.my.other.ip/bigbluebutton/

    ProxyPass /client/ http://xyz.my.other.ip/client/
    ProxyPassReverse /client/ http://xyz.my.other.ip/client/

    ProxyPass /bbb http://xyz.my.other.ip/
    ProxyPassReverse /bbb http://xyz.my.other.ip/

    ProxyPass /demo/ http://xyz.my.other.ip/demo/
    ProxyPassReverse /demo/ http://xyz.my.other.ip/demo/

    ProxyPass /streams.xml http://xyz.my.other.ip/streams.xml
    ProxyPassReverse /streams.html http://xyz.my.other.ip/streams.html

    ProxyPass /testjava.html http://xyz.my.other.ip/testjava.html
    ProxyPassReverse /testjava.html http://xyz.my.other.ip/testjava.html

    ProxyPass /myngleapi/ http://xyz.my.other.ip/myngleapi/
    ProxyPassReverse /myngleapi/ http://xyz.my.other.ip/myngleapi/

    ProxyPass /myngleapi http://xyz.my.other.ip/myngleapi
    ProxyPassReverse /myngleapi http://xyz.my.other.ip/myngleapi

    ProxyPass /help.html http://xyz.my.other.ip/help.html
    ProxyPassReverse /help.html http://xyz.my.other.ip/help.html

    ProxyPass /call.php http://www.source/mynglevline/call.php
    ProxyPassReverse /call.php http://www.source/mynglevline/call.php

</VirtualHost>
<VirtualHost *:80>
    ServerName subdomain6.my.domain
    DocumentRoot "web_root/subdomain5/source/admin"
    ServerAdmin postmaster@dummy-host2.localhost
    ErrorLog "logs/subdomain5-admin-error.log"
    CustomLog "logs/subdomain5-admin-access.log" combined

</VirtualHost>

A:
ProxyRequests On

This is your problem, quote from  Apache's mod_proxy document:

Warning
Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large.


text:
Q: Is the image of a map $S^1 \to X$ necessarily a loop?
Show that if $X$ is a topological space and $\pi_1(X, x_0) = 0$, then every map $S^1 \to X$ is null-homotopic.

I think I've boiled this down to the fact that I would need to be sure that if $f : S^1 \to X$ is any map, then $f(S^1)$ is a loop in $X$.
Let $f : S^1 \to X$ be a map such that $x_0 \in f(S^1)$. Now if the image of $f$ is a loop, then $[f] \in \pi_1(X, x_0)$ and since $\pi_1(X,x_0) = 0$ this implies that $f$ is homotopic to $x_0$ i.e. null-homotopic.
I think I need to make these few assumptions here that $f(S^1)$ is a loop and that $x_0 \in f(S^1)$? Are these necessary?

A: You need $X$ to be path-connected. Otherwise, Let's say $X=S^1\sqcup\{x_0\}$, i.e., $x_0\notin S^1$. Suppose there is no path from $x_0$ to any point of $S^1$. Then the only loop based at $x_0$ is the constant loop, so $\pi_1(X,x_0)=0$. With path-connectedness, we can talk about loops regardless of base points.
Let $f$ be any map from $S^1$ to $X$ (comment: in algebraic topology, we assume all maps are continuous; otherwise it is not interesting). Then $f$ maps $S^1$ to a loop on $X$, which is a trivial loop. it means that there is a path homotopy between $f(S^1)$ and the constant loop, by definition, it means that there is a path homotopy between $f(S^1)$ and a point. Thus $f$ is nullhomotopic.
Indeed, if $X$ is path-connected and has a trivial fundamental group, it is called simply-connected. This statement is equivalent to Proposition 1.6 in Hatcher's book.
And nullhomotopy of any map from $S^1$ to $X$ means that any loop on $X$ is a trivial loop, by the same statement, this is a characterization of simply-connectedness.


text:
Q: moderncv user variable in section How can I use a variable (e.g. a first name) in \cvitem?
\firstname{Firstname}
  \begin{document}
  \makecvtitle % Print the CV title
  \section{Personal Data}
  \cvitem{}{\firstname}

A: If you look at \meaning\firstname, you'll see that it just means
\def\@firstname{#1}

To get the functionality you want, you'll have to say
\firstname{Firstname}
  \begin{document}
  \makecvtitle % Print the CV title
  \section{Personal Data}
  \cvitem{}{\makeatletter\@firstname\makeatother}

(Remembering, of course, that you can make a macro to do the dirty work for you if you plan to do this a lot: \makeatletter\newcommand\myfirstname{\@firstname}\makeatother.)


text:
Q: compiling two C files using the terminal, one file includes a.h and two file include c.h I'm trying to compile two C files using the terminal. File one.c includes a.h and file two.c includes c.h but I'm receiving the following errors
one.c fatal error: a.h No such file or directory
two.c fatal error: c.h No such file or directory

I think the issue is with the command I'm using to run gcc. What's the right command to compile these two files together?
one.c starts with
#include "a.h"
#include "b.h"

two.c starts with
#include "c.h"
#include "b.h"

A: Just add the quotes like this #include "a.h" and make sure that all the header files .h are located in your include path


text:
Q: QGIS QtQuick integration? I would like to use QGIS with QtQuick. I can use QGIS with QtWidget with the libs that I downloaded from OSGeo4W but there is no qtquick libraries in there. In QGIS's website there is a demo with QtQuick but since I don't have the qtquick libraries I can't use that code. Where can I found qgis quick libraries?
In demo's profile they write this but I don't have qgis_guick lib
  QGIS_PREFIX_PATH = $${QGIS_INSTALL_PATH}
  QGIS_LIB_DIR = $${QGIS_INSTALL_PATH}/lib
  QGIS_INCLUDE_DIR = $${QGIS_INSTALL_PATH}/include
  QGIS_QML_DIR = $${QGIS_INSTALL_PATH}/qml
  QT_LIBS_DIR = $$dirname(QMAKE_QMAKE)/../lib

  INCLUDEPATH += \
    $${QGIS_INCLUDE_DIR}/qgis \
    $${QGIS_INCLUDE_DIR}

  LIBS += -L$${QGIS_LIB_DIR}
  LIBS += -lqgis_core -lqgis_quick

A: Base on QGIS Documentation ( https://qgis.org/api/qgsquick.html) it is neccessary to buile the library.
Building the library
The QGIS Quick library is not built by default because QGIS application currently does not use it. In order to build the library please make sure that WITH_QUICK variable in CMake configuration is set to ON.
It is recommended to build with CMake variable ENABLE_TESTS set to ON because that will also build a small example application that uses Qt Quick components. In the generated project you should see target "qgis_quickapp".
The built QML plugin is installed to a dedicated directory - see QgsApplication::qmlImportPath(). When using QGIS Quick components, it is necessary to either use QQmlEngine::addImportPath() to add that directory or to specify QML2_IMPORT_PATH environment variable.


text:
Q: SmartGWT - ordered view of values in comboboxitem I'm using Java7 and SmartGWT 3.1. Having the following code I encountered that the values are not displayed in the order I put them into.
LinkedHashMap<Integer, String> insertOrdered = new LinkedHashMap<Integer, String>();
for (MyEnum me : MyEnum.values()) {
  insertOrdered.put(me.getId(), me.getMyName());
}
ComboBoxItem cbi = new ComboBoxItem();
cbi.setValueMap(insertOrdered);

the ID's are not ordered (neither ascending nor descending). But, this shouldn't matter, because if I'm not totally mistaken, LinkedHashMap orders with respect to insertion. Just to be sure I checked the JavaDoc again (http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html) and that's the case.
Why is the ComboBoxItem ignoring my ordering? Is there any other way to achieve ordering in a ComboBoxItem?

A: The Javadoc of LinkedHashMap states:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Even though, I would agree that the order that they appear should be the order that they are declared in the enum as stated by JLS. If you are having problems with LinkedHashMap ans you really want to ensure this order, perhaps you might want to try setting the values with the variable argument list method. You will essentially change it to an array, it might be undesired but it could potentially solve your issue.
List<String> list = new ArrayList<String>();
for(MyEnum me: MyEnum.values()){
    list.add(me.getMyName());
 }

 ComboBoxItem cbi = new ComboBoxItem();
 cbi.setValueMap(list.toArray(new String[list.size()]));

A: I suggest you check if you are setting setSortField somewhere in your code. If you set the following:
 setSortField("null");

on the ComboBoxItem it will remove any sorting you may have and will keep the sort order of the backing LinkedHashMap.

A: Use this operation the ComboxItem
ComboxItem cb = new ComboxItem();
cb.setSortField(SortDirection.ASCENDING.compareTo(SortDirection.ASCENDING));


text:
Q: It it possible to take a snapshot for Java Profilers with Java? I would like to periodically take a snapshot of my runtime (the .snapshot files used on profilers for Java, like YourKit, JProfiler, VisualVM, etc), is possible to take a snapshot by calling a method or something else? With Java, running on the same jvm?

A: I would suggest periodically running a Java Flight Recorder.
What is it? It is a profiling tool similar to the ones you already mentioned, it captures all the usual data.
How to use it? Here is a short description on how to start it up. Be careful that the application you want to profile needs these extra JVM params:
java -XX:+UnlockCommercialFeatures -XX:+FlightRecorder

And finally for a periodic scheduling you need a command that you can use from crontab. For that you can use the example command from the previous link:
jcmd 5368 JFR.start duration=60s filename=myrecording.jfr

Where "5368" is the PID of your profiled application and the rest is self-explanatory.

A: Each profiler will have a different mechanism for periodically saving snapshots.
For JProfiler, use a "Timer" trigger with a "Save snapshot" action. If you want to record data for a limited time just before saving the snapshot, add the following sequence of trigger actions:

*

*"Start recording" (with the desired recording types selected)

*"Sleep" (for the desired amount of time)

*"Stop recording"

*"Save snapshot" (with "add unique number to file name" selected)

If you would rather like to control recording and saving snapshots programmatically from the same JVM, use the Controller API like this:
Controller.startCPURecording(true);
Thread.sleep(10000);
Controller.saveSnapshot(new File("snapshot.jps"));