Q: DJANGO importing fields to model from another model I have the following Models and I'm try to get the vector in Especie.zonas to be a field in the model Zona.
i.e. Especie.zonas is a vector of Zonas (model Zona) and I want it to have a OneToOne relationship with the model EspecieZona
Models.py
class Zona(models.Model):
    codigo          = models.CharField(max_length=120)
    area            = models.CharField(max_length=120)
    especies        = models.ManyToManyField("Especie", blank=True)

        def __str__(self):
            return self.codigo
        def get_especies(self):
            return self.especies.all().values_list('nome', flat=True)

    class Especie(models.Model):
        nome            = models.CharField(max_length=120)
        nome_latino     = models.CharField(max_length=120)
        data_insercao   = models.DateTimeField(auto_now_add=True)
        actualizacao    = models.DateTimeField(auto_now=True)
        zonas           = models.ManyToManyField("Zona",blank=True )

        def get_zonas(self):
            return self.zonas.all().values_list('codigo', flat=True)
        def __str__(self):
            return self.nome

    class EspecieZona(models.Model):
        idEspecie          = models.OneToOneField("Especie")
        here_is_my_problem = models.Especie.zonas()
        idZona             = models.OneToOneField("Especie.zonas")
        fechado            = models.BooleanField()
        def __str__(self):
            return str(self.idEspecie)+' em '+str(self.idZona)

Thanks in advance!

A: I'm not entirely sure of your intent. Relationships are to be established between models (so you can't OneToOne to a class' field). As I understand EspecieZona relates one Especie instance to one Zona instance, but you also would like to easily get all the Zona instances related to some Especie instance that you are accessing through EspecieZona.
It seems to me like you should drop that here_is_my_problem field entirely and use foreign keys to Especie and Zona in EspecieZona, instead of OneToOne. With the foreign keys you can use a ManyToMany field from Zona to Especie (or vice versa. you have to declare the MtM field in only one side of the relationship, whichever makes more sense to you) and use EspecieZona as a 'through' field for that relationship (probably with a unique_together constraint for Especie and Zona). That way you can establish a relationship like this:
"Each species can be on multiple zones, and each zone can have multiple species (described by the MtM relationship). Additionally, for each zone and species found in them, each species might or not have been recorded(?) in that zone (described in the 'through' model, EspecieZona, thou not sure I understand the meaning of fechado here. In any case, a 'through' model lets you describe whatever details about the relationship between two models)".
Then, in order to retrieve Especies.zonas from an instance of EspecieZona you can do someSpecificEspecieZona.especie.zonas.all() (assuming zonas
 is declared as a MtM field in Especie), which would get you all the zones that are related to that species (as I understand your models)
I suggest reading through the documentation of relationship fields https://docs.djangoproject.com/en/1.11/ref/models/fields/#module-django.db.models.fields.related so you get the details about how it all works, like how to use a  ManyToManyField.through, and perhaps about reverse relationships if you need them.
(also, maybe that was just a mistake when copypasting your code here, but the indentation looks wrong. Different models should be at the same level of indentation there)


Q: How to run bash file for (different directory) as input automatically I have a bash file which takes 5 inputs.
Input1 = file1
Input2 = file2
Input3 = directory1
Input4 = func
Input5 = 50

input 4 and 5 are always the same, never change.
file1 and file 2 are located inside directory1
directory1 is located inside a code directory
/code/directory1/file1
/code/directory1/file2

and there are many directories with the same structure directory(1-70) inside the code folder
/code/directory1/*
/code/directory2/*
/code/directory3/*
...
/code/directory70/*

In order to run the bash file, I have to run the command from terminal 70 times :<
Is there a way to automatically run all these folders at once?
UPDATE: the directory(1-7) each one has a different name e.g bug1, test, 4-A and so on. Even the files are different e.g. bug1.c hash.c
/code/bug1/bug1.c
code/bug1/hash.c

A: Try this:
for dirs in $(ls -F /code | grep '/')
do
    eval files=( "$(ls -1 ${dirs})" )
    <ShellScript>.sh "${dirs}${files[0]}" "${dirs}${files[1]}" "${dirs%/}" func 50
done


Q: Generic template template parameters Fed up with "uniform initialisation" not being very uniform, I decided to write a generic construct() wrapper which uses aggregate initialisation if a type is an aggregate, and direct initialisation otherwise:
template <class T, class... Args,
          std::enable_if_t<std::is_aggregate_v<T>, int> = 0>
constexpr auto construct(Args&&... args)
    -> decltype(T{std::forward<Args>(args)...})
{
    return T{std::forward<Args>(args)...};
}

template <class T, class... Args>
constexpr auto construct(Args&&... args)
   -> decltype(T(std::forward<Args>(args)...))
{
    return T(std::forward<Args>(args)...);
}

This works well enough:
template <class T, class U>
struct my_pair { T first; U second; };

auto p = construct<my_pair<int, float>>(1, 3.14f);
auto v = construct<std::vector<int>>(5, 0);

I'd like to extend this to use template argument deduction for constructors. So I added another pair of overloads:
template <template <class...> class T, // <-- (1)
          class... Args,
          class A = decltype(T{std::declval<Args>()...}),
          std::enable_if_t<std::is_aggregate_v<A>, int> = 0>
constexpr auto construct(Args&&... args)
    -> decltype(T{std::forward<Args>(args)...})
{
     return T{std::forward<Args>(args)...};
}

template <template <class...> class T, // <-- (1)
          class... Args>
constexpr auto construct(Args&&... args)
    -> decltype(T(std::forward<Args>(args)...))
{
    return T(std::forward<Args>(args)...);
}

Perhaps surprisingly (at least to me), this works for simple cases:
// deduction guide for my_pair
template <class T, class U> my_pair(T&&, U&&) -> my_pair<T, U>;

auto p = construct<my_pair>(1, 3.14f); // my_pair<int, float>
auto v = construct<std::vector>(5, 0); // vector of 5 ints

Unfortunately however this fails when trying to call
auto a = construct<std::array>(1, 2, 3); // No matching call to construct()

because std::array has a non-type template parameter, so it doesn't match the template <class...> class T template template parameter at (1).
So my question is, is there a way to formulate the parameter at (1) such that it can accept any class template name, regardless of the kind (type or non-type) of its template parameters?

A: Unfortunately, there is no proper way of doing this without code repetition. The newly added "auto as template parameter" in C++17 only supports non-type template parameters.
The only way I can think this could work is by using a code generator to generate a fixed amount of permutations of auto and class. E.g.
template <
    template <class, auto...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <class, auto, class...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <auto, class, auto...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <auto, class, auto, class...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <auto, class, auto, class, auto...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

// and so on...

live example on wandbox
Sounds like you have a good idea for a proposal...


Q: Implement messaging into website I have a website where I have registered users in the system. When user logs into his profile I have section "Messages".
What is the best way to implement messaging into the website? I don't want to use plug-ins with live chat because of the pop-up boxes. I just want when one user will send a message to another, to have notification for new message, and to be able to start conversation between two sides in the real time.
I have an idea how to implement this with ajax, but I don't think it's a good idea to check for a new messages every a few seconds. Is there some better way to listening for a new messages and for implementing messaging feature in the site?

A: A websocket is what you are looking for; however it is subject to some browser limitations and libraries may fall back to polling with Ajax if the browser doesn't support it.
Here is some reading for you so you can ask a more specific question in the future:

*

*http://en.wikipedia.org/wiki/WebSocket (general info)

*http://socket.io/ (NodeJS and browser client library)


Q: How does shell expands *.c? I encounter a question while I am reading a textbook - Unix System Programming

How big is the argument array passed as the second argument to execvp
  when you execute execcmd of Program 3.5 with the following command
  line?
execcmd ls -l *.c

Answer: The answer depends on the number of .c files in the current
  directory because the shell expands *.c before passing the command
  line to execcmd.

Program 3.5:
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "restart.h"
int main(int argc, char *argv[]) {
   pid_t childpid;
   if (argc < 2){     /* check for valid number of command-line arguments */
      fprintf (stderr, "Usage: %s command arg1 arg2 ...\n", argv[0]);
      return 1;
   }
   childpid = fork();
   if (childpid == -1) {
      perror("Failed to fork");
      return 1;
   }
   if (childpid == 0) {
      execvp(argv[1], &argv[1]);
      perror("Child failed to execvp the command");
      return 1;
   }
   if (childpid != r_wait(NULL)) {
      perror("Parent failed to wait");
      return 1;
   }
   return 0;
}

Why is the size of argument array passed depending on the number of .c files in the current directory? Isn't it the argument array just something like
argv[0] = "execcmd";
argv[1] = "ls";
argv[2] = "-l";
argv[3] = "*.c";
argv[4] = NULL;

Update: Find a link explains pretty well about the shell expansion. May useful for someone who see this post later also do not understand shell expansion.
Description about shell expansion

A: No, because the shell does the wild card expansion.
It finds files in the directory that match the expression, so for instance you can use "echo *.c" to discover what the shell would match.  Then it lists out, every filename matching *.c on the exec call or if none *.c which is likely to result in an error message about file not found.
It is more powerful that the shell does the expansion, the same file wildcarding is immediately available for all programs, like cat, echo, ls, cc.


Q: Nested Params in Spring Controllers is asking for Neting in JSP file Path. How to deal with that? So this is my controller code :
`
package org.inventorymanagement.controller;

import org.inventorymanagement.databaseservice.BorrowBookDatabaseService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BorrowPageController {

    @RequestMapping(value = "/borrow/{bookName}/{issuerName}", method = RequestMethod.GET)
    public ModelAndView searchForBookName(@PathVariable("bookName") String bookName, @PathVariable("issuerName") String issuerName) {
        ModelAndView mav = new ModelAndView("borrow.jsp");
        String rs = (String) new BorrowBookDatabaseService().borrowBookFromBookTable(bookName, issuerName);

        return mav;
    }

}

Here is the error which i am seeing on my webpage:
JSP file [/borrow/ABC/borrow.jsp] not found
ABC is my bookName.
Any suggestions how can i overcome it ?
I tried to change the path of jsp inside ABC folder and it works fine. But since ABC is generic how many folders i will made ?


Q: Advantages of Maven Tycho over Eclipse PDE Tools for exporting RCP In the light of some recent issues regarding JavaFX and exporting an Eclipse RCP application, I'm considering abandoning the Eclipse PDE exporter, and switching to a Tycho build.

*

*Which approach is simpler, and which is over-complicated? Do I need to constantly tweak the Tycho build configuration?

*Current project is already using ant scripts to build a core EAR. Should that be built with Maven to be consistent?

*I'm aware of some issues between Maven and Eclipse Plug-ins. Is there anything critical I should be worried about?
I'm in heavy R&D mode.
Also, I don't consider this to be opinion-based, rather a topic asking for strong arguments in favour of each one of these two.

A: I wouldn't say one of them is much simpler then the other. Most often Tycho is preferred since Maven is de facto an industry standard for builds. As such Maven skills are more common. This also allows you to build an RCP product like any other application using Maven.
In Maven/Tycho both the pom.xml and the OSGi manifest include dependency information so there's a bit of redundancy. The idea is to have one of these files be the master version. If you choose OSGi files to be master then resulting approach is called manifest-first. Choose otherwise and you end up with POM-first.
I'm using manifest-first and my POM files for plugins look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>aerie-sdk</groupId>
      <artifactId>aerie-sdk</artifactId>
      <version>3.0.5-SNAPSHOT</version>
      <relativePath>../pom.xml</relativePath>
   </parent>
   <groupId>aerie-sdk</groupId>
   <artifactId>com.example.aerie.ui</artifactId>
   <version>2.5.5-SNAPSHOT</version>
   <packaging>eclipse-plugin</packaging>
</project>

I only need to bump versions in POM files to match the ones in manifest files.
Answers:

*

*I'd say the one you're more familiar with is simpler. If you're new to Maven but have some experience with PDE build then Maven is harder. For Maven POM-first there's a need to tweak POM files quite often. If you choose manifest-first then POMs are not modified that frequently (and changes are simpler - mostly version changes).

*You can run Ant from Maven, no need to convert.

*Not really. If you hit any bumps there's a lot of information on Eclipse community forums, stackoverflow or similar sites.

A: I'm not sure your comparison makes sense at all. The Eclipse PDE exporter is an interactive tool, and as such cannot be used for an automated build. So if you need an automated build, you will have move to something else, e.g. Tycho.
Tycho is a Maven build extension which aims to make it easy to set up an automated build for projects developed with the Eclipse PDE. It re-uses the configuration files that you already have (MANIFEST.MF, feature.xml, *.product), so the additional configuration files needed for Tycho (pom.xml) are pretty minimal and rarely need to be updated.
The only piece of information which is redundant in the pom.xml file is the artifact version. To support you when updating artifact versions, there is a command-line tool: the tycho-versions-plugin.


Q: UserForm ComboBox with searchable list to not select first item with keyDown Background
I have a UserForm with a ComboBox (ComboBox1) that includes a searchable list (thanks to the code). However, when I use the down button, it just selects the first item and gets rid of the rest of the list that was there first (like as if basically puts the first item as the searched name).
I have found a very similar question on stack overflow but the solution did not fully work for me.
Here is the link: How use the combobox keydown event without selecting the listed item
The code that I have for my UserForm is below:
Dim a()

Private Sub CommandButton2_Click()

End Sub

Private Sub UserForm_Initialize()
  a = [Liste].Value
  Me.ComboBox1.List = a
End Sub
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Abort As Boolean
    Select Case KeyCode
        Case 38  'Up
            If ComboBox1.ListIndex <= 0 Then KeyCode = 0 'ignore "Up" press if already on the first selection, or if not on a selection
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection past the first entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox.ListIndex - 1
            End If
            Me.ComboBox1.DropDown
        Case 40 'Down
            If ComboBox1.ListIndex = ComboBox1.ListCount - 1 Then KeyCode = 0
        ' This method was from the discussion I linked, prevents "falling off the bottom of the list"
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection before the last entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox1.ListIndex + 1
            End If
            Me.ComboBox1.DropDown
    End Select
    Abort = False
End Sub

Private Sub ComboBox1_Change()
If Abort Then Exit Sub ' Stop Event code if flag set
    Abort = True
    ' sets the flag until finished with commands to prevent changes made by code triggering the event multiple times
Set d1 = CreateObject("Scripting.Dictionary")
    tmp = UCase(Me.ComboBox1) & "*"
    For Each c In a
        If UCase(c) Like tmp Then d1(c) = ""
    Next c
    Me.ComboBox1.List = d1.keys
    Me.ComboBox1.DropDown
Abort = False
End Sub

Private Sub CommandButton1_Click()
  ActiveCell = Me.ComboBox1
  Unload Me
End Sub

Private Sub cmdClose_Click()
  Unload Me
End Sub

The particular section that is apparently trying to stop the comboBox from selecting the first item is this:
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Abort As Boolean
    Select Case KeyCode
        Case 38  'Up
            If ComboBox1.ListIndex <= 0 Then KeyCode = 0 'ignore "Up" press if already on the first selection, or if not on a selection
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection past the first entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox.ListIndex - 1
            End If
            Me.ComboBox1.DropDown
        Case 40 'Down
            If ComboBox1.ListIndex = ComboBox1.ListCount - 1 Then KeyCode = 0
        ' This method was from the discussion I linked, prevents "falling off the bottom of the list"
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection before the last entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox1.ListIndex + 1
            End If
            Me.ComboBox1.DropDown
    End Select
    Abort = False
End Sub

However, when I enter something (Let's say I enter "App" to find "Applesauce" and the dropdown list shows both "Apple" and "Applesauce") and click the down button, it just goes to the first item and does not move anymore. The list does not disappear but it just gets stuck on the first item.
Does anyone have any idea what I need to change in my code to make it work? (Or any other ideas on how to make it work in general)?
GIF for clarification:
KeyDown not moving beyong first item


Q: How to compute this double integral in r? I'm wanting to compute an integral of the following density function :

Using the packages "rmutil" and "psych" in R , i tried :
X=c(8,1,2,3)

Y=c(5,2,4,6)

correlation=cov(X,Y)/(SD(X)*SD(Y))

bvtnorm <- function(x, y, mu_x = mean(X), mu_y = mean(Y), sigma_x = SD(X), sigma_y = SD(Y), rho = correlation) {
  force(x)
  force(y)
  function(x, y)
    1 / (2 * pi * sigma_x * sigma_y * sqrt(1 - rho ^ 2)) *
    exp(- 1 / (2 * (1 - rho ^ 2)) * ((x - mu_x) / sigma_x) ^ 2 +
          ((y - mu_y) / sigma_y) ^ 2 - 2 * rho * (x - mu_x) * (y - mu_y) /
          (sigma_x * sigma_y))
}

f2 <- bvtnorm(x, y)

print("sum_double_integral :")

integral_1=int2(f2, a=c(-Inf,-Inf), b=c(Inf,Inf)) # should normaly give 1

print(integral_1)  # gives Nan

The problem :
This integral should give 1 , but it gives Nan ??
I don't know how can i fix the problem , i tried to force() x and y variables without success.

A: You were missing a pair of parentheses. The corrected code looks like:
library(rmutil)
X=c(8,1,2,3)

Y=c(5,2,4,6)

correlation=cor(X,Y)

bvtnorm <- function(x, y, mu_x = mean(X), mu_y = mean(Y), sigma_x = sd(X), sigma_y = sd(Y), rho = correlation) {

  function(x, y)
    1 / (2 * pi * sigma_x * sigma_y * sqrt(1 - rho ^ 2)) *
    exp(- 1 / (2 * (1 - rho ^ 2)) * (((x - mu_x) / sigma_x) ^ 2 +
          ((y - mu_y) / sigma_y) ^ 2 - 2 * rho * (x - mu_x) * (y - mu_y) /
          (sigma_x * sigma_y)))
}

f2 <- bvtnorm(x, y)

print("sum_double_integral :")

integral_1=int2(f2, a=c(-Inf,-Inf), b=c(Inf,Inf)) # should normaly give 1

print(integral_1)  # prints 1.000047

This was hard to spot. From a debugging point of view, I found it helpful to first integrate over a finite domain. Trying it with things like first [-1,1] and then [-2,2] (on both axes) showed that the integrals were blowing up rather than converging. After that, I looked at the grouping even more carefully.
I also cleaned up the code a bit. I dropped SD in favor of sd since I don't see the motivation in importing the package psych just to make the code less readable (less flippantly, dropping psych from the question makes it easier for others to reproduce. There is no good reason to include a package which isn't be used in any essential way). I also dropped the force() which was doing nothing and used the built-in function cor for calculating the correlation.


Q: Centering MenuItems in second ActionBar? So I am trying to center my icons like this image from Google Developer:

My second row is actually just below the top row (which is also actionbar tabs without a title or icon enabled in the activity). So, right now, as I've added in my three buttons (just text, no icons) they stack on the right side of the bar, and I can't seem to find anything in the docs about centering. Any ideas?
Relevant code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_demos"
          android:title="Chart +/-"
          android:showAsAction="always|withText" />
    <item android:id="@+id/menu_data"
          android:title="Datas"
          android:showAsAction="always|withText" />
    <item android:id="@+id/menu_reset"
          android:title="Reset"
          android:showAsAction="always|withText" />
</menu>

manifest line:
<activity android:name="polling.Chart" android:label="Chart"
        android:icon="@drawable/chart512"     android:windowSoftInputMode="stateHidden"/>

Main Activity:
    bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    bar.setDisplayShowTitleEnabled(false);
    bar.setDisplayShowHomeEnabled(false);

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.chartsmenu, menu);
    return true;
}

A: Use the split action bar option. All items which does not fix in the top action bar will be shown in the second action bar at the bottom of your screen. The remaining items will be centered within the second action bar.
protected void onCreate(final Bundle savedInstanceState) {
    getSherlock().setUiOptions(ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW);
    super.onCreate(savedInstanceState);
}


Q: Running an interactive shellscript using java I am writing a javacode to call a interactive shellscript and using process builder for calling shellscript. I know that to pass parameters to this shell script i have to take its inputstream to check it's output and need to use output stream to pass command to it. My question is that how would I know using Input Stream that it's  prompting for entering values ?
My code :
  ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh","--ip="+formobj.getUpFile().getFileName(),"--seqs="+seqs);

        script_exec = pb2.start();

                OutputStream in = script_exec.getOutputStream();

                InputStreamReader rd=new InputStreamReader(script_exec.getInputStream());

                pb2.redirectError();

                BufferedReader reader1 =new BufferedReader(new InputStreamReader(script_exec.getInputStream()));

                StringBuffer out=new StringBuffer();

                String output_line = "";

                  while ((output_line = reader1.readLine())!= null)
                  {
                           out=out.append(output_line+"/n");
                           System.out.println("val of output_line"+output_line);

                           //---> i need code here to check that whether script is prompting for taking input ,so i can pass it values using output stream

                  }

Is there any  way to know directly that script is waiting for an input from user?

A: Read the process output stream and check for the input prompt, if you know the input prompt, then put the values to process inupt stream.
Otherwise you have no way to check.
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
BufferedReader b1 = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter w1 = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String line = "";
String outp = "";
while ((line = b1.readLine()) != null) {
  if (line.equals("PLEASE INPUT THE VALUE:")) {
     // output to stream
     w1.write("42");
  }
  outp += line + "\n";
}

...

UPD: for your code it should be something like that
    ProcessBuilder pb2=new ProcessBuilder("/home/ahijeet/sample1.sh","--ip="+formobj.getUpFile().getFileName(),"--seqs="+seqs);

    script_exec = pb2.start();

            OutputStream in = script_exec.getOutputStream();

            InputStreamReader rd=new InputStreamReader(script_exec.getInputStream());

            pb2.redirectError();

            BufferedReader reader1 =new BufferedReader(new InputStreamReader(script_exec.getInputStream()));

            StringBuffer out=new StringBuffer();

            String output_line = "";

              while ((output_line = reader1.readLine())!= null)
              {
                       out=out.append(output_line+"/n");
                       System.out.println("val of output_line"+output_line);

                       //---> i need code here to check that whether script is prompting for taking input ,so i can pass it values using output stream
                       if (output_line.equals("PLEASE INPUT THE VALUE:")) {
                           // output to stream
                           in.write("42");
                       }

              }


Q: How can I save a variable from a database and use it in C#? I am changing a program and I need some help because I don't know C#. I change things with:
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=385";
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();

There is a case where I need to find an ID, store it and then use it again. So I use select
 OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
 OleDbDataReader reader = cmd.ExecuteReader();
 if (reader.HasRows)
 {
   reader.Read();
   var result = reader.GetInt32(0);
 }

 strSQL = "UPDATE materials SET ";
 strSQL = strSQL + "Dscr = 'concrete', ";
 strSQL = strSQL + "width=50 ";
 strSQL = strSQL + " WHERE ID=result";
 objCmd = new OleDbCommand(strSQL, db_def.conn);
 objCmd.ExecuteNonQuery();

But I get an error:

No value given for one or more required parameters.

A: Although your code that you're working on is less than desirable, I'll just provide the fix you require at this point:
Change your code to :
 OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
 OleDbDataReader reader = cmd.ExecuteReader();

int result=0;

 if (reader.HasRows)
 {
   reader.Read();
   result = reader.GetInt32(0);
 }

 strSQL = "UPDATE materials SET ";
 strSQL = strSQL + "Dscr = 'concrete', ";
 strSQL = strSQL + "width=50 ";
 strSQL = strSQL + " WHERE ID=" + result;
 objCmd = new OleDbCommand(strSQL, db_def.conn);
 objCmd.ExecuteNonQuery();

You need to provide the value of the result variable outside the SQL string - the database will not know the value of 'result' in its own context.
EDIT: the result variable was declared within the if statement, therefore not available further down for assigning.

A: you can try this and tell  me if it works
     OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
     OleDbDataReader reader = cmd.ExecuteReader();
    int result=-1 ;
     if (reader.HasRows)
     {
       reader.Read();
       result = reader.GetInt32(0);
     }
if (result != -1)
{
     strSQL = "UPDATE materials SET ";
     strSQL = strSQL + "Dscr = 'concrete', ";
     strSQL = strSQL + "width=50 ";
     strSQL = strSQL + " WHERE ID="+result;
     objCmd = new OleDbCommand(strSQL, db_def.conn);
     objCmd.ExecuteNonQuery();
}


Q: Unable to Import after Pip Install Ive just installed a package via pip,
  Cloning https://github.com/felix001/commontools.git to /tmp/pip-LMwfnO-build
Installing collected packages: commontools
  Running setup.py install for commontools
Successfully installed commontools-1.0

When I try to import commontools it doesnt import.
The path looks ok though,
>>> import pprint
>>> import sys
>>> pprint.pprint(sys.path)
['',
 '/Library/Python/2.7/site-packages/pip-7.1.2-py2.7.egg',
 '/Users/felix001',
 '/usr/local/lib/python2.7/site-packages',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages',
 '/Library/Python/2.7/site-packages']
>>>
MacBook-Pro:~ felix001$ ls -l /Library/Python/2.7/site-packages
total 392
-rw-r--r--   1 root  wheel    119  9 Sep  2014 README
drwxr-xr-x   7 root  wheel    238 18 Dec 21:39 commontools-1.0-py2.7.egg-info
-rw-r--r--   1 root  wheel    207  3 Nov 20:20 easy-install.pth
drwxr-xr-x   4 root  wheel    136  3 Nov 20:20 pip-7.1.2-py2.7.egg
drwxr-xr-x  60 root  wheel   2040 23 Oct  2014 scapy
-rw-r--r--   1 root  wheel    261 18 Oct  2014 scapy-2.1.0-py2.7.egg-info
drwxr-xr-x   7 root  wheel    238 11 Dec 22:18 threader-1.0-py2.7.egg-info
drwxr-xr-x   6 root  wheel    204 20 Jul 21:49 vboxapi
-rw-r--r--   1 root  wheel    241 20 Jul 21:49 vboxapi-1.0-py2.7.egg-info
drwxr-xr-x  10 root  wheel    340  3 Nov 20:21 virtualenv-13.1.2.dist-info
-rw-r--r--   1 root  wheel  99421  3 Nov 20:21 virtualenv.py
-rw-r--r--   1 root  wheel  83209  3 Nov 20:21 virtualenv.pyc
drwxr-xr-x   8 root  wheel    272  3 Nov 20:21 virtualenv_support

Here is the package details.
MacBook-Pro:~ felix001$ pip show commontools
---
Metadata-Version: 1.0
Name: commontools
Version: 1.0
Summary: commontools
Home-page: UNKNOWN
Author: ====
Author-email: ====
License: UNKNOWN
Location: /Library/Python/2.7/site-packages
Requires:

EDIT :
The error is shown below when I try to import,
MacBook-Pro:~$ which python
/usr/local/bin/python

MacBook-Pro:~$ python
Python 2.7.10 (default, Sep 23 2015, 04:34:14)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from commontools import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named commontools

EDIT2 :
So i removed all instances of python. I installed a new version using brew. Same Issue.
New Python path ,
MacBook-Pro:~ felix001$ which python
/usr/local/bin/python

Now if I install anything by pip. It works fine. But if I install my own git repos it fails (??). Heres an example of one - https://github.com/felix001/commontools
Heres an example,
MacBook-Pro:~ felix001$ pip -v install netaddr
Collecting netaddr
  Getting page https://pypi.python.org/simple/netaddr/
  1 location(s) to search for versions of netaddr:
  * https://pypi.python.org/simple/netaddr/
  Getting page https://pypi.python.org/simple/netaddr/
  Analyzing links from page https://pypi.python.org/simple/netaddr/
    Skipping link https://pypi.python.org/packages/2.4/n/netaddr/netaddr-0.3.1.win32.exe#md5=ba0615105ab8193f4115e2a5767a121c (from https://pypi.python.org/simple/netaddr/); unsupported archive format: .exe
    Skipping link https://pypi.python.org/packages/2.4/n/netaddr/netaddr-0.4.win32.exe#md5=77c28e03c14e081b3339118fad7f1bce (from https://pypi.python.org/simple/netaddr/); unsupported archive format: .exe
    Skipping link https://pypi.python.org/packages/2.4/n/netaddr/netaddr-
0.7.x/CHANGELOG (from https://pypi.python.org/simple/netaddr/); not a file
    Skipping link http://packages.python.org/netaddr/ (from https://pypi.python.org/simple/netaddr/); not a file
    Skipping link https://github.com/drkjam/netaddr/blob/rel-0.7.x/CHANGELOG (from https://pypi.python.org/simple/netaddr/); not a file
    Skipping link https://pythonhosted.org/netaddr/ (from https://pypi.python.org/simple/netaddr/); not a file
  Using version 0.7.18 (newest of versions: 0.7.18, 0.7.18, 0.7.18, 0.7.17, 0.7.17, 0.7.17, 0.7.16, 0.7.16, 0.7.16, 0.7.15, 0.7.15, 0.7.15, 0.7.14, 0.7.14, 0.7.14, 0.7.13, 0.7.13, 0.7.13, 0.7.12, 0.7.12, 0.7.11, 0.7.11, 0.7.10, 0.7.10, 0.7.3, 0.7.3, 0.7.2, 0.7.2, 0.7.1, 0.7.1, 0.7, 0.7, 0.6.4, 0.6.4, 0.6.3, 0.6.3, 0.6.2, 0.6.2, 0.6.1, 0.6.1, 0.6, 0.6, 0.5.2, 0.5.2, 0.5.1, 0.5.1, 0.5, 0.5, 0.4, 0.4, 0.3.1, 0.3.1)
  Using cached netaddr-0.7.18-py2.py3-none-any.whl
  Downloading from URL https://pypi.python.org/packages/any/n/netaddr/netaddr-0.7.18-py2.py3-none-any.whl#md5=f18d38b78469bb440560544f5559e649 (from https://pypi.python.org/simple/netaddr/)
Installing collected packages: netaddr

Successfully installed netaddr-0.7.18
Cleaning up...
MacBook-Pro:~ felix001$ python
Python 2.7.10 (default, Sep 23 2015, 04:34:14)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import netaddr
>>>
>>>
>>>
MacBook-Pro:~ felix001$ pip -vvv  install git+https://github.com/felix001/commontools
Collecting git+https://github.com/felix001/commontools
  Cloning https://github.com/felix001/commontools to /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build
  Running command git clone -q https://github.com/felix001/commontools /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build
  Running setup.py (path:/var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build/setup.py) egg_info for package from git+https://github.com/felix001/commontools
    Running command python setup.py egg_info
    running egg_info
    creating pip-egg-info/commontools.egg-info
    writing pip-egg-info/commontools.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/commontools.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/commontools.egg-info/dependency_links.txt
    writing manifest file 'pip-egg-info/commontools.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'pip-egg-info/commontools.egg-info/SOURCES.txt'
    writing manifest file 'pip-egg-info/commontools.egg-info/SOURCES.txt'
  Source in /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build has version 1.0, which satisfies requirement commontools==1.0 from git+https://github.com/felix001/commontools
Installing collected packages: commontools
  Running setup.py install for commontools
    Running command /usr/local/opt/python/bin/python2.7 -c "import setuptools, tokenize;__file__='/var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-hU9LyU-record/install-record.txt --single-version-externally-managed --compile
    running install
    running build
    running install_egg_info
    running egg_info
    creating commontools.egg-info
    writing commontools.egg-info/PKG-INFO
    writing top-level names to commontools.egg-info/top_level.txt
    writing dependency_links to commontools.egg-info/dependency_links.txt
    writing manifest file 'commontools.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'commontools.egg-info/SOURCES.txt'
    writing manifest file 'commontools.egg-info/SOURCES.txt'
    Copying commontools.egg-info to /usr/local/lib/python2.7/site-packages/commontools-1.0-py2.7.egg-info
    running install_scripts
    writing list of installed files to '/var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-hU9LyU-record/install-record.txt'
  Removing source in /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build
Successfully installed commontools-1.0
Cleaning up...
MacBook-Pro:~ felix001$ python
Python 2.7.10 (default, Sep 23 2015, 04:34:14)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import commontools
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named commontools
>>>

Any ideas ?

A: This is not a problem with pip; this is a problem with the commontools package.
Here is its setup.py:
from setuptools import setup

setup(
    name="commontools",
    version="1.0",
    author="xxxxxxxxxxxx",
    author_email="xxxxxxxxxxxx",
    description="commontools",
)

It does not even follow the minimal viable example for packaging or the basic use for setuptools.
TL;DR:
It is not including the source files; which is what the packages keyword for setup() does.


Q: Getting a "Unexpected field at makeError" when uploading a form My form has an input for a file (in my case an image) and for some text. When I hit the submit button, the stated error occurs. I have had the issue for two days now and I tried to understand where the problem was, but my efforts were in vain and I have decided to yield and seek assistance.
Here is my controller for the image:
// using this to generate a random name for an image
var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
    imgUrl = '';

// this is just a loop to create a 10 character random name
for(var i = 0; i < 10; i++) {
    imgUrl += possible.charAt(Math.floor(Math.random() *
              possible.length));
}

/* I saw an answer to a similar question where the correct answer author
said path will always refer to folder where the input folder resides */

var tempPath = req.file.path,
    ext = path.extname(req.file.path).toLower(),
    targetPath = './app/controller/store/' + imgUrl + ext;

// Check if image is of the correct format
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif')
{
    fs.rename(tempPath, targetPath, function(err) {
        if (err) throw err;
        res.redirect('/posts/'+ imgUrl);
    });
} else {
    fs.unlink(tempPath, function () {
        if (err) throw err;
        res.json(500, {error: 'Only image files are allowed.'});
    });

var post = new Post({
    content: req.body.content,
    author: req.user,
    filename: imgUrl + ext
});

post.save(function(err) {
    if(err) {
        return res.status(400).send({
            message: getErrorMessage(err)
        });
    } else res.json(post);
});
}

And here is the form:
<form method="post" action="/posts" enctype="multipart/form-data">
    <textarea name="content"></textarea>
    <input type="file" name="file" id="file">
    <input type="submit" value="Post">
</form>

I did the usual stuff in my configuration file:
app.use(multer({dest: './app/controller/store'}).single('photo'));

I would truly appreciate it if you steer me towards the right path, thanks in advance.

A: .single('parameter') means the input field's name is 'parameter'
In your case:
app.use(multer({dest: './app/controller/store'}).single('photo'));

You passed a 'photo' argument into single func.
Then your form should look like this, change it:
..
    ..
    <input type="file" name="photo">
    ..
..


Q: Unable to deserialize the execution context after upgrading to spring boot 2.0 for a spring cloud dataflow task I updated my spring boot (Task) application to spring boot 2.0 from 1.5. Now when I run it I get a deserializable error.
2018-10-29 15:03:00.346 ERROR 713 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:776) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at com.mediaiq.miq.batch.MiqBatchApplication.main(MiqBatchApplication.java:42) [classes!/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
Caused by: java.lang.IllegalArgumentException: Unable to deserialize the execution context
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:325) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:309) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:667) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:657) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:688) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:756) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.getExecutionContext(JdbcExecutionContextDao.java:112) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutionDependencies(SimpleJobExplorer.java:202) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutions(SimpleJobExplorer.java:83) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at com.sun.proxy.$Proxy185.getJobExecutions(Unknown Source) ~[na:na]
    at org.springframework.batch.core.JobParametersBuilder.getNextJobParameters(JobParametersBuilder.java:264) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:162) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:179) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:134) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:128) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:792) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    ... 13 common frames omitted
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id '' as a subtype of [simple type, class java.lang.Object]: no such class found
 at [Source: (ByteArrayInputStream); line: 1, column: 11] (through reference chain: java.util.HashMap["map"])
    at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.invalidTypeIdException(DeserializationContext.java:1635) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownTypeId(DeserializationContext.java:1187) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver._typeFromId(ClassNameIdResolver.java:53) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver.typeFromId(ClassNameIdResolver.java:44) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:156) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:97) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromAny(AsArrayTypeDeserializer.java:71) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla.deserializeWithType(UntypedObjectDeserializer.java:712) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:529) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:364) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3077) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:70) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:50) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:322) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]

One person had suggested that :
This error happens when the execution context of your job is serialized with version 3 (using XStream by default) and then deserialized with version 4 (using Jackson by default). So either downgrade Spring Batch to version 3 or configure your job repository to use the XStreamExecutionContextStringSerializer.
In your case, you have already defined a bean of type BatchConfigurer, so you can override the createJobRepository method and configure the XStream serializer. For example:
@Bean
BatchConfigurer configurer(@Qualifier("dataSource") DataSource dataSource, PlatformTransactionManager transactionManager) {
    return new DefaultBatchConfigurer(dataSource) {
        @Override
        protected JobRepository createJobRepository() throws Exception {
            JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
            factory.setDataSource(dataSource);
            factory.setTransactionManager(transactionManager);
            factory.setSerializer(new XStreamExecutionContextStringSerializer());
            factory.afterPropertiesSet();
            return factory.getObject();
        }
    };
}

I added the above bean to my main class but still got the error.

A: In the batch_job_execution_context table, you may have some records which are created by the spring batch version 3. While you are trying to execute new execution with spring batch version 4, it trying to compare previous records. So it trying to deserialize those older records. this is why you are getting this issue.
Spring batch version 3 records are like bellow in the batch_job_execution_context table

{"map":[{"entry":{"string":["key","value"]}}]}

Spring batch version 4 records are like bellow in the batch_job_execution_context table
{"key":"value"}

Remove all the records created by version 3. This will fix the issue.


Q: How can integrate Keycloak with kafka? I have configured 3 nodes kafka cluster. Now we want to setup security with Keycloak for kafka. Please let me know what are the ways to do the same.
Question 1: How to implement security for kafka broker to kafka broker with keycloak?
Question 2: How to implement security for kafka client to kafka broker with keycloak?
Note: We had already Keycloak setup.

A: You can configure Kafka to use AUTHBEARER which is implemented in latest kafka release , You can find more info how to configure here .
And also get more information about the feature from Kafka doc
You need to implement  org.apache.kafka.common.security.auth.AuthenticateCallbackHandler to get token from keycloak  and validate token from Keycloak.


Q: Pandas - get the mean of one column using descending N rows of another column I have this dataframe:
             team        opponent home_dummy     round     points
0     Athlético-PR       Flamengo          0        13      22.91
1     Athlético-PR    Atlético-GO          0        17       23.6
2     Athlético-PR      Fortaleza          1        20      28.58
3     Athlético-PR      Fortaleza          0         1      75.71
4     Athlético-PR          Ceará          1        14      42.22
5     Athlético-PR       Coritiba          1        10      52.91
6     Athlético-PR          Goiás          1         2      39.82
7     Athlético-PR          Goiás          0        21      65.13
8     Athlético-PR  Internacional          0        15      43.09
9     Athlético-PR         Grêmio          1        18      15.38
10    Athlético-PR          Sport          0        19      13.09
11    Athlético-PR         Santos          1        22      65.45
12    Athlético-PR         Santos          0         3      28.04
13    Athlético-PR      Palmeiras          1         4      -7.31
14    Athlético-PR      Palmeiras          0        23      11.02
15    Athlético-PR          Vasco          0         8      15.93
16    Athlético-PR     Fluminense          1         5       9.16
17    Athlético-PR          Bahia          1        12      59.78
18    Athlético-PR    Corinthians          1        16      18.22
19    Athlético-PR       Botafogo          1         9      29.35
20    Athlético-PR     Bragantino          1         7      20.07
.......

The dataframe above has another 19 teams, other than 'Athlético-PR'.

How do I group this dataframe, getting, for each team:

*

*Mean points for the last N rounds, say N=6, which would get the mean of round 23, 22, 21, 20, 19, 18.

*Mean points for the last N rounds passing 'home_dummy' as condition, which would get the mean of either rounds 23, 21, 19, 17, 15, 13 or rounds 22, 20, 18, 16, 14, 12.

ending up with:
    team           mean_total   mean_home_0   mean_home_1
 0  Athlético-PR       mean x        mean y        mean z
  ...

A: I think you can to do two separate groupby:
df = df.sort_values(['team','round'])

out = (df.groupby(['team','home_dummy']).tail(6)
         .groupby(['team','home_dummy'])['points'].mean()
         .unstack('home_dummy')
         .add_prefix('mean_home_')
      )

out['mean_total'] = df.groupby('team').tail(6).groupby('team')['points'].mean()

Output:
home_dummy    mean_home_0  mean_home_1  mean_total
team
Athlético-PR    29.806667    38.271667   33.108333

Another option is to write a udf so as to reduce the two groupby to one:
def last6mean(x):
    return x.tail(6).mean()

out = (df.groupby(['team','home_dummy'])['points']
        .apply(last6mean)
        .unstack('home_dummy')
        .add_prefix('mean_home_')
     )

out['mean_total'] = df.groupby('team')['points'].apply(last6mean)

A: You can create two dataframes for filtering for the 6 largest with groupby and then get the means and merge together:
First make sure they are numeric:
df['round'] = df['round'].astype(int)
df['points'] = df['points'].astype(float)

OR
df['round'] = pd.to_numeric(df['round'], errors='coerce')
df['points'] = pd.to_numeric(df['points'], errors='coerce')

Then, you can run the following:
df1 = (df.loc[df.index.isin(df.groupby('team')['round'].nlargest(6).reset_index().iloc[:,1]),
        ['team', 'points']].groupby('team')['points'].mean().rename('mean_total').reset_index())
df2 = (df.loc[df.index.isin(df.groupby(['team','home_dummy'])['round'].nlargest(6).reset_index().iloc[:,2]),
        ['team', 'home_dummy', 'points']].groupby(['team','home_dummy'])['points'].mean()
       .unstack(1).add_prefix('mean_home_').reset_index())
df1.merge(df2, on='team')
Out[1]:
           team  mean_total  mean_home_0  mean_home_1
0  Athlético-PR   33.108333    29.806667    38.271667

You could also create a function to make cleaner:
def f(df, cols):
    return df.loc[df.index.isin(df.groupby(cols)['round'].nlargest(6).reset_index().iloc[:, len(cols)]),
        cols + ['points']].groupby(cols)['points'].mean()

(f(df, ['team']).rename('mean_total').reset_index().merge(
    f(df, ['team', 'home_dummy']).unstack(1).add_prefix('mean_home_').reset_index()))
Out[2]:
       team  mean_total  mean_home_0  mean_home_1
0  Athlético-PR   33.108333    29.806667    38.271667

A: I know that there's already awesome answers here, but I'd just like to share one using pivot_table:
If your DataFrame looks something like this
   team  home_dummy  round  points
0     A           0      1       3
1     A           0      2       4
2     A           1      3       7
3     A           1      4       8
4     B           0      1       3
5     B           1      2       6
6     B           1      3       9
7     B           0      4      12
8     C           0      1       5
9     C           1      2       5
10    C           1      3       5
11    C           0      4       5

Then you could do something like:
N = 2
df['points'] = df['points'].astype(float)

result = df.pivot_table(index='team',
                        columns='home_dummy',
                        values='points',
                        aggfunc=lambda x: x.tail(N).mean())

result.rename({i: f"mean_home_{i}" for i in result.columns}, axis=1, inplace=True)
result.columns.name = None

result['mean_total'] = df.groupby('team').tail(N).groupby('team')['points'].mean()

Which will give you the following dataframe
      mean_home_0  mean_home_1  mean_total
team
A             3.5          7.5         5.5
B             7.5          7.5         7.5
C             5.0          5.0         5.0


Q: Problem on import a react native component I'm having a error once import a component, react native says me that the file path is wrong, but it's not!
My main component where I'm trying to import a component and my file structure:

I'm on pages/Main/index and wanna import a file from components/Header/index, I'm sure about the path, I'm I think this is because of some react native project config, something like this
(I'm a windwos user and tryed to use /index in the path too)
The error:

A: Try passing '../components/Header'
Please let me know if it works. Thanks

A: Your .'./components/Header' path is right..
In your Header component folder there is no any styles.js but you are importing in index.js which is in Header folder.. The above error is regarding path to styles.js in header folders Index.js
Read the error carefully. They have mentioned original Path and target path.
Hope you get it.


Q: Why UITableView is not getting any user interaction as it's ViewController is added to a UITabBarController as subView I'm setting a left side menu programatically to a UITabBarController. To do this I am inserting a viewController with 0 index as subView to the TabBarController. When I press menu icon first tabView move right and menu UITableView is shown but I can not interact with the UITableView where did I make wrong?

Total UITabBarController.swift file
import UIKit

class MainTabBarController: UITabBarController {

// MARK: Properties

var menuController: MenuController!
var centerController: UIViewController!
var isExpanded = false

// MARK: Initialization

override func viewDidLoad() {
    super.viewDidLoad()
    configureHomeController()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
    return .slide
}

override var prefersStatusBarHidden: Bool {
    return isExpanded
}

// MARK: Handlers

func configureHomeController() {
    let navigationController = self.viewControllers![0] as! UINavigationController
    let homeController =  navigationController.viewControllers[0] as! FirstViewController
    homeController.homeControllerDelegate = self
    centerController = homeController
}

//Configuring Side Menu Controller

func configureMenuController() {
    if menuController == nil {
        // add menu controller here
        menuController = MenuController()
        menuController.homeControllerDelegate = self
        // Add Child View Controller
        addChild(menuController)
        // Add Child View as Subview
        view.insertSubview(menuController.view, at: 0)
        // Configure Child View
        menuController.view.frame = view.bounds
        menuController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        // Notify Child View Controller
        menuController.didMove(toParent: self)
    }
}

func animateSideMenuOpeningAndClosing(shouldExpand: Bool, menuItem: MenuItem?) {
    if shouldExpand {
        // Show Menu
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            self.centerController.view.frame.origin.x = self.centerController.view.frame.width - 80
        }, completion: nil)
    } else {
        // Hide Menu
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0,options: .curveEaseInOut, animations: {
            self.centerController.view.frame.origin.x = 0
        }) { (_) in
            guard let menuItem = menuItem else {return}
            self.didSelectMenuItem(menuItem: menuItem)
        }
    }
    animateStatusBar ()
}

func didSelectMenuItem(menuItem: MenuItem) {
    switch menuItem {
    case .Dashboard:
        print("Show Dashboard")
    case .Profile:
        print("Show Profile")
    case .Notifications:
        print("Show Notifications")
    case .Contacts:
        let controller = SettingsController()
        controller.username = "YAMIN"
        present(UINavigationController(rootViewController: controller), animated: true, completion: nil)
    }
}

func animateStatusBar () {
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0,options: .curveEaseInOut, animations: {
        self.setNeedsStatusBarAppearanceUpdate()
    }, completion: nil)
}

}

extension MainTabBarController: HomeControllerDelegate {
func handleMenuToogle(forMenuItem menuItem: MenuItem?) {
    print("Pressed")
    if !isExpanded {
        configureMenuController()
    }
    isExpanded = !isExpanded
    animateSideMenuOpeningAndClosing(shouldExpand: isExpanded, menuItem: menuItem)
}

}

A: You insert subview at 0 index, so, I think there are some views which are higher in subviews hierarchy.
You can look at your subviews with "Debug View Hierarchy button"


Q: how to make invisible some layers with actionscript? I have a map and i can use on (release), on (rollover) but i can't use onload function. I want some cities will be invisible on load. My code is here with images;
Here is my city code:
on (rollOver) {              //this code is on all city.
y = new String(_name);
a = y.slice(1, 3);
_parent.rbtxt(a);
}
on (rollOut) {
_parent.rbalon(a);
}
on (release) {
_parent.rpress(a);
}

Here is my actionscript codes:
ilad="a,Adana,Adıyaman,Afyon,Ağrı";  //.. more city
ilurl="a,adana,adıyaman,afyon,ağrı"; //.. more city
passivearray="b,adana,afyon"         //must be passive this cities.

function rbtxt(a) {
var Register_1_ = a;
var Register_2_ = this;
balon._visible = true;
arbtxt = ilad.split(",");
balon.txt.text = arbtxt[Register_1_];
Register_2_[("x" + Register_1_)].play();
balon._x = Register_2_[("x" + Register_1_)]._x;
balon._y = (Register_2_[("x" + Register_1_)]._y - Register_2_[("x" + Register_1_)]._height / 2) - 25;
}

function rbalon(a) {
balon._visible = false;
this[("x" + a)].gotoAndStop(1);
 }

Should be passive array is => passivecities.
How can i make invisible somecities ?

A: At the beginning of your script, you can use
movieclipName._visible=false;
Then you modify the same property to reverse that.

A: Have you tried:
on(load){
    this._visible = false;
}


Q: c# printing through PDF drivers, print to file option will output PS instead of PDF After struggling whole day, I identified the issue but this didn't solve my problem.
On short:
I need to open a PDF, convert to BW (grayscale), search some words and insert some notes nearby found words. At a first look it seems easy but I discovered how hard PDF files are processed (having no "words" concepts and so on).
Now the first task, converting to grayscale just drove me crazy. I didn't find a working solution either commercial or free. I came up with this solution:

*

*open the PDF

*print with windows drivers, some free PDF printers

This is quite ugly since I will force the C# users to install such 3'rd party SW but.. that is fpr the moment. I tested FreePDF, CutePDF and PDFCreator. All of them are working "stand alone" as expected.
Now when I tried to print from C#, obviously, I don't want the print dialog, just select BW option and print (aka. convert)
The following code just uses a PDF library, shown for clarity only.
                Aspose.Pdf.Facades.PdfViewer viewer = new Aspose.Pdf.Facades.PdfViewer();
                viewer.BindPdf(txtPDF.Text);

                viewer.PrintAsGrayscale = true;
                //viewer.RenderingOptions = new RenderingOptions { UseNewImagingEngine = true };

                //Set attributes for printing
                //viewer.AutoResize = true;         //Print the file with adjusted size
                //viewer.AutoRotate = true;         //Print the file with adjusted rotation
                viewer.PrintPageDialog = true;   //Do not produce the page number dialog when printing

                ////PrinterJob printJob = PrinterJob.getPrinterJob();

                //Create objects for printer and page settings and PrintDocument
                System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
                System.Drawing.Printing.PageSettings pgs = new System.Drawing.Printing.PageSettings();
                //System.Drawing.Printing.PrintDocument prtdoc = new System.Drawing.Printing.PrintDocument();

                //prtdoc.PrinterSettings = ps;

                //Set printer name
                //ps.PrinterName = prtdoc.PrinterSettings.PrinterName;

                ps.PrinterName = "CutePDF Writer";
                ps.PrintToFile = true;

                ps.PrintFileName = @"test.pdf";
                //
                //ps.

                //Set PageSize (if required)
                //pgs.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);

                //Set PageMargins (if required)
                //pgs.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);

                //Print document using printer and page settings
                viewer.PrintDocumentWithSettings(ps);
                //viewer.PrintDocument();

                //Close the PDF file after priting

What I discovered and seems to be little explained, is that if you select
ps.PrintToFile = true;
no matter C# PDF library or PDF printer driver, Windows will just skip the PDF drivers and instead of PDF files will output PS (postscript) ones which obviously, will not be recognized by Adobe Reader.
Now the question (and I am positive that others who may want to print PDFs from C# may be encountered) is how to print to CutePDF for example and still suppress any filename dialog?
In other words, just print silently with programmatically selected filename from C# application. Or somehow convince "print to file" to go through PDF driver, not Windows default PS driver.
Thanks very much for any hints.

A: I solved conversion to grayscale with a commercial component with this post and I also posted there my complete solution, in care anyone will struggle like me.
Converting PDF to Grayscale pdf using ABC PDF


Q: PHP: Uncaught Error Cannot use object of type mysqli_result as array I have a simple section in which I am displaying data from the database,
If the user clicks eg construction and selects eg Algeria, I am displaying [251, 211,712] if a user clicks eg Power and selects eg. Egypt I am displaying [406, 228,559] etc
Now I want if the user clicks the button All available industries and select eg. Algeria I want to display this [251+203+130, 211,712+179,877+154,946] in a simple way like this in SQL
SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value FROM `meed` WHERE Countries = 'Algeria'

Which give me this [611, 546535]
Here is my solution
HTML

        Construction

        Power

        Oil

        All available industries

Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
    if( $(e.target).find("span.label").html()=="Confirm" ) {

        var selectedCountries = [];

        $('.video-btns .selected').each(function () {
            selectedCountries.push( $(this).parent().find("span.label").html() ) ;
        });

        if( selectedCountries.length>0 ) {
            if(selectedCountries.indexOf("All available countries")>-1) {
                selectedCountries = [];
            }

        } else {

            return;
        }

        var ajaxurl = "";
        if(selectedCountries.length>0) {
            ajaxurl = "data.php";
        } else {
            ajaxurl = "dataall.php";

        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                    countries: selectedCountries.join(","),
                    sector: selectedSector
            },
            success: function(result){
                console.log(result);
                result = JSON.parse(result);
                $(".video-btns").each(function () {
                    var getBtn = $(this).attr('buttonid');
                    if (getBtn == 106) {
                        var totalProjects = $(""+ result[0] + "");
                        $(this).append(totalProjects)
                    }else if(getBtn ==107){
                        var resultBudget = result[1]
                        var totalBudgets = $(""+ '&#36m' +" " + resultBudget +"");
                        $(this).append( totalBudgets)
                    }
                });
                return;
              }
        });
    }
});

UPDATE Here is Updated  data.php
      <?php

$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
echo '$countries';

 $conn = mysqli_connect("localhost", "root", "", "meedadb");
 if (mysqli_connect_errno())   {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $result = mysqli_query($conn, "SELECT * FROM meed");
 $data = array();

 $wynik = [];
$totalProjects = 0;
$totalBudget = 0;

 while ($row = mysqli_fetch_array($result))
 {
    if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {

     $totalProjects+= $row['SumofNoOfProjects'];
     $totalBudget+= $row['SumofTotalBudgetValue'];

    }elseif($selectedSectorByUser =="All available industries"){
      $result = mysqli_query($conn,
      "SELECT sum(SumofNoOfProjects) as 'SumofNoOfProjects, sum(SumofTotalBudgetValue) as SumofTotalBudgetValue
      FROM `meed`
      WHERE Countries = '$countries'");

      while( $row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
         echo json_encode([ $row['SumofNoOfProjects,'], $row['SumofTotalBudgetValue '] ] );
         exit;
        }

      exit;
    }
 }

 echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>

Now when the user clicks All available industries btn and selects a country I  get the following error

b>Fatal error:  Uncaught Error: Cannot use object of type mysqli_result as array in C:\custom-xammp\htdocs\editor\data.php:23

What do I need to change to get what I want? any help or suggestion will be appreciated,

A: you  should fecth a row (at least)
if (mysqli_connect_errno())   {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($conn,
    "SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value
    FROM `meed`
    WHERE Countries = '$countries'");

while( $row=mysqli_fetch_array($result,MYSQLI_ASSOC);) {
 echo json_encode([ $row['sum_projects'], $row['sum_value'] ] );
 exit;
}

for the multiple countries
Asuming you  $_POST['countries'] contains "'Egypt','Algerie'"
then you could use a query as
"SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value
    FROM `meed`
    WHERE Countries IN (" . $_POST['countries'] . ");"


Q: Dealing with single quotes in excel vba sql queries I am using excel sql queries to fetch data from the backend according to the selection i make in a dropdown box.However my sql queries are not working in cases where there is a single quote(') in the dropdown box value. For example-- Men's Wear . Please suggest me a way to deal with this problem
    SQL = "select Segment,Weeks,Value from [Category performance data$] where       Departments='" &       Sheet3.Range("Dept_name").Value & _
     "' and Metric ='Total Spend' group by Segment,Weeks,Value"
    Call execQry

A: Departments='" & replace(Sheet3.Range("Dept_name").Value, "'", "''") & _ "' and Metric


Q: Encrypting data at rest protect me against what type of attack? Encrypt data at rest is one of the major 101 of security for a lot of compliance (if not all of them). I am  however not sure I understand against which attack this protect me.
Let say I am in AWS cloud. I encrypt my S3 data at rest using KMS provided service.
The protection I get is, if someone get access to AWS network  and were able to access the data, it would get encrypted data. So basically, I am encrypting my data in case AWS is getting hacked. Now as unlikely it is, I understand the value.
Is there another kind of attack possible that encrypting data protecting me against?

A: Somebody could get access to a resource via a misconfigured IAM role for example. This is especially relevant for S3, where public access might sometimes be configured inadvertently. If you have encryption via KMS, access to the key would also have to be granted, which provides an additional layer of security, and something you can monitor and alert on easily. This also applies to your own components, some of which will be granted access to the KMS key, but others (like a frontend server) might not, because they don't need it, and you want to implement the least privilege principle to limit the impact of a potential breach. Of course you will not only rely on key access to implement access control to your resources, but it provides a single point where rules and actual access can easily be enforced and audited.
Also think about backups and disposed media. Maybe more usual to consider this when you host stuff yourself, but it is still relevant for public clouds. You probably trust AWS to manage backups and disposed media securely, but while they're pretty good at it, they might not be perfect, and you have zero control. If you store your data encrypted, there is no way for it to be recovered from a dumpster.


Q: Angular 2+ routage basic Complete a simple Angular component named MenuDisplayComponent having menu-display-component as selector.
Complete the declaration of the appRoutes variable.
The component must contain two  elements. They symbolize a menu of the application:
When we click on the  element with id="menu1" the component associated with the /menu1 route should be loaded.
When the  element with id="menu2" is clicked the component associated with the /menu2 route must be loaded.
Initially, neither component is loaded.
You must create the corresponding routes in appRoutes. Menu1Component corresponds to the menu1 path, Menu2Component corresponds to the menu2 path.
You only need to update MenuDisplayComponent (+ its template) and appRoutes.
 import { Component, Input, NgModule } from '@angular/core';
    import {APP_BASE_HREF} from '@angular/common';
    import { RouterModule, Routes } from '@angular/router';

    @Component({
      selector:'menu1-component',
      template: `

You are at menu 1.

      `
    })
    export class Menu1Component {
    }

    @Component({
      selector:'menu2-component2',
      template: `

You are at menu 2.

      `
    })
    export class Menu2Component {
    }

    @Component({
      selector:'menu-display-component',
      template: `

You are at menu 2.

      `

    })
    export class MenuDisplayComponent {

    }

    export const appRoutes:Routes = [
      {path:"menu1",component:Menu1Component},
       {path:"menu2",component:Menu2Component}
    ];

    // #region Preview
    @Component({
        template: `
          <menu-display-component></menu-display-component>
        `
    })
    export class PreviewComponent { }
    // #endregion Preview

    // #region Module declaration - Do not Change
    @NgModule({
      imports: [RouterModule.forRoot(appRoutes, {useHash: true})],
      exports: [RouterModule]
    })
    export class AppRoutingModule {
    }

    @NgModule({
        imports: [
          RouterModule,
          AppRoutingModule
        ],
        declarations: [PreviewComponent, Menu1Component, Menu2Component, MenuDisplayComponent],
        entryComponents: [PreviewComponent],
        providers: [{provide: APP_BASE_HREF, useValue : '/'}]
    })
    export class PreviewModule { }
    // #endregion Module declaration

A: One way you can do this is using children routes. This will help you load components inside of another component. You will need to add the router outlet tag inside the parent component for this to work. Let me know if that helps.


Q: Is it possible to add custom view on DefaultTimeBar in ExoPlayer Need to add custom views on the DefaultTimeBar in Exoplayer at particular timestamps to indicate that there is something which is coming up during the video play similar to what we have in terms of video ads.
Please find the attached image to understand the exact requirement.


Q: Split a pair of strings in bracket using python I want to split the following data into two columns, latitude and longitude and put them in a dataframe.
0     (45.349586099999996, -75.81031967988278)
1            (-37.77922725, 175.2010323246593)
2                   (-42.9945669, 170.7100413)
3                    (-39.2711067, 174.154795)
4                      (51.2800275, 1.0802533)
5           (-41.30222105, 172.89453190955697)
6                   (-35.3712702, 173.7405337)
7                   (-45.7255555, 168.2936808)
8                   (-40.3284102, 175.8190684)
9                   (-45.1299859, 169.5248818)
10           (-37.9503756, 176.93828736155422)

Can anyone help me please?

A: Another way:
data='''a  b
0     (45.349586099999996, -75.81031967988278)
1            (-37.77922725, 175.2010323246593)
2                   (-42.9945669, 170.7100413)
3                    (-39.2711067, 174.154795)
4                      (51.2800275, 1.0802533)
5           (-41.30222105, 172.89453190955697)
6                   (-35.3712702, 173.7405337)
7                   (-45.7255555, 168.2936808)
8                   (-40.3284102, 175.8190684)
9                   (-45.1299859, 169.5248818)
10           (-37.9503756, 176.93828736155422)'''
df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python')
df[['lat', 'lon']] = df.b.str[1:-1].str.split(',', expand=True)

     a                                         b                 lat                  lon
0    0  (45.349586099999996, -75.81031967988278)  45.349586099999996   -75.81031967988278
1    1         (-37.77922725, 175.2010323246593)        -37.77922725    175.2010323246593
2    2                (-42.9945669, 170.7100413)         -42.9945669          170.7100413
3    3                 (-39.2711067, 174.154795)         -39.2711067           174.154795
4    4                   (51.2800275, 1.0802533)          51.2800275            1.0802533
5    5        (-41.30222105, 172.89453190955697)        -41.30222105   172.89453190955697
6    6                (-35.3712702, 173.7405337)         -35.3712702          173.7405337
7    7                (-45.7255555, 168.2936808)         -45.7255555          168.2936808
8    8                (-40.3284102, 175.8190684)         -40.3284102          175.8190684
9    9                (-45.1299859, 169.5248818)         -45.1299859          169.5248818
10  10         (-37.9503756, 176.93828736155422)         -37.9503756   176.93828736155422

A: Data
          Position
0   (45.349586099999996,-75.81031967988278)
1          (-37.77922725,175.2010323246593)
2                 (-42.9945669,170.7100413)
3                  (-39.2711067,174.154795)
4                    (51.2800275,1.0802533)
5         (-41.30222105,172.89453190955697)
6                 (-35.3712702,173.7405337)
7                 (-45.7255555,168.2936808)
8                 (-40.3284102,175.8190684)
9                 (-45.1299859,169.5248818)
10         (-37.9503756,176.93828736155422)

Solution
 #Strip of the brackets if column is string and not tuple.
 #str.split column to make it a list
 #stack it to dataframe it

 pd.DataFrame(np.vstack(df['Position'].str.strip('\(\)').str.split(',')), columns=['Lat','Long'])

             Lat                Long
0   45.349586099999996  -75.81031967988278
1         -37.77922725   175.2010323246593
2          -42.9945669         170.7100413
3          -39.2711067          174.154795
4           51.2800275           1.0802533
5         -41.30222105  172.89453190955697
6          -35.3712702         173.7405337
7          -45.7255555         168.2936808
8          -40.3284102         175.8190684
9          -45.1299859         169.5248818
10         -37.9503756  176.93828736155422


Q: Passing Multidimensional array with variable size Passing dimensions of the array to function but still getting an error!
Code (You can directly scroll down to the error it gives and see only those lines in code)
class Solution {
    public:
    int mod = 1e9 + 7;
    int checkRecord(int n) {
        int dp[n + 1][2][3];
        memset(dp, -1, sizeof(dp));
        return helper(0, 1, 2, n + 1, 2, 3, dp);
    }
    int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {
        if(idx == N) return;

        if(dp[idx][A][startL] != -1) {
            return dp[idx][A][startL];
        }

        dp[idx][A][startL] = helper(idx + 1, A, 2, N, M, K, dp) % mod;

        if(startL > 0) {
            dp[idx][A][startL] += helper(idx + 1, A, startL - 1, N, M, K, dp) % mod;
        }
        return dp[idx][A][startL];
    }
};

Error
 error: cannot initialize a parameter of type 'int (*)[*][*]' with an lvalue of type 'int [n + 1][2][3]'
        return helper(0, 1, 2, n + 1, 2, 3, dp);
                                            ^~
 note: passing argument to parameter 'dp' here
    int helper(int idx, int A, int startL, int N, int M, int K, int dp[][M][K]) {
                                                                    ^

A:
int checkRecord(int n) {
    int dp[n + 1][2][3];

The size of an array variable must be compile time constant in C++. n + 1 is not compile time constant and as such the program is ill-formed.
If you want to create an array with runtime size, then you must create an array with dynamic storage duration. simplest way to do that is to use std::vector.

int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {

Same applies to parameters which are also variables. Though there is slight difference since the array parameter will be adjusted to be a pointer to the first element of the array and the outermost dimension of the array i.e. N is ignored. The type of dp would be int(*)[M][K] if M and K were compile time constant.

Yeah, but 3d vector is too much to type vector<vector<..

In order to write long class template instances, you should pace yourself so that you don't get exhausted before the end. In case you are overcome by fatigue, take a short break to recover and continue later. I believe that you can do it.
That said, the inner dimensions of your array seem to be constant, so you don't need to use vectors inside vectors.

if(idx == N) return;

This is an ill-formed return statement in a non-void function.

A: Seems like you are trying to solve a competitive programming problem. So my answer is going to focus on that. I think others pointed out why it is not valid C++.
In C++, I don't see any easy way to achieve what you want.
In practice, when it comes to competitive programming problems, you may just define a big global array(As problems have fixed input sizes usually. In this case, there would be the max number of N, M, and K) and you don't have to struggle with passing it. Reuse the array for each case, but make sure you initialize it every time. Yeah, this is not a good practice in general but pretty handy for competitive programming.
If you think about 3D vectors are overkill, you may consider this.


Q: How to use setMenuVisibility in fragment? I have a sliding tabbed layout with seven fragments. I am saving my events in another activity and retrieving data from database in fragment and creating views.
Now when I save the data in add event activity and finish that activity and return to fragment, the events are not getting created.  I am using setMenuVisibility funcion to show this events. But when I did debug the setMenuVisibility never run when I return from activity.
What's wrong here? How can I show events on fragments when I return from activity?
Fragment code:
public class Mon extends Fragment {

    private FrameLayout fab;
    private EventTableHelper mDb;
    private Intent i;
    private ViewGroup dayplanView;
    private int minutesFrom,minutesTo;
    private List<EventData> events;
    private List<View> list;
    private EventData e;
    private LayoutInflater inflater;
    public  boolean editMode;
    private RelativeLayout container;
    RelativeLayout parent;
     View eventView;
    private boolean mCheckFragment;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mon, container, false);
        list = new ArrayList<View>();

        dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout);

        showEvents();

        mCheckFragment = true;

        return view;
    }

    private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,final int id) {

       eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();

        container = (RelativeLayout) eventView.findViewById(R.id.container);
        TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
        list.add(eventView);

        if (tvTitle.getParent() != null)
           ((ViewGroup) tvTitle.getParent()).removeView(tvTitle);

        if(location.equals(""))
        {
            tvTitle.setText("Event : " + title);
        }
        else
        {
            tvTitle.setText("Event : " + title + " (At : " + location +")");
        }
        int distance = (toMinutes - fromMinutes);
        layoutParams.topMargin = dpToPixels(fromMinutes + 9);
        layoutParams.height = dpToPixels(distance);

        eventView.setLayoutParams(layoutParams);
        dayplanView.addView(eventView);
        container.addView(tvTitle);

        eventView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                i = new Intent(getActivity(), AddEventActivity.class);
                editMode = true;
                i.putExtra("EditMode", editMode);
                i.putExtra("id", id);
                startActivityForResult(i, 1);

            }
        });
    }

 @Override
 public void setMenuVisibility(final boolean visible) {
     super.setMenuVisibility(visible);
     if (visible) {

         if(mCheckFragment) {
             removeView();
             showEvents();
             Toast.makeText(getActivity(), "Monday", Toast.LENGTH_SHORT).show();
         }
         // ...
     }
 }

    public void showEvents()
    {
        mDb = new EventTableHelper(getActivity());
        events = mDb.getAllEvents("Mon");

        for (EventData eventData : events) {

            int id = eventData.getId();
            String datefrom = eventData.getFromDate();

            if (datefrom != null) {
                String[] times = datefrom.substring(11, 16).split(":");
                minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
            }
            String title = eventData.getTitle();
            String location = eventData.getLocation();
            String dateTo = eventData.getToDate();

            if (dateTo != null) {
                //times = dateTo.substring(11,16).split(":");
                String[] times1 = dateTo.substring(11, 16).split(":");
                minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
            }
            createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id);
            id++;

        }
    }

    public void removeView()
    {
        for(int i=0; i<list.size(); i++)
        {
            View view = (View)list.get(i);
            dayplanView.removeView(view);
        }
    }

    private int dpToPixels(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

}

Thank you.


Q: HTML5 video not playing on IE9 Im trying to use HTML5 video on IE9 but doesn't play.
When i play it locally evrything works fine, but when i upload to the server doesn't work.
This is the URL: http://inoq.com/lxgo2/monumentos.html
It works fine in all other browsers(Chrome, Safari, Opera, Firefox..) just not IE9.
I already added the mime types too .htaccess file:
AddType video/ogg                      ogv
AddType video/mp4                      mp4 m4v
AddType video/webm                     webm
This image shows the network logs on IE9:
Network logs IE9 http://inoq.com/lxgo2/network-log.jpg
Any idea on what can be the problem?
Thanks
Bruno


Q: 0x4 Decompression error in Python Confluent Kafka I've been having trouble getting python-confluent-kafka to work on my windows server.
When creating a simple consumer on my local machine, everything works fine.
However, once on the windows server, I will receive the messages but get the following error:

b'Decompression (codec 0x4) of message at 24023756 of 9550 bytes failed: Local: Not implemented'

I copied the exact conda environment I have on my local machine to the server.

A: Turns out it had to do with the .dll's not being found due to the Path/Environment Variables not being configured properly.


Q: Adding new unique grouping ID based on group_by variable I have a dataset with drugs being administered overtime. I want to create groups for each block of the drug being administered. I figured out a simple method to do this with a for-loop that I can apply to each patients set of drugs.
BUT I am curious if there is simple way to do this within the realm of tidyverse?
Not that it matters, but more so I am curious if there is a simple method already created for this problem.
Set-up
have <- tibble(
    patinet = c(1),
    date = seq(today(), today()+11,1),
    drug = c(rep("a",3), rep("b",3), rep("c",3), rep("a",3))
)

## Want

want <- tibble(
    patinet = c(1),
    date = seq(today(), today()+11,1),
    drug = c(rep("a",3), rep("b",3), rep("c",3), rep("a",3)),
    grp =  sort(rep(1:4,3))
)

> have
# A tibble: 12 × 3
   patinet date       drug
     <dbl> <date>     <chr>
 1       1 2022-03-16 a
 2       1 2022-03-17 a
 3       1 2022-03-18 a
 4       1 2022-03-19 b
 5       1 2022-03-20 b
 6       1 2022-03-21 b
 7       1 2022-03-22 c
 8       1 2022-03-23 c
 9       1 2022-03-24 c
10       1 2022-03-25 a
11       1 2022-03-26 a
12       1 2022-03-27 a

> want
# A tibble: 12 × 4
   patinet date       drug    grp
     <dbl> <date>     <chr> <int>
 1       1 2022-03-16 a         1
 2       1 2022-03-17 a         1
 3       1 2022-03-18 a         1
 4       1 2022-03-19 b         2
 5       1 2022-03-20 b         2
 6       1 2022-03-21 b         2
 7       1 2022-03-22 c         3
 8       1 2022-03-23 c         3
 9       1 2022-03-24 c         3
10       1 2022-03-25 a         4
11       1 2022-03-26 a         4
12       1 2022-03-27 a         4

A: You can use data.table::rleid
have %>% mutate(group = data.table::rleid(drug))

# A tibble: 12 x 4
   patinet date       drug  group
     <dbl> <date>     <chr> <int>
 1       1 2022-03-16 a         1
 2       1 2022-03-17 a         1
 3       1 2022-03-18 a         1
 4       1 2022-03-19 b         2
 5       1 2022-03-20 b         2
 6       1 2022-03-21 b         2
 7       1 2022-03-22 c         3
 8       1 2022-03-23 c         3
 9       1 2022-03-24 c         3
10       1 2022-03-25 a         4
11       1 2022-03-26 a         4
12       1 2022-03-27 a         4


Q: Apply function to URL and write in new column in CSV I'm a newbie and surprised there's already not a clear answer similar to what I'm asking, apologies if this is a duplicate.
I have a list of URLs in a CSV file I'm trying to shorten, I want to loop through my CSV file and then write a new column with the shortened URL right next to the original URL.
from pyshorteners import Shortener
import csv

def generate_short(url):
    x = shortener.short(url)
    return x
with open('Links_Test.csv') as csvfile:
    my_date = csv.reader(csvfile, dialect = 'excel')
    for row in my_data:
        x = shortener.short(row)
        print(X)

EDIT:
I keep getting the error "ValueError: Please enter a valid url" and don't know how to proceed from here.....I'm sure I'm the problem.
Here's what my input data looks like:
URL
http://www.google.com
http://www.facebook.com
http://www.twitter.com
http://www.linkedin.com

and here's what I want my output to look like:
URL                        Short_URL
http://www.google.com      http://goo.gle
http://www.facebook.com    http://goo.g3c
http://www.twitter.com     http://goo.g3a
http://www.linkedin.com    http://goo.g2q

Thank you for your help.  I was very surprised there's not already a clear answer posted (at least I couldn't find it) so I'm sorry if this is a duplicate.

A: Apply the function on row[0] or row['URL']
Also you have to apply it on my_data.iterrows()and not on my_data
from pyshorteners import Shortener
import pandas as pd

def generate_short(url):
    x = shortener.short(url)
    return x
    my_date = pd.read_csv( 'Link-Tests.csv', sep = "\t") #seperator argument is optional. It can be a semi colon, a tab. Check your CSV file for knowing what the separator is.
    for index,row in my_data.iterrows():
        x = shortener.short(row[0])
        print(X)

If you can always store the shortened URL into a separate list, convert it into a DataFrame and then merge with the original dataframe based on index.
lst = []
my_date = pd.read_csv( 'Link-Tests.csv', sep = "\t")
    for index,row in my_data.iterrows():
        x = shortener.short(row[0])
        lst.append(X)
df = pd.DataFrame(lst, columns=["Short-Url"])
my_data = my_data.join(df, how= 'outer')

A: First try doing this:
from pyshorteners import Shortener
import csv

def generate_short(url):
    x = shortener.short(url)
    return x
with open('Links_Test.csv') as csvfile:
    my_data = csv.reader(csvfile, dialect = 'excel')
    for row in my_data:
        print(row) # output: ['URL'], ['google.com']...

You probably want to use next() or maybe look at this thread  to ignore the header. Also, you probably want to use row[0] to get the first item in the list. So your final code might be
from pyshorteners import Shortener
import csv

def generate_short(url):
    x = shortener.short(url)
    return x
with open('Links_Test.csv') as csvfile:
    next(csvfile) # skip the header row
    my_data = csv.reader(csvfile, dialect = 'excel')
    for row in my_data:
        print(row[0]) # output: 'google.com' ....
        # do the link shortener stuff here