text:
Q: Problema com listView dentro de um fragment O meu problema é que quando clico em algum item da listView o app não me retorna nenhuma opção do menu. Opção qual, que quando clicada chamaria uma nova activity.
Código:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    animais = new ArrayList<>();

    View view = inflater.inflate(R.layout.fragment_animais, container, false);

    listView = (ListView) view.findViewById(R.id.lv_animais);

    adapter = new AnimaisAdapter(getActivity(),animais); //utilizo um adapter customizado

    listView.setAdapter(adapter);
    registerForContextMenu(view.findViewById(R.id.lv_animais)); //teste também passando apenas listView, porém sem sucesso

    Preferencias preferencias = new Preferencias(getActivity());
    String identificadorLogado = preferencias.getIdentificador();

    firebase = ConfiguracaoFirebase.getFirebase()
               .child("animal")
               .child(identificadorLogado);

    valueEventListenerAnimais = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            animais.clear();

            for(DataSnapshot dados: dataSnapshot.getChildren()){
                Animal animal = dados.getValue(Animal.class);
                animais.add(animal);
            }

            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };

    return view;
}

Rotina do CreateContextMenu:
@Override
public void onCreateContextMenu(final ContextMenu menu, View v, final ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuItem visualizarAnimal = menu.add("Visualizar Animal");
    visualizarAnimal.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            final Animal animal = (Animal) animais.get(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);

            Intent intent = new Intent(getActivity(), CadastroAnimalActivity.class);
            intent.putExtra("brinco", animal.getBrinco());
            intent.putExtra("nome", animal.getNome());
            startActivity(intent);

            return false;
        }
    });

}

Eu fiz uma tentativa (veja abaixo), porém sem sucesso:
@Override
public void   onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_item_list, menu);
 }

 @Override
 public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    final Animal animal = (Animal) animais.get(info.position);

        switch (item.getItemId()) {
            case R.id.item_list_editar:

                Intent intent = new Intent(getActivity(), CadastroAnimalActivity.class);
                intent.putExtra("brinco", animal.getBrinco());
                intent.putExtra("nome", animal.getNome());
                startActivity(intent);

                return true;

            case R.id.item_list_visualizar_despesas:
                Intent intentDespesas = new Intent(getActivity(), DespesasAnimal.class);

                intentDespesas.putExtra("brinco", animal.getBrinco());
                intentDespesas.putExtra("nome", animal.getNome());

                startActivity(intentDespesas);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
}

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {

animais = new ArrayList<>();

View view = inflater.inflate(R.layout.fragment_animais, container, false);

listView = (ListView) view.findViewById(R.id.lv_animais);

adapter = new AnimaisAdapter(getActivity(),animais);

listView.setAdapter(adapter);
registerForContextMenu(listView);

Preferencias preferencias = new Preferencias(getActivity());
String identificadorLogado = preferencias.getIdentificador();

firebase = ConfiguracaoFirebase.getFirebase()
           .child("animal")
           .child(identificadorLogado);

valueEventListenerAnimais = new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        animais.clear();

        for(DataSnapshot dados: dataSnapshot.getChildren()){
            Animal animal = dados.getValue(Animal.class);
            animais.add(animal);
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
};

return view;
}

}

A: > Eu faria diferente colocaria um popup no click da lista para assim fazer a chamada
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

            Animal animal = (Animal) arg0.getItemAtPosition(position)

            PopupMenu popup = new PopupMenu(MainActivity.this, arg1);
            popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
            //registering popup with OnMenuItemClickListener
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.item_list_editar:

                            Intent intent = new Intent(getActivity(), CadastroAnimalActivity.class);
                            intent.putExtra("brinco", animal.getBrinco());
                            intent.putExtra("nome", animal.getNome());
                            startActivity(intent);

                            return true;

                        case R.id.item_list_visualizar_despesas:
                            Intent intentDespesas = new Intent(getActivity(), DespesasAnimal.class);

                            intentDespesas.putExtra("brinco", animal.getBrinco());
                            intentDespesas.putExtra("nome", animal.getNome());

                            startActivity(intentDespesas);
                            return true;
                        default:
                            return super.onContextItemSelected(item);
                    }
                    return true;
                }
            });

            popup.show();//showing popup menu
        }
    });


text:
Q: MySql mariaDB CREATE FUNCTION DELIMITER doesnt work. has error near '' im going insane. i dont know whats wrong with this code i see nothing wrong in it. but it kept reading thee same error each time i put the $$ after the "END". please help guys...
here is my code
DELIMITER $$
CREATE FUNCTION fungsi1 (a int)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE nilaiasal INT;
DECLARE teks VARCHAR(50);
SET nilaiasal = a * a;
IF nilaiasal > 100 THEN
SET teks  = 'LEBIH DARI SERATUS';
ELSEIF nilaiasal < 100 THEN
SET teks  = 'KURANG DARI  SERATUS';
INSERT INTO table1 (dataone,datatwo) VALUES(a,teks);
SELECT * FROM table1;
RETURN (nilaiasal);
END $$
DELIMITER ;

And the error is this

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 15

Please help me. I've looked up create functions error and there hasnt been anyone that has a problem near ''.

A: You might want to consider using a stored procedue instead of a function if you want to return a result set.
You are missing END IF; as Ergest Basha suggested and you are trying to return a result set from a function which is not allowed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using a unit of minutes in MySQL query How do I change 1 hour to 10 minutes in the query below?
$query = "SELECT COUNT(*) as num
  FROM values
 WHERE time >= NOW() - INTERVAL 1 HOUR
   AND ip1 = '$ip1'
   AND ip2 = '$ip2'
   AND submissionid = '$submissionid'";

A: See the documentation for date and time functions.
INTERVAL 10 MINUTE

A: just change INTERVAL 1 HOUR to INTERVAL 10 MINUTE


text:
Q: is there a limit to how many drives I can connect to my Mac? I am on Mac Book Pro running OS X El Capitan 10.11.5 and I use a lot of drives for my personal data and data from clients (and every drive has a redundant drive constantly being updated in case of drive failure).
Besides the internal SSD drive and Might Drive SSD Flash drive inside my SD slot, I have 8 external drives. 5 of them are all powered drives connected via daisy-chained FireWire 800 cables that originate from the Thunderbolt port with a TB to FW800 adapter. 4 of them are USB drives (one is a powered USB 2.0 drive and the other 3 are self-powered USB 3.0 drives that are connected to the computer via a 3.5A powered USB 3.0 hub).
Today I had to connect another drive from a client. This drive is a self-powered drive that has USB 3.0 and FW800 connections. Needless to say the drive works if plugged in by itself with either of those connections but as soon as I plug the drive in with my existing drives all in it either doesn't mount at all (if I plug it in on the USB hub via USB 3.0) or it makes the entire daisy-chain of FW800 drives disconnect (and I get an error saying I improperly disconnected the drives). I have drive putting the drive at the top or at the end of the chain of drives but I get the same result every time. Even though I specifically bought a USB 3.0 powered 3.5A amp to avoid issues of powering multiple drives, I thought it might be a power issue, but when this happens on the FireWire 800 chain and all the drives on that chain are powered by walmart adapters I began to question if there is a limit to connecting drives to a computer.
Any information on this would be helpful.
Thanks


text:
Q: Ошибка (активно) E0137 выражение должно быть допустимым для изменения левосторонним значением Понятия не имею что ему не нравиться, но указывает на эту ошибку в 5-ой строке.
 void poz_perv_i_posl_par_0(int* x, int n)
 {
    int i;
    for (i = 0; i < n; i++)
        if (x[i] = 0 && x[i+1] = 0)
        {
            printf("Порядковый номер первого элемента первой пары\n i=% ", i);
            break;
        }
    for (i = n; i = 0; i--)
        if (x[i] = 0 && x[i + 1] = 0)
        {
            printf("Порядковый номер первого элемента последней пары\n i=% ", i);
            break;
        }
}

A: Приоритеты операторов приводят к тому, что ваше
if (x[i] = 0 && x[i+1] = 0)

рассматривается как
if (x[i] = (0 && x[i+1]) = 0)

т.е. вы, получается, хотите присвоить значение 0 выражению
0 && x[i+1]

Т.е. сделать что-то вроде
5+3 = 2

присвоить 2 сумме 5+3 :)
А вообще, просто типичная ошибка - перепутать оператор присваивания = и сравнения на равенство ==. Явно хотели написать
if (x[i] == 0 && x[i+1] == 0)


text:
Q: "say something" vs. "tell something to somebody" I am familiar with this rule:
1.Tell something to somebody
2. Say something
But what about his sentence from Melville's Bartleby Scrivener?

"Bartleby!"
  "I know you," he said, without looking round,—"and I want nothing to say to you."

A: To tell and to say are very flexible in their usage. A rule of thumb: when you tell something, you are giving particular information, and when you say something, you are letting your opinion be known or sharing your thoughts.
These are all idiomatic:
Psssst! ... I have a secret to tell you!
Angry mother to disobedient teenage daughter:
Come downstairs this instant, young lady! I have something to say to you!
The locution Bartleby uses is somewhat archaic today. Bartleby is saying that he does not want to have anything to do with the person.  He does not want to find himself in a situation where the two of them are conversing about anything.


text:
Q: Draw nodes following a specific order on Networkx in Python? I didn't find any answer to the question I asked, maybe because I didn't use the correct words to express it, so I'll try asking her hoping someone can help me, thanks in advance.
I'm trying to draw graphs using the NetworkX library, version 2.5, with Python 3.9, running on Debian.
My graph consists in a node "s", a node "t", multiple nodes t_i , 1 <= i <= n , and multiple nodes v_j, 1 <= j <= m. There are edges connecting "s" and t_i nodes, between some t_i and v_j nodes, and between v_j and "t" nodes.
Is it possible to draw it like in the picture below (includes edges of course) ? I didn't find a way to order how the nodes are displayed...

Thanks a lot !

A: You can use the multipartite_layout for your desired positioning. You need to specify in a node attribute (see level below) to which group the node should belong and then retrieve a layout in the given levels. Adding edges will not change the position of the nodes, so I did not added them to the following minimal example:
import networkx as nx
import matplotlib.pylab as pl

G = nx.Graph()

G.add_node("s", level=0)
G.add_node("t_1", level=1)
G.add_node("t_2", level=1)
G.add_node("v_1", level=2)
G.add_node("v_2", level=2)
G.add_node("v_3", level=2)
G.add_node("t", level=3)

pos = nx.multipartite_layout(G, subset_key="level")

nx.draw(G, pos, with_labels=True)
pl.show()

Result


text:
Q: Array comparison? I am making a function that takes in an example and an ip address. For ex.
compare('192.168.*','192.168.0.42');

The asterix indicates that the following parts of ip can be anything. The function returns true or false based on if the example and ip is a match. I tried this kind of solution.
var compare = function(example, ip){
  var ex = example.split(".");
  var ip = ip.split(".");
  var t = 0;
  for(var i=0; i<4; i++){
    if(ex[i] == ip[i] || ex[i] == "*" || typeof ex[i] === 'undefined' && ex[i-1] == "*"){
          t++
          if(t==4){
            return true
          }
       }else{
        return false;
      }
  }
}

What are the main advantages of using regular expression over this solution? What would be the best regular expression to do this?

A: How about checking if they are not equal then just return false?

var compare = function(example, ip){

  // You should have some basic IP validations here for both example and ip.

  var ex = example.split(".");
  var ip = ip.split(".");
  for(var i=0; i<ex.length; i++){

      if(ex[i]=='*')
        break;

      if(ex[i]!=ip[i])
        return false;

  }

  return true;
}

alert(compare('333.321.*','333.321.345.765'));
alert(compare('333.322.*','333.321.345.765'));
alert(compare('333.321.345.*','333.321.345.765'));

A: This goes way better with regular expressions. Try this:
function compare(example, ip) {
  var regexp = new RegExp('^' + example.replace(/\./g, '\\.').replace(/\*/g, '.*'));
  return regexp.test(ip);
}

compare('192.168.*', '192.168.0.42'); // => true
compare('192.167.*', '192.168.0.42'); // => false

What this does is, it translates your pattern to an regular expression. Regular expressions are extremely powerful in matching string. It also covers cases like this:
compare('192.168.*.42', '192.168.1.42'); // => true
compare('192.167.*.42', '192.168.1.43'); // => false


text:
Q: How to make axes fontsize in subplots similar in matplotlib? I have plotted a group of 4 box-plots with matplotlib and I have used different ways to make axes font-size and shape similar but one of the subplots has a different shape. I do not know how to fix it. I have put my result here. I used rcParams also font-size in each sub-plot but none of them were a solution to this problem. How to make all of the axis font sizes similar in terms of shape??I know that it would be better to define a reproducible question but I was not sure in which part I made a mistake that's why I have written my code here. The code is below:

import os
import numpy as np
import matplotlib.pyplot as plt
import pylab
import matplotlib as mpl
import pandas as pd
from matplotlib import cm
from matplotlib import rcParams
fig, axs = plt.subplots(2, 2,sharex=True,sharey=True)

plt.rcParams.update({'font.size': 20})
root = r'C:\Users\Master Candidate\Desktop\New folder\Desktop\Out\NEW SCENARIO\Intersection\Beta 10\intersection'
xx=[]
percentage=[]
labels = []
gg=[]
my_list = os.listdir(root)
my_list =  [file for file in sorted(my_list) if os.path.isdir(os.path.join(root, file))]
my_list= sorted(my_list)
percetanges = []
for directory in my_list:
    CASES = [file for file in os.listdir(os.path.join(root, directory)) if file.startswith('config')]
    if len(CASES)==0:
        continue
    CASES=sorted(CASES)
    percentage=[]
    for filename in CASES:
        with open(os.path.join(root, directory,filename), "r") as file:
            lines = file.readlines()
            x = [float(line.split()[0]) for line in lines]
            y = [float(line.split()[1]) for line in lines]
            g = np.linspace(min(y),max(y),100)
            h = min(y)+6
            t = max(y)-6
            xx=[]
            for i in range(1,len(x)):
                if (y[i] < h or y[i] > t):
                    xx.append(x[i])
            percent = len(xx)/len(y)
        percentage.append(percent)
    labels.append(directory)
    labels=sorted(labels)
    percetanges.append(percentage)
for i, x in enumerate(percetanges):
    axs[0, 0].boxplot(x,positions=[i],whis=0.001,widths = 0.6)
plt.xticks(np.arange(len(labels)),labels)
plt.grid()
plt.ylim((0,1))
...
the same strategy for the rest of 3 subplots

At the end of the code, I finalize the procedure with saving. I mean the effort that you see above is repeated for each subplot and I do not do any thing else

A: There are two ways to set the x-axis font size for multiple plots
plt.setp(ax.get_xticklabels(), fontsize=14)
ax.tick_params(axis='x', labelsize=14)

Code:
import matplotlib.pyplot as plt

def example_plot(ax):
    ax.plot([1, 2])
    plt.setp(ax.get_xticklabels(), fontsize=14)
#     ax.tick_params(axis='x', labelsize=16)

fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)

for ax in axs.flat:
    example_plot(ax)

fig.suptitle('sub title', fontsize=16)
fig.text(0.5, 0.04, '$Cr$', ha='center', va='center', fontsize=16)
fig.text(0.06, 0.5, '$a$', ha='center', va='center', rotation='vertical', fontsize=16)

plt.show()


text:
Q: How to compare columns and return values recursively? I have a data frame that looks like this:
data_dict = {'factor_1' : np.random.randint(1, 5, 10), 'factor_2' : np.random.randint(1, 5, 10), 'multi' : np.random.rand(10), 'output' : np.NaN}
df = pd.DataFrame(data_dict)

I'm getting stuck implementing this comparison:

*

*If factor_1 and factor_2 values match, then output = 2 * multi (Here 2 is kind of a base value). Continue scanning the next rows.

*If factor_1 and factor_2 values don't match then:

*

*output = -2. Scan the next row(s).

*If factor values still don't match until row R then assign values for output as $-2^2, -2^3, ..., -2^R$ respectively.

*When factor values match at row R+1 then assign value for output as $2^(R+1) * multi$.

*Repeat the process

The end result will look like this:

A: flag = False
cols = ('factor_1', 'factor_2', 'multi')
z = zip(*[data_dict[col] for col in cols])
for i, (f1, f2, multi) in enumerate(z):
    if f1==f2:
        output = 2 * multi
        flag = False
    else:
        if flag:
            output *= 2
        else:
            output = -2
            flag = True
    data_dict['output'][i] = output

The tricky part is flag variable, which tells you whether the previous row had match or not.

A: The solution I present is, maybe, a little bit harder to read, but I think it works as you wanted. It combines

*

*numpy.where() in order to make a column based on a condition,

*pandas.DataFrame.shift() and pandas.DataFrame.cumsum() to label different groups with consecutive similar values, and

*pandas.DataFrame.rank() in order to construct a vector of powers used on previously made df['output'] column.

The code is following.
df['output'] = np.where(df.factor_1 == df.factor_2, -2 * df.multi, 2)
group = ['output', (df.output != df.output.shift()).cumsum()]
df['output'] = (-1) * df.output.pow(df.groupby(group).output.rank('first'))

A: This solution does not use recursion:
# sample data
np.random.seed(1)
data_dict = {'factor_1' : np.random.randint(1, 5, 10), 'factor_2' : np.random.randint(1, 5, 10), 'multi' : np.random.rand(10), 'output' : np.NaN}
df = pd.DataFrame(data_dict)

# create a mask
mask = (df['factor_1'] != df['factor_2'])
# get the cumsum from the mask
df['R'] = mask.cumsum() - mask.cumsum().where(~mask).ffill().fillna(0)

# use np.where to create the output
df['output'] = np.where(df['R'] == 0, df['multi']*2, -2**df['R'])

   factor_1  factor_2     multi     output    R
0         2         1  0.419195  -2.000000  1.0
1         4         2  0.685220  -4.000000  2.0
2         1         1  0.204452   0.408904  0.0
3         1         4  0.878117  -2.000000  1.0
4         4         2  0.027388  -4.000000  2.0
5         2         1  0.670468  -8.000000  3.0
6         4         3  0.417305 -16.000000  4.0
7         2         2  0.558690   1.117380  0.0
8         4         3  0.140387  -2.000000  1.0
9         1         1  0.198101   0.396203  0.0


text:
Q: Missing wso2is stub maven dependencies I'm trying to migrate my project from wso2is-5.2.0 to wso2is-5.3.0.
My project has dependencies to many wso2is stub.
For exemple for oauth2 webservices I have
<dependency>
    <groupId>org.wso2.carbon.identity</groupId>
    <artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
    <version>5.1.3</version>
</dependency>

witch is available in wso2is nexus repository :
http://maven.wso2.org/nexus/content/repositories/releases/org/wso2/carbon/identity/org.wso2.carbon.identity.oauth.stub/5.1.3/
in wso2is-5.3 according to $wso2is_home/repository/components/plugins the stub is now in version  5.3.4
witch in not available in
http://maven.wso2.org/nexus/content/repositories/releases/org/wso2/carbon/identity/org.wso2.carbon.identity.oauth.stub/
Same problem for artifacts

*

*org.wso2.carbon.identity.user.registration.stub

*org.wso2.carbon.identity.mgt.stub

*org.wso2.carbon.user.mgt.stub

*org.wso2.carbon.authenticator.stub

*org.wso2.carbon.um.ws.api.stub

I cannot keep previous version because wso2is-52 client stub calling wso2is-53 webservice I got error like this for exemple :
Caused by: java.lang.Exception: org.apache.axis2.databinding.ADBException: Unexpected subelement {http://dto.oauth.identity.carbon.wso2.org/xsd}state
Are the correct version going to be deployed later or a new nexus repository exists somewhere else or did I missed something ?
Regards

A: The group ids of the identity components were changed due to some technical requirement. So you have to refer the dependencies with the new group ids.
The org.wso2.carbon.authenticator.stub group id should remain unchanged as org.wso2.carbon because it comes from carbon kernel. The group ids of the rest of the listed ones should be changed as follows.

*

*org.wso2.carbon.identity.oauth.stub should have org.wso2.carbon.identity.inbound.auth.oauth2

*org.wso2.carbon.identity.user.registration.stub, org.wso2.carbon.identity.mgt.stub, org.wso2.carbon.user.mgt.stub all should have org.wso2.carbon.identity.framework

*org.wso2.carbon.um.ws.api.stub should have org.wso2.carbon.identity.user.ws


text:
Q: how to add border on row using table? can you please tell me how to add border on row using table ?
here is my code

.table_view_el {
  border: 1px solid
}

.table_view_el tr {
  border: 1px solid
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

        Party
        Lead Seats
        Win Seats
        Total Seats

        INC
        0
        120
        120

        BJP
        0
        50
        50

        JD(S)
        0
        37
        37

        OTH
        0
        15
        15

https://jsbin.com/hosogiyaji/edit?html,css,output

A: I usually apply two borders to the table and then the 2 opposite borders to the cells:

.table_view_el {
  border-right: 1px solid;
  border-bottom: 1px solid;
}

.table_view_el th,
.table_view_el td {
  border-top: 1px solid;
  border-left: 1px solid;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

        Party
        Lead Seats
        Win Seats
        Total Seats

        INC
        0
        120
        120

        BJP
        0
        50
        50

        JD(S)
        0
        37
        37

        OTH
        0
        15
        15

If you just want rows only, move left border from the cells to the table

A: i think so we can apply border on td so You can use this code for solution.
td {
    border-top: 1px solid #000000;
    border-left: 1px solid #000000;
    border-right: 1px solid #000000;
}

A: You can add the following border-collapse rule on your table to get the row borders to show:
table {
  border-collapse: collapse;
}

.table_view_el {
  border: 1px solid
}

.table_view_el tr {
  border: 1px solid
}

table {
border-collapse: collapse;
}

      Party
      Lead Seats
      Win Seats
      Total Seats

      INC
      0
      120
      120

      BJP
      0
      50
      50

      JD(S)
      0
      37
      37

      OTH
      0
      15
      15

A: It seems to me that
cannot be styled directly so what you can do is add a border bottom to the .
tr td {
  border-bottom: 1px solid black;
}

tr:last-child td {
  border-bottom: 0;
}


text:
Q: Livewire component can't read property sent in request I am trying to make new model which is sending the product_id. When I try to dump it, it will display the correct data but when I send the request I get error:
Attempt to read property "id" on null [On line 155]

And my line 155 is:
'product_id' => $this->product->id,
At the top of the file I have public $product; and I am calling this component as
 <livewire:prods.testComponent :product="$product"></livewire:prods.testComponent>

And $product is provided via TestComponentController.
I have also tried to do something like:
    public function mount(Product $product){
        $this->product = $product;
    }

Any ideas?


text:
Q: How to create Android UI mimicking the Living Social UI? I am fairly new to Android UI design. I'm attempting to mimic the UI design of the following Living Social screen shot:

What is the best way to structure the UI elements here? How can this be implemented in XML? I'm trying to use the Android Eclipse UI editor to drag and drop UI elements, but it seems that I'll need to dynamically program the UI. What is the recommended way to approaching a problem like this?
So far, I have the following:
<LinearLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >
            <ImageView
                android:id="@+id/imageViewBackground"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:layout_gravity="fill"
                android:scaleType="fitXY"
                android:src="@android:drawable/dialog_holo_dark_frame" />
            <View
                android:id="@+id/view1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <View
                android:id="@+id/view3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/abc_search_url_text_normal"
        android:gravity="bottom|end"
        android:orientation="vertical" >

        <Button
            android:id="@+id/buttonBUY"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="BUY!" />
    </LinearLayout>
</LinearLayout>

Questions:

*

*I'm using a parent LinearLayout. Inside this, I have a ScrollView for the top and a LinearLayout on the bottom. The LinearLayout on the bottom has a child button for the BUY NOW button. Is this the correct parent layout scheme?

*Inside the ScrollView is an ImageView which is aligned to the top of the ScrollView. Then, inside the scrollview are X number of white boxes. How can I place the inner white box view slightly on top of the ImageView? Will I need to do this programatically?

*What is the recommended way to create the inner white box views? Do I need to create a separate .xml view file for each of these? Or would you recommend to use a Fragment for each of the white boxes? Or, do I need to implement a custom view class for each of the white boxes?

Thank you

A: Probably, you need Parallax effect and CardView controls inside linear layout control. In order to add bottom button you can use Relative layout. As for parallax, please, take a look at the following thread : How to do the new PlayStore parallax effect


text:
Q: Multiple conditions in if statement shell script I would like to know whether it is possible to have more than two statements in an if statement when you are writing a shell script?
username1="BOSS1"
username2="BOSS2"
password1="1234"
password2="4321"

if(($username == $username1)) && (($password == password1)) ||
  (($username == $username2)) && (($password == password2)) ; then

This does NOT work. But is there a way to make it work?
Thanks!

A: if using /bin/sh you can use:
if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:
if [[ <condition> && <condition> ]]; then
    ...
fi

A: You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).


text:
Q: Erase a line using touch input Windows Phone 8 I have a sort of drawing app. The lines are drawn on the touch input.
      void Touch_FrameReported(object sender, TouchFrameEventArgs e)
      {
        int pointsNumber = e.GetTouchPoints(InkCanvas2).Count;
        TouchPointCollection pointCollection = e.GetTouchPoints(InkCanvas2);

        for (int i = 0; i < pointsNumber; i++)
        {
            if (pointCollection[i].Action == TouchAction.Down)
            {
                preXArray[i] = pointCollection[i].Position.X;
                preYArray[i] = pointCollection[i].Position.Y;
            }
            if (pointCollection[i].Action == TouchAction.Move)
            {
                Line line = new Line();

                line.X1 = preXArray[i];
                line.Y1 = preYArray[i];
                line.X2 = pointCollection[i].Position.X;
                line.Y2 = pointCollection[i].Position.Y;

                line.Stroke = StrokeColorBrush;
                line.Fill = StrokeColorBrush;
                line.StrokeThickness = StrokeWidth;
                line.StrokeDashCap = PenLineCap.Round;
                line.StrokeStartLineCap = PenLineCap.Round;
                line.StrokeEndLineCap = PenLineCap.Round;

                InkCanvas2.Children.Add(line);

                preXArray[i] = pointCollection[i].Position.X;
                preYArray[i] = pointCollection[i].Position.Y;

                Brush aSolidBrush = new SolidColorBrush(Colors.Black);

            }
        }

Mouse events
    void InkCanvas2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        currentPoint = e.GetPosition(InkCanvas2);
        oldPoint = currentPoint;
    }

    void InkCanvas2_MouseMove(object sender, MouseEventArgs e)
    {
        currentPoint = e.GetPosition(this.InkCanvas2);

        Line line = new Line() { X1 = currentPoint.X, Y1 = currentPoint.Y, X2 = oldPoint.X, Y2 = oldPoint.Y };
        line.Stroke = StrokeColorBrush;
        line.StrokeThickness = StrokeWidth;

        line.StrokeStartLineCap = PenLineCap.Round;
        line.StrokeEndLineCap = PenLineCap.Round;
        line.StrokeLineJoin = PenLineJoin.Round;

        this.InkCanvas2.Children.Add(line);
        oldPoint = currentPoint;
    }

I have done clear all by
 InkCanvas2.Children.Clear();

now Im trying to implement a eraser function, then i draw over the line, it should erase those parts.
I tried changing color to transparent which does not do the trick. Any suggestions?

A: You can do something like this:
inkCanvas2.EditingMode = InkCanvasEditingMode.EraseByPoint;


text:
Q: xmlstarlet, change xmlnodes, given a list of identifier nodes I have used xmlstarlet, for the following
replacement:
xmlstarlet ed -u //author[text()='Gambardella, Matthew'] -v 'Gambardella' bookstore.xml, in the following XML file:
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>

How can i, instead of a search and replace process, set specifically the values, in an xml file, using the book id identifier?
For example, for the  book id="bk101", and for book id="bk103" the author node, must become Gambardella, no matter what it now has (so we do not search and replace, but we set the value), for book id="bk102", the author must be set to say Clems Lebof. So we provide some comma separated book id values, and the corresponding values we need to be set, so the output will eventually become:
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Clems Lebof</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Gambardella</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>

How could the above, be accomplished, with the use of xmlstarlet?

A: Change the XPath to match author elements that is child of book where id attribute equals either 'bk101' or 'bk103' :
xmlstarlet ed -u "//book[@id='bk101' or @id='bk103']/author" -v 'Gambardella' bookstore.xml


text:
Q: String or binary data would be truncated, but everything is varchar(max)? I have a query to pivot some tabular data into a JSON-esque string array using a query similar to this:
SELECT cr.TableId AS Id,
       cast(quotename(
                       stuff(
                            (SELECT cast(',' AS VARCHAR(max)) + quotename(cast(li.ImageUrl AS VARCHAR(max)), '"')
                             FROM   [DSP].[CreativeLibraryImage] cli WITH (nolock)
                                    INNER JOIN [DSP].[LibraryImage] li WITH (nolock)
                                      ON li.LibraryImageId = cli.[CreativeLibraryImageId]
                             WHERE  cli.TableId = cr.TableId
                             FOR xml path('')
                             ), 1, 1, ''
                             ) --stuff
                      ) --quotename
                      AS VARCHAR(max)
            ) --cast
            AS ImagePaths
FROM   MyTable cr WITH (nolock);

I am getting the "String or binary data would be truncated" error halfway through my query, but I think I'm casting all the varchar data to varchar(max) data, so I shouldn't have any string length issues.  Clearly there's problem shoehorning this tabular data into a wide column, but I can't see where it could be truncating.
Can someone advise me on what conditions could cause this so that I can compensate accordingly?

A: Directly from BOL for quotename:

'character_string' Is a string of Unicode character data.
  character_string is sysname and is limited to 128 characters. Inputs
  greater than 128 characters return NULL.


text:
Q: CSV content being read as null with Spark I am trying to read a CSV file, so that I can query it using Spark SQL. The CSV looks like below:
16;10;9/6/2018

The CSV file contains no headers but we know that first column is a department code, second column is building code and third column is a date of format m/d/YYYY.
I wrote the following code to load the CSV filesv with a custom schema:
 StructType sch = DataTypes.createStructType(new StructField[] {
            DataTypes.createStructField("department",  DataTypes.IntegerType, true),
            DataTypes.createStructField("building", DataTypes.IntegerType, false),
            DataTypes.createStructField("date", DataTypes.DateType, true),

    });
    Dataset<Row> csvLoad = sparkSession.read().format("csv")
            .option("delimiter", ";")
            .schema(sch)
            .option("header","false")
            .load(somefilePath);
    csvLoad.show(2);

When I use csvLoad.show(2) it is only showing me the below output:
|department|building|date|
+----------+---------+---+
|null      |null     |null |
|null      |null     |null |

Can anyone please tell what is wrong in the code ? I am using spark 2.4 version.

A: The issue is with your date field, since it has a custom format you'll need to specify the format as an option:
Dataset<Row> csvLoad = sparkSession.read().format("csv")
        .option("delimiter", ";")
        .schema(sch)
        .option("header","false")
        .option("dateFormat", "m/d/YYYY")
        .load(somefilePath);

This will result in output:
+----------+--------+----------+
|department|building|      date|
+----------+--------+----------+
|        16|      10|2018-01-06|
+----------+--------+----------+


text:
Q: Unit test for checking is something was logged How would I go about writing a unit test to check if It logged the info.
 public void loadWheels() throws IOException {
        // Connect to Partner process file (if exists)
        SftpSession session = null;
        try {
            session = partnerServerClient.getSession();
            InputStream is = partnerServerClient.getWheelFile(session);
            log.info("File " + partnerServerClient.getConfig().getWheelFilename() + " was found");
            partnerServerClient.backupWheelFile(session);
        }
        catch(IOException e) {
            log.info("" + partnerServerClient.getConfig().getWheelFilename() + "was not found");
        }
        finally {
            // Close the session
            partnerServerClient.closeSession(session);
        }
    }
}

I have tried using private void setLogger but I am confused on how to use it.


text:
Q: SQL Server deleted stored procedure recovery I mistakenly removed all stored procedures from the database, actually executed a query but didn't notice EXEC statement. I recovered just 4 stored procedures from log by
Select
    Convert(varchar(Max), Substring([RowLog Contents 0], 33,
    LEN([RowLog Contents 0]))) as [Script]
from
    fn_dblog(NULL, NULL)
Where
    [Operation] = 'LOP_DELETE_ROWS'
    And [Context] = 'LCX_MARK_AS_GHOST'
    And [AllocUnitName] = 'sys.sysobjvalues.clst'

Please advice, stored procedures deleted and needs to be recovered.
Thanks


text:
Q: Can I use multi-threading inside pyspark mapPartitions? Can I use multi-threading inside pyspark mapPartitions?
I am running a spark job, where I have to do API calls over each row. We are using rdd map to run a python function to do API calls. These API calls take 0.01 ~ 0.5 seconds.
Can we use rdd mapParitions to run a python multi-threading function? What are the implications or Why can't we use threading?

Note: We are aware that, Spark may not the best tool for this job. Also, we can't use pandas udf or vectorization due to PyArrow dependencies.
Image Source: https://medium.com/ibm-data-science-experience/using-spark-as-a-parallel-processing-framework-for-accessing-rest-based-data-services-cd4c98526784 (not related to this question)

A: You should be able to, provided the target system is designed to cope with so many calls.
I would recommend going for non-blocking IO based API calls, those should be much more CPU efficient.
If you must assign more CPUs for task in hand, then you can instruct spark to do so with spark.task.cpus. Beware, this is a setting at spark application level. This could actually make your application slow if you have long data processing pipeline.


text:
Q: SSH in shell script with password I want to write  one shell script like
command1
ssh vivek@remotehost
    fire command on remote host

Now I have password in pass.txt . But when I change stdin with file. It is not reading password from file.
script.sh < password.txt

It is prompting for the password in place of reading password from the file.
What I am doing wrong ?
Second problem is that shell script don't shows the command fired. Is there a way , I can show fired command from it ?
Note :
I don't have key based access on remote system. I can only use password based login for ssh.

A: You can use ssh-agent or expect (the programing language) to do this.

A: OpenSSH ssh does not reads the password from stdin but from /dev/tty. That's why you have to use Expect or some other similar tool to automate it.
plink is another client, also available for Linux/Unix that accepts the password as a parameter on the command line... though that has some ugly security implications.

A: Okay, just to mention yet another option: sshpass is a tool developed for exactly the task of "fooling" regular openssh client to accept password non-interactively.


text:
Q: Auto refreshing div and new row data with sound alert I have the following piece of code for auto-refreshing a row. I would like to play a sound alert only if there is an incoming new entry in my database.
The new row updates, the alert message runs, but the notification sound auto replays regardless of whether the database entry is new. I am having difficulty determining:

*

*Why the audio replays regardless of whether the database entry is new, and

*How to make sure the audio message plays based only on some value retrieved from my database (like, timestamp or id, for example)

Below is my code:
HTML Code:
    <!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

JavaScript Code: with findBootstrapEnvironment function

PHP file Code: I created db with single table (events)
<?php
$host="localhost";  //Mysql Database Host Address
$username="root";       //Database Username
$pass="";           //Database Password
$dataname="testdb";     //Database Name

$connect = mysqli_connect($host, $username, $pass)
or die("Could not connect: " . mysql_error());
mysqli_select_db($connect, $dataname) or die(mysqli_error($con));

$sql = "SELECT * FROM events ORDER BY id DESC";

$result = mysqli_query($connect, $sql);

 print "

";

        while($row = mysqli_fetch_array($result))
        {
            echo "
" . $row['time'] . "
"; // Things that you want to fetch
        }

 echo "

";

 ?>


text:
Q: Prove $m-n$ and $2m+2n+1$ are coprime I have a small problem:

Let $m$ and $n$ be integers such that $2m^2+m = 3n^2+n$.
  Prove that $m-n$ and $2m+2n + 1$ are perfect square.

My work:
We have $$(m-n)(2m+2n+1) = 2(m^2-n^2) + m-n = n^2.$$
So, we need to prove that $m-n$ and $2m+2n+1$ are coprime. But I don't get further. Anyone can give me a hint?

A: Assume for contradiction $p\mid \gcd(m-n,2m+2n+1)$ for some prime $p$.
But then $p\mid n^2\iff p\mid n$, and so $p\mid m-n\implies p\mid m$.
However, $p\mid 2m+2n+1$ is then impossible.


text:
Q: Recommended TFS 2010 team project setup What is the recommended organizational structure of team projects in TFS 2010? Let's say we have 4 big departments within our enterprise. Is the recommended approach to create a team project for each department or logical representation of one's organization and have different folders for VS projects within those TFS team projects? Or should each reasonable big project have their own team project?
I am asking more from a perspective of code storage and TFS artifacts. If we are to store both code and user stories, tasks, etc. in one big team project, does that hinder the agile development process? We can still setup separate queries and a separate dashboard for each "project" within the big team project. However, the builds would be in this giant list of builds.
If we had many smaller team projects, it would be more difficult for QA to span their work across multiple team projects. They'd need to know where to enter bugs - knowledge that we don't necessarily want to rely on.
So what is the best practice?

A: Storing everything in a single project will not hinder "the agile development process".  My recommendation would be to create an area path for each project, and organize your work items under those area paths.  You'll have a product backlog query for each area.  Use the iteration path field to then drive a schedule across all the projects.  That should work fine.  All the reports can then be filtered by area and/or iteration.
For builds, I see many teams prefixing build definitions to provide better organization.  Here's a blog post that describes an extension you can download to help better organize builds.
http://blogs.msdn.com/b/bharry/archive/2011/04/01/build-folders.aspx


text:
Q: Creating numlink functions in php Hae .
I have a website where i display data from my website ... I have a very big problem of creating num link php functions. For instance , on click the next numlink for this example url 'http://www.deffsale.com/AllAds/?Ad=Other%20ladys%20Fashion?page=1' it is returning this 'http://www.deffsale.com/AllAds/?page=1' I'm testing it on my local host and have been searching all over the net and up .. I request any person with an idea or a link where i can solve this problem for my site . In addition , i have a mobile version for the same site and i would like to apply the same theory on it .
My code
<?php
            require'../../../php/connection.php';

            $dataperpage=12;
            $page_visible=200;

            if(isset($_GET['page'])){
                $pagenum=$_GET['page'];
                $query="select `create_gig_id` from `create_gig`";
                $query_run=mysql_query($query);

                if($num_rows=mysql_num_rows($query_run)){
                    $num_rows;
                }
                $user_id=getUserField('account_id');

                $maxpage=ceil($num_rows / $dataperpage);
                $itemfrom=($pagenum-1) * $dataperpage;

                $query="select t1.create_gig_id,t1.gigSubCategory,t1.amount_charge,t1.gig_pic,t1.gig_type,t1.duration,t2.profile_photo,t2.user_name FROM create_gig t1 JOIN user_account t2 ON t2.account_id=t1.account_id where t1.Approve='approved' order by rand() DESC limit $itemfrom,$dataperpage";
                $query_run=mysql_query($query);
                $cols=4;

                echo"
";
                do{

                    echo"
";
                        for($i=1;$i<=$cols;$i++){

                            $row=mysql_fetch_array($query_run);

                            if($row){

                                $gig_pic= $row['gig_pic'];
                                $order_type=$row['gigSubCategory'];
                                $create_gig_id = $row['create_gig_id'].'

';

                                    $duration= $row['duration'];

                                    echo"";

                                    echo"
";
                                        echo"
";
                                        echo"$".$row['amount_charge']."";

                                                echo"".''."";
                                                        $passString=$row['create_gig_id'];
                                                        $gig_id=encrypt($passString);
                                                        //$gig_id=urlencode($encrypted_string);
                                                        $rand=encrypt(rand(34567,345678988));

                                                echo"I will do ".$order_type."
by &nbsp".$row['user_name']." in ".$duration." days
read more >>";

                                                echo"	";
                                                echo"".'&nbsp'."	";
                                        echo"
";
                                    echo"
";
                                                echo"	";

                                }else
                                    {
                                        echo " 	";
                                    }
                            }
                                        echo"
";
                                }while($row);
                    echo"
";

                echo"

";

    numlinks($pagenum,$maxpage,$maxpage,'','');
    }
    ?>

Numlink include code
<?php

function numlinks($pagenum, $maxpage, $pages_visible, $scriptname="", $get="") {

    echo '

';
    if ($pagenum > 1) {
        echo '«	';   // first page
        echo 'previous	';   // prev page
    } else {
        echo '«	';   // first page
        echo 'previous	';   // prev page
    }

    $i=1;
    while ($i <= $pages_visible){
        if ($pagenum-ceil($pages_visible/2) < 0) {  //wenn unterer Bereich
            if ($i == $pagenum) echo ''.($pagenum).'	';
            else echo ''.($i).'	';

        } else if ($pagenum+floor($pages_visible/2) > $maxpage) {  // wenn oberer bereich
            if($maxpage > $pages_visible) $j = $maxpage-$pages_visible+$i;
            else $j = $i;

            if ($j == $pagenum) echo ''.($pagenum).'	';
            else echo ''.$j.'	';

        } else {  // wenn mittlerer bereich
            if ($i == ceil($pages_visible/2)) echo ''.($pagenum).'	';
            else {
                $j = $pagenum-ceil($pages_visible/2)+$i;
                echo ''.$j.'	';
            }
        }
        if ($i == $maxpage) break;
        $i++;
    }

    if ($pagenum < $maxpage){
        echo 'next	';  // next page
        echo '»	';   // last page
    } else {
        echo 'next	';   // first page
        echo '»	';   // prev page
    }

    echo '

';
}

function page_name($nr, $scriptname, $get="") {
    $scriptname.='?page='.$nr;
    if ($get != '') $scriptname.='&'.$get;
    return $scriptname;
}

?>


text:
Q: In Python, how can I inspect a specific section of XML and extract the node text? I'm using minidom to inspect XML which contains a list of debug key listings. An example of the XML is as follows:
<Shortcuts>
  <Item>
    <CommandName>DebugCommandName_1</CommandName>
    <ShortcutKeys>
      <Item>
        <Keys>
          <Item>KEY_1</Item>
          <Item>KEY_2</Item>
        </Keys>
      </Item>
    </ShortcutKeys>
  </Item>
...
  <Item>
    <CommandName>DebugCommandName_2</CommandName>
    <ShortcutKeys>
      <Item>
        <Keys>
          <Item>KEY_3</Item>
        </Keys>
      </Item>
      <Item>
        <Keys>
          <Item>KEY_4</Item>
        </Keys>
      </Item>
    </ShortcutKeys>
  </Item>
</Shortcuts>

For reasons beyond my control, I will not be able to demand the format of the incoming XML is changed to be more consistent, so I must account for both layouts of the ShortcutKeys sections of the document, as well as the multiple Item child elements all over the place.
Parsing the XML with minidom, I then use the following Python to extract content:
for item in parsedKeyComboFile.getElementsByTagName("Item"):
if (item.getElementsByTagName("CommandName").length > 0):
    commandName = item.getElementsByTagName("CommandName")[0].childNodes[0].nodeValue
    print(commandName)
elif (item.getElementsByTagName("Keys").length > 0):
    keyCombo = item.getElementsByTagName("Item")[0].childNodes[0].nodeValue
    print(keyCombo)

I'll eventually be adding this info to dictionaries, but for now the print out of the above XML I get is:
DebugCommandName_1
KEY_1
DebugCommandName_2
KEY_3
KEY_4

when what I desire is:
DebugCommandName_1
KEY_1 KEY_2
DebugCommandName_2
KEY_3 KEY_4

(I realise I'm not properly formatting the print of the keys to achieve the single line output. They key thing here is not skipping over the KEY_2 Item.)
I know that the [0] in the keyCombo= line limits me to the first occurence of Item in Keys.
So, is there a way for me to inspect a top level Item and all its child elements, pulling out the single CommandName and all of the Keys Items inside that top-level Item, before then moving on to the next top level Item and repeating the process? I have utterly failed to achieve this so far.
Should I be using ElementTree?
Many thanks.

A: I've no experience with minidom, and by recommendation

It's use is not recommended, you probably want to use xml.etree.ElementTree instead.

-- from the minidom tag info
If you can use xml.etree.ElementTree instead, this may be a straightforward way:
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()  # unused variable in this example

for elem in tree.iter():
    if elem.tag == 'CommandName':
        print(elem.text)
    if elem.tag == 'Keys':
        for item in elem:
            print(item.text)

Prints
DebugCommandName_1
KEY_1
KEY_2
DebugCommandName_2
KEY_3
KEY_4

Or if you want lists for each <Keys> tag:
if elem.tag == 'Keys':
    print([item.text for item in elem])

Prints:
DebugCommandName_1
['KEY_1', 'KEY_2']
DebugCommandName_2
['KEY_3']
['KEY_4']

A: I am unable to comment as i am below the threshold so please forgive me for putting this in as an answer
yes you should probally be using element tree as per this link i found on here
Python Minidom XML Query


text:
Q: Show multiple dropdown values at once in Plotly So I am aware the "multi=True" will allow users to select more than one value from the dropdown box. However, I keep getting an error every time and I believe its due to the number of Y axises on my graph.
The code is below, and the goal is to select more than one things on the graph at once. Right now, my code is set to select to different y values set to the same x axis via two separate graphs (fig1 and fig2).Before, I had one graph with both y axis on it, but could not get the call back to address each one individually.
Any ideas on how to make this happen? Thanks in advance!

###THIS WILL LET ME DROP DOWN BUT TO SEPERATE GRAPHS AND WONT ALLOW ME TO HAVE BOTH DISPLAYED AT THE SAME TIME

import pandas as pd

fig1 = px.line(full_data, x = "Date", y = "Volume")
fig2 = px.line(full_data, x = "Date", y = "Price")

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px

# you need to include __name__ in your Dash constructor if
# you plan to use a custom CSS or JavaScript in your Dash apps
app = JupyterDash(__name__)

#---------------------------------------------------------------
app.layout = html.Div([
    html.Div([
        html.Label(['Full Chart']),
        dcc.Dropdown(
            id='my_dropdown',
            options=[
                     {'label': 'Price', 'value': 'Price'},
                     {'label': 'Volume', 'value': 'Volume'},
                     {'label': 'Positive Tweets', 'value': 'Positive Tweets'},
                     {'label': 'Negative Tweets', 'value': 'Negative Tweets'},
                     {'label': 'Neutral Tweets', 'value': 'Neutral Tweets'},
                     {'label': 'Total Number of Tweets', 'value': 'Total Number of Tweets'}
            ],
            value='Price',
            multi=True,
            clearable=False,
            style={"width": "50%"}
        ),
    ]),

    html.Div([
        dcc.Graph(id='the_graph')
    ]),

])

#---------------------------------------------------------------
@app.callback(
    Output(component_id='the_graph', component_property='figure'),
    [Input(component_id='my_dropdown', component_property='value')]
)

def update_graph(my_dropdown):
    if my_dropdown == 'Price':
        return fig1
    if my_dropdown == 'Volume':
        return fig2
etc for rest of the data...

<!-- begin snippet: js hide: false console: true babel: false -->

if __name__ == '__main__':
    app.run_server(debug=True, port = 9001)

A: First of all, in case of multi-dropdown menu, the value attribute inside the dropdown component should be a list and not a string (as you'll be selecting a list of options).
In order to customize each trace separately, you have to use graph_objects instead of Plotly express. The following code will update the figure with a new trace every time you'll select an option from the dropdown menu.
import pandas as pd
import numpy as np

# fig1 = px.line(full_data, x = "Date", y = "Volume")
# fig2 = px.line(full_data, x = "Date", y = "Price")

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go

# you need to include __name__ in your Dash constructor if
# you plan to use a custom CSS or JavaScript in your Dash apps
app = dash.Dash(__name__)

# Creating random DataFrame
columns = ['Price', 'Volume', 'Positive Tweets', 'Negative Tweets', 'Neutral Tweets', 'Total Number of Tweets']
np.random.seed(2019)
N = 10
rng = pd.date_range('2019-01-01', freq='MS', periods=N)
df = pd.DataFrame(np.random.rand(N, 6), columns=columns, index=rng)

#---------------------------------------------------------------
app.layout = html.Div([
    html.Div([
        html.Label(['Full Chart']),
        dcc.Dropdown(
            id='my_dropdown',
            options=[
                     {'label': 'Price', 'value': 'Price'},
                     {'label': 'Volume', 'value': 'Volume'},
                     {'label': 'Positive Tweets', 'value': 'Positive Tweets'},
                     {'label': 'Negative Tweets', 'value': 'Negative Tweets'},
                     {'label': 'Neutral Tweets', 'value': 'Neutral Tweets'},
                     {'label': 'Total Number of Tweets', 'value': 'Total Number of Tweets'}
            ],
            value=['Price'],
            multi=True,
            clearable=False,
            style={"width": "50%"}
        ),
    ]),

    html.Div([
        dcc.Graph(id='the_graph')
    ]),

])

#---------------------------------------------------------------
@app.callback(
    Output(component_id='the_graph', component_property='figure'),
    [Input(component_id='my_dropdown', component_property='value')]
)

def update_graph(my_dropdown):

    fig = go.Figure()

    for label in my_dropdown:
        fig.add_trace(go.Scatter(
            x = df.index,
            y = df[label],
            mode = 'lines',
            name = label
        ))
    return fig

if __name__ == '__main__':
    app.run_server(debug=True, port=9001)

The output of the code: Click Here

A: final code and function, allowed me to use the drop down menu and added the additional y axis as well so multiple values can show properly at once. Thanks to Waleed Malik for the initial code!

import pandas as pd

import dash
from dash import dcc
from dash import  html
from dash.dependencies import Input, Output
import plotly.express as px

# you need to include __name__ in your Dash constructor if
# you plan to use a custom CSS or JavaScript in your Dash apps
app = JupyterDash(__name__)

app.layout = html.Div([
    html.Div([
        html.Label(['Full Chart']),
        dcc.Dropdown(
            id='my_dropdown',
            options=[
                     {'label': 'Price', 'value': 'Price'},
                     {'label': 'Volume', 'value': 'Volume'},
                     {'label': 'Positive Tweets', 'value': 'Positive Tweets'},
                     {'label': 'Negative Tweets', 'value': 'Negative Tweets'},
                     {'label': 'Neutral Tweets', 'value': 'Neutral Tweets'},
                     {'label': 'Total Number of Tweets', 'value': 'Total Number of Tweets'}
            ],
            value=['Price'],
            multi=True,
            clearable=False,
            style={"width": "50%"}
        ),
    ]),

    html.Div([
        dcc.Graph(id='the_graph')
    ]),

])
#---------------------------------------------------------------

#---------------------------------------------------------------
@app.callback(
    Output(component_id='the_graph', component_property='figure'),
    [Input(component_id='my_dropdown', component_property='value')]
)

def update_graph(my_dropdown):

    fig = make_subplots(specs=[[{"secondary_y": True}]])

    for label in my_dropdown:
        if label == "Volume":
            fig.add_trace(go.Bar(
            x = full_data["Date"],
            y = full_data["Volume"],
            #mode = "lines",
            name = label),
                secondary_y = True
        )

        else:
            fig.add_trace(go.Scatter(
            x = full_data["Date"],
            y = full_data[label],
            mode = 'lines',
            name = label,
        ))

    return fig

if __name__ == '__main__':
    app.run_server(debug=True, port = 9001)


text:
Q: Finding photos on OS X 10.10.4 Ever since I updated my MacBook to OS X 10.10.4 a lot of my current uploaded photos from 2015 (iPhoto) can not be found?
Am I able to get these back?

A: Your photos have always been there and look at the picture the old iPhone app folder'll be there.
Try clicking the right mouse button and choose open with iPhoto and find your entire library.


text:
Q: How to move the body content of pdf report according to header height I am having two plugins where one plugin is used for designing the headers and footers for the reports and another is for writing the body content of the pdf reports.
When the height of the header increases or decreases the body content of the pdf report should move dynamically up and down according to the height of the header. Any solution on this would be very much helpful.
def custom_report_pdf
  begin
report = CustomReport.find(params[:id].to_i)
paper_margin = report.paper_margin
paper_orientation = report.paper_orientation
paper_size = report.paper_size
unless paper_size.nil?
  @page_height = paper_size[:page_height]
  @page_width = paper_size[:page_width]
end
@student_ids = []
query = []
@sorted_description =[]
params[:custom_reports].each do |key,value|
  @student_ids << key if value.to_i == 1
end
@student_ids = CustomReport.sort_by_first_name(@student_ids)
@student_ids.each do |student_id|
    # the content of tinymce description part whole thing is splitted then it is made loop one by one as word
    description = report.description.split
    description.each_with_index do |word, i|
      @value = CustomReport.match_string(query, word, student_id, i, params[:id]).to_s
    end
    @sorted_description << @value
    query = []
  end
  #      if defined? HeaderFooterDesign == 'constant' and HeaderFooterDesign.first.config_key == true
  #        render :pdf => "#{report.name}"
  #      else
  render :pdf => "#{report.name}",
    :orientation => paper_orientation.nil? ? 'Portrait' : paper_orientation,
    :page_height => @page_height.nil? ? '27.94cm' : @page_height+"cm",
    :page_width => @page_width.nil? ? '21.59cm' : @page_width+"cm",
    :margin => paper_margin.nil? ? {:top => '3.2cm',:bottom => '2cm', :left => '2cm',:right => '2.1cm'} : {:top => (paper_margin[:top].to_f+ 3.5).to_s + "cm",:bottom => (paper_margin[:bottom].to_f + 0.2).to_s + "cm", :left => paper_margin[:left]+"cm",:right => (paper_margin[:right].to_f).to_s + "cm" }
  #      end
rescue Exception => e
  Rails.logger.info "Exception in design_custom_reports controller, custom_report_pdf action"
  Rails.logger.info e
  flash[:notice] = "Sorry, something went wrong. Please inform administration"
  redirect_to :action => :index
end

end

A: See below example, how to use bounding_box
pdf_file_path = "#{Rails.root}/tmp/#{pdf_file_name}.pdf"
Prawn::Document.generate(pdf_file_path, :top_margin => 0, :bottom_margin => 0) do
  font "Helvetica"
  repeat :all do
    # header
    bounding_box [bounds.left, bounds.top], :width => bounds.width, :height => 100 do
      move_down(5)
      text_box "103, 1st Floor, Bldg #42, Jasminium,", :align => :right, :size => 8, :at => [bounds.left, bounds.top - 10]
      text_box "link road extension,", :align => :right, :size => 8, :at => [bounds.left, bounds.top - 20]
      text_box "Bhujbal complex,", :align => :right, :size => 8, :at => [bounds.left, bounds.top - 30]
      text_box "pune", :align => :right, :size => 8, :at => [bounds.left, bounds.top - 40]
      image "#{Rails.root}/public/images/logo.png", :position => :left, :scale => 0.2
      stroke_horizontal_rule
    end

    # footer
    bounding_box [bounds.left, bounds.bottom + 65], :width  => bounds.width, :height => 80 do
      stroke_horizontal_rule
      move_down(5)
      image "#{Rails.root}/public/images/stamp.jpg", :at => [bounds.left, bounds.top - 2], :scale => 0.7
      text "www.google.com", :align => :center
    end
  end
    summary_cells = [[make_cell(:content => "", :background_color => "6E6E6E", :text_color => "FFFFFF"),
      make_cell(:content => "Overview", :background_color => "6E6E6E", :text_color => "FFFFFF"),
      make_cell(:content => "Status", :background_color => "6E6E6E", :text_color => "FFFFFF"),
      make_cell(:content => "Flag", :background_color => "6E6E6E", :text_color => "FFFFFF"),
      make_cell(:content => "Approval Type", :background_color => "6E6E6E", :text_color => "FFFFFF")]]
    @students.each do |b|
      color = case b.status
      when "Active" then "3BA936"
      when "InActive" then "C80000"
      when "InProgress" then "FA9632"
      else "6E6E6E"
      end
      students << b.documents.not_auto.visible
      summary_cells << [b.class.to_s, b.overview, b.completion_status, make_cell(b.status.titleize, :text_color => color), b.linked_task.try(:means_of_approval)]
    end
end


text:
Q: Serving UI in express.js after logic I understand how to return a file using express with:
res.sendFile(path.join(__dirname, 'fileName.html'))

And I understand how to serve up a folder using:
app.use('/customAPI', express.static('folderName'));

using the documentation here.
The folder with the UI is created using angular 4 build. So, it all goes into one folder creating a index.html and a bunch of *.bundle.html files.
However, I don't understand how to serve up a the UI after doing some logic. For example:
router.get("/", function (req, res) {
    let myParam = req.query.whatever;
    if (whatever) {
        res.redirect('//google.com'); //this works fine
    }
    else {
        //I don't know what to do here
        app.use("/somePath", 'dist'); //won't work because what do I put in "somePath"?
        res.sendFile(path.join(__dirname, '../../dist/index.html'));
        //^ this only serves up the file but fails because it can't find the library files that index.html needs to load.
    }
});

I've tried going down the road of trying to use res.render but I'm not 100% sure if that is what I'm looking for.
Question: How do I serve up a folder containing all ui information correctly

A: When you serve a specific path these are sending the content only for that path, for example an HTML with the interface, the HTML file can make calls to other files, like CSS, JS etc ...
You need to serve the static files in a public folder
app.use('/static', express.static(path.join(__dirname, 'public')))

All files in the static folder will be served in the url /static/filename
In the html of the path, you must include the resources of the static folder that you need


text:
Q: MacOS: How to mount volumes using docker-compose.yml and Dockerfile? My project's folder structure looks like:
+ cython_test/
    + ny/
        + nyc/
            + docker-compose.yml
            + Dockerfile
            + pigeon.py
            + data/
                + temps.txt

The docker-compose.yml:
version: '2.1'
services:
  worker:
    build: .
    volumes:
      - ./:/opt

The Dockerfile:
FROM python:3.6-alpine3.10

RUN sleep 5000

To get the container started, I do:
docker-compose -f "ny/nyc/docker-compose.yml" up -d --build

And I get the output:
Alexs-MacBook-Pro:cython_test alexvissup$ cd "/Users/alexvissup/Codes/cython_test"
Alexs-MacBook-Pro:cython_test alexvissup$ docker-compose -f "ny/nyc/docker-compose.yml" up -d --build
Creating network "nyc_default" with the default driver
Building worker
Step 1/2 : FROM python:3.6-alpine3.10
 ---> 92a867c54c0f
Step 2/2 : RUN sleep 5000
 ---> Running in fdeb933e6cfc

When I exec into the container I expect to go into /opt and see everything inside my local nyc folder, but it's empty.
I'm required to specify the volumes in the docker-compose.yml. Is this possible?
What am I doing wrong?

A: Docker volume will be created when the containers are created and not during the build time. Your docker file is execting a sleep command for a long time, therefore the docker-compose does not create the container until the sleep functions completely finish. (I don't see why you need the sleep at all, it is not a common thing in Docker world)
The second issue that you have here is that you do not define the container command nether in the docker-compose nor in the Dockerfile. You must define one in order to keep the container running after building the docker image.
You can try to use the below command to fix the issue (You may need to install python dependencies also )
FROM python:3.6-alpine3.10
# RUN pip install flask -- if you need to have some dependencies
WORKDIR /opt
ENTRYPOINT ["python", "pigeon.py"]


text:
Q: Google Drive API Android/Java - files list always empty The problem - I try to list the files/folders in google drive with their API from my android app but the list is always empty.
1. I know I'm connected. The listFiles method is called from the onConnected callback of the GoogleApiClient object.
2. The MetadataBuffer object is not null.
3. Please please help
private void listFiles() {

    DriveFolder folder = Drive.DriveApi.getRootFolder(googleApiClient);
    folder.listChildren(googleApiClient).setResultCallback(metadataResult);
}

final private ResultCallback<DriveApi.MetadataBufferResult> metadataResult = new
        ResultCallback<DriveApi.MetadataBufferResult>() {
            @Override
            public void onResult(DriveApi.MetadataBufferResult result) {

                if (!result.getStatus().isSuccess()) {
                    Log.d(TAG, "Problem while retrieving files");
                    return;
                }

                MetadataBuffer mdb = result.getMetadataBuffer();
                for (Metadata md : mdb) {
                        Log.d(TAG, md.getTitle());
                        Log.d(TAG, md.getAlternateLink());
                }

                // Also tried this way
                Iterator<Metadata> iterator = result.getMetadataBuffer().iterator();
                while(iterator.hasNext()) {
                    Log.d(TAG, iterator.next().getTitle());
                }
            }
        };

A: So in case someone needs this in future,
Apparently you will see only the files in folders that your app created. That's why when you login for the first time and try to list the files you won't see anything.
Thanks @seanpj for the heads up.
P.S. Maybe it's a permissions thing though...


text:
Q: Keychain access and wildcard signing between developer accounts I have a bit of an unusual problem. I have a client who is using keychain access to store login credentials for their iOS apps. When I re-sign one of their apps to my provisioning profile (on my own developer account) it, breaks keychain access, which is what I'd expect.
I was wondering if there is a way for me to re-sign their app with my own wildcard provisioning profile and still allow keychain access. I get that it would be easier to just have them add a few of my devices to their portal, so I wouldn't need to re-sign, but they have already used all 100 slots.
I assume that I'll need a custom entitlements file, but I'm not totally sure what changes to make.
Thanks for any help you can give me!
-Jason

A: Access to keychain element is restricted by the Team ID. This is a 10 character string that can be found on the Member Center here https://developer.apple.com/membercenter/index.action#accountSummary. If you look at the provisioning profile in a text editor you will see an element like this
<key>keychain-access-groups</key>
<array>
    <string>XXXXXXXXXX.*</string>
</array>

The XXXXXXXXXX corresponds to your Team ID. If the app is trying to store anything into the keychain with a different prefix, it will not work.


text:
Q: How to install nodemon Nodejs on macOS? nodemon keeping show : command not found Currently I already install nodemon with command npm install -g nodemon. And I got Permissions issue, so I do command with sudo npm install -g nodemon and i did it. But when I make "nodeman" command was always show nodemon: command not found.

A: According to this, Create a new directory to store your global packages. So that there is no permission issue.
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'

Edit your .profile or .bash_profile to add the new location to your PATH:
export PATH=~/.npm-global/bin:$PATH

Then install the package without sudo:
npm install -g nodemon

A: If for any reasons you are unable to set a Global PATH then under your current project directory, run
npm install nodemon --save-dev

then under "scripts" in your package.json file, add "start": "nodemon app.js" like this -
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
}

then run
npm start

A: If you want to install global nodemon use SUDO, because if you need to be a global user, you need to be a super user

A: If you need to install nodemon globally on mac OS, try
sudo npm install -g nodemon.
Then you'll have to enter your password. Once the installation is completed successfully, run
nodemon -v
to check nodemon version on terminal.

A: The other answer is correct but my advice is that it's better to not install packages globally if you can help it, this makes your application self sufficient without relying on the environment and avoids versioning issues between applications.
npm install -D nodemon

You can now execute nodemon from scripts in package.json:
"scripts": {
   "start": "nodemon src/index.js"
}

Or you can execute it yourself using npx if you're in that directory from the terminal. npx executes local scripts, e.g. npx nodemon --inspect ./src/index.js 8080

A: Just run these commands and the error will get solved.
Specially for MAC People:

*

*sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

*Enter your laptop password

*npm install i -g nodemon or npm install -g nodemon
All set .....


text:
Q: Msg 8115, Level 16, State 2, Line 17 Arithmetic overflow error converting expression to data type int i am getting an error while executing below query. Please help me on this.
SELECT
    row_Date AS row_date,
    ForecastTimeGroup AS LastIntervalStartTime,
    DATEADD(ss,1799,ForecastTimeGroup) AS LastIntervalEndTime,
    DATEDIFF(mi,'01jan1900 00:00:00',DATEADD(ss,1799,ForecastTimeGroup)) AS    IntervalDurationMins,
        ReportCampaignID,
        ReportCampaignName,
    acd AS acd,
    rsv_level AS rsv_level,
SUM(abncalls) AS abncalls,
SUM(abntime) AS abntime,
SUM(acd_release) AS acd_release,
SUM(acdauxoutcalls) AS acdauxoutcalls,
SUM(acdcalls) AS acdcalls,
SUM(acdcalls_r1) AS acdcalls_r1,
SUM(acdcalls_r2) AS acdcalls_r2,
SUM(acdtime) AS acdtime,
SUM(acwincalls) AS acwincalls,
SUM(acwintime) AS acwintime,
SUM(acwoutadjcalls) AS acwoutadjcalls,
SUM(acwoutcalls) AS acwoutcalls,
SUM(acwoutoffcalls) AS acwoutoffcalls,
SUM(acwoutofftime) AS acwoutofftime,
SUM(acwouttime) AS acwouttime,
SUM(acwtime) AS acwtime,
SUM(ansringtime) AS ansringtime,
SUM(assists) AS assists,
SUM(auxincalls) AS auxincalls,
SUM(auxintime) AS auxintime,
SUM(auxoutadjcalls) AS auxoutadjcalls,
SUM(auxoutcalls) AS auxoutcalls,
SUM(auxoutoffcalls) AS auxoutoffcalls,
SUM(auxoutofftime) AS auxoutofftime,
SUM(auxouttime) AS auxouttime,
SUM(conference) AS conference,
SUM(da_abncalls) AS da_abncalls,
SUM(da_abntime) AS da_abntime,
SUM(da_acdcalls) AS da_acdcalls,
SUM(da_acdtime) AS da_acdtime,
SUM(da_acwincalls) AS da_acwincalls,
SUM(da_acwintime) AS da_acwintime,
SUM(da_acwoadjcalls) AS da_acwoadjcalls,
SUM(da_acwocalls) AS da_acwocalls,
SUM(da_acwooffcalls) AS da_acwooffcalls,
SUM(da_acwoofftime) AS da_acwoofftime,
SUM(da_acwotime) AS da_acwotime,
SUM(da_acwtime) AS da_acwtime,
SUM(da_anstime) AS da_anstime,
SUM(da_othercalls) AS da_othercalls,
SUM(da_othertime) AS da_othertime,
SUM(da_release) AS da_release,
SUM(event1) AS event1,
SUM(event2) AS event2,
SUM(event3) AS event3,
SUM(event4) AS event4,
SUM(event5) AS event5,
SUM(event6) AS event6,
SUM(event7) AS event7,
SUM(event8) AS event8,
SUM(event9) AS event9,
SUM(holdabncalls) AS holdabncalls,
SUM(holdacdtime) AS holdacdtime,
SUM(holdcalls) AS holdcalls,
SUM(holdtime) AS holdtime,
SUM(i_acdaux_outtime) AS i_acdaux_outtime,
SUM(i_acdauxintime) AS i_acdauxintime,
SUM(i_acdothertime) AS i_acdothertime,
SUM(i_acdtime) AS i_acdtime,
SUM(i_acwintime) AS i_acwintime,
SUM(i_acwouttime) AS i_acwouttime,
SUM(i_acwtime) AS i_acwtime,
SUM(i_auxintime) AS i_auxintime,
SUM(i_auxouttime) AS i_auxouttime,
SUM(i_auxstbytime) AS i_auxstbytime,
SUM(i_auxtime) AS i_auxtime,
SUM(i_availtime) AS i_availtime,
SUM(i_da_acdtime) AS i_da_acdtime,
SUM(i_da_acwtime) AS i_da_acwtime,
SUM(i_otherstbytime) AS i_otherstbytime,
SUM(i_othertime) AS i_othertime,
SUM(i_ringtime) AS i_ringtime,
SUM(i_stafftime) AS i_stafftime,
SUM(incomplete) AS incomplete,
SUM(noansredir) AS noansredir,
SUM(o_acdcalls) AS o_acdcalls,
SUM(o_acdtime) AS o_acdtime,
SUM(o_acwtime) AS o_acwtime,
SUM(phantomabns) AS phantomabns,
SUM(ringcalls) AS ringcalls,
SUM(ringtime) AS ringtime,
SUM(ti_auxtime) AS ti_auxtime,
SUM(ti_auxtime0) AS ti_auxtime0,
SUM(ti_auxtime1) AS ti_auxtime1,
SUM(ti_auxtime2) AS ti_auxtime2,
SUM(ti_auxtime3) AS ti_auxtime3,
SUM(ti_auxtime4) AS ti_auxtime4,
SUM(ti_auxtime5) AS ti_auxtime5,
SUM(ti_auxtime6) AS ti_auxtime6,
SUM(ti_auxtime7) AS ti_auxtime7,
SUM(ti_auxtime8) AS ti_auxtime8,
SUM(ti_auxtime9) AS ti_auxtime9,
SUM(ti_availtime) AS ti_availtime,
SUM(ti_othertime) AS ti_othertime,
SUM(ti_stafftime) AS ti_stafftime,
SUM(transferred) AS transferred,

    MAX(MartLoadID) AS MartLoadID
FROM VF_ATT_Mart.mart.IPThAgentIntraday_ReportCampaign_30mins ipt


text:
Q: calling cms static block on product detail page I want to call my cms static block on product detail page above price ,
I have added  the below code via admin category > custom design .
{{block type="cms/block" block_id="my_block_here"}}

Can anyone help me ,Where i goes to wrong.

A: Issue: You cannot set product details page layout from Category  >custom design tab.
For show a static block at product detail and want to set this cms block from admin .Then you need to goto  admin>Catalog>Manage Product > select any product  and Goto if it design tab and put this code
<reference name="product.info">
<block type="cms/block" name="mystaticblock" >
<action method="setBlockId"><block_id>YOUR_BLOCK_ID</block_id></action>
</block>
</reference>

As product detail page main layout template is view.phtml, and it doesn't render it child block automatically, so on catalog/product/view.phtml add those code  block by <?php echo $this->getChildHtml('mystaticblock')?> for render te block.
Note: from admin manage you can only set cms  block for one page.


text:
Q: mongodb user for ubuntu EC2 instance I am trying to install mongodb on Ubuntu EC2 instance. However, I am confused about what user the DB would run as:
If I follow: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
Then it says : "mongodb"
If I follow : http://docs.mongodb.org/ecosystem/tutorial/install-mongodb-on-amazon-ec2/
It says : "mongod"
I think it leads me to inconsistent state. There was a process running is ps output for mongodb but sudo service mongodb status or stop says: Unknown Instance.
What should be the user of mongodb?

A: The reason for the difference is that the articles describe two different versions of Linux.  For the install MongoDB on Ubuntu tutorial you are talking about Ubuntu.  If you are following the install MongoDB on Amazon EC2 tutorial then you are talking about Amazon Linux.
Ubuntu uses deb/apt based packages (which gets you the mongodb user) and Amazon Linux uses rpm/yum based packages (which gets you the mongod user).  You are using Ubuntu according to your question, hence the relevant user for you is "mongodb".
I would point out though, that this likely has nothing to do with the issue you are having with the service status or shutting it down.  That's more likely some sort of problem with the wrong PID being referenced by upstart, or possibly an issue with MongoDB starting in the first place (check your logs).
I would recommend:

*

*Stop MongoDB manually (log in with the mongo shell and issue the shutdown command)

*Start the service again, with sudo service start mongodb

*Verify that it started correctly (logs, login with the mongoshell again)

*Re-check with sudo service mongodb status


text:
Q: How do I generate random numbers in 3 lines - Linux Shell Script I would like to write a code that can generate 3 rows of 6 random numbers spaced out, which shuffle after a given time (0.5 seconds), and no new rows are created, basically 6 random numbers keep generating in 3 rows.
The code I have so far is:
echo " "

echo " "

echo " "

for i in {1..5};

do

for i in {1..1};

do

echo -ne " $(($RANDOM % 100))   $(($RANDOM % 100))   $(($RANDOM % 100))   $(($RANDOM % 100))   $(($RANDOM % 100))   $(($RANDOM % 100))\r"

done

sleep 0.5

done

However, when I try to add the second and third row to this, it doesn't seem to work the way I want it. A sample output could look like:
45 88 85 90 44 22
90 56 34 55 32 45
58 99 42 10 48 98
and between these numbers, new ones will generate, keeping only 6 columns and 3 rows. I have tried making matrix too but it didn't work for me.

A: I would recommend you to avoid using the shell for this. The shell is great for automating system administration tasks - e.g interact with files, directories, shell commands -, but it is also great to keep people away from learning a 'real' and most powerful programming language.
python, ruby or perl can help you out.
if all you have is a hammer, everything looks like a nail.
e.g ruby
def print_random_numbers(num)
  random_numbers = []
  num.times do |n|
    random_numbers << rand(100)
  end
  puts random_numbers.join(' ')
  puts
end

while true
  3.times do
    print_random_numbers(6)
  end
  sleep 0.5
end

A: I'm not sure whether I really understand your problem, but:
This gets you 6 numbers taken at random from the range 1-100
numbers=$(shuf -i 1-100 -n 6)
echo $numbers

The numbers are selected without repetition. If you want repetition, use -r.
This gives you a permutation of the numbers drawn before:
 echo $numbers | tr ' ' '\n' | shuf | xargs echo

A: I don't know if you have it finish, but continuing on from the comment, I would fill an indexed array with random values between 1-100, e.g.
#!/bin/bash

for ((i = 0; i < 18; i++)); do      ## fill array with random values
    a[i]=$(($RANDOM % 100 + 1))
done

What you would then want is a function you could call, passing the number of values in each row (so you can output a '\n' after those digits print) and then the array values as arguments to the function to read into a local array within the function (of course, you can just use the original array without worrying about passing elements as arguments, but I prefer using local values within function to preserve values in other scopes unchanged. For that your print function could be something like:
## function to print array in shuffled order, using tput for cursor control
prnarray() {
    local n=$1
    local al=( ${@:2} )
    local c=0
    for i in $(shuf -i 0-$((${#al[@]} - 1))); do
        [ "$c" -gt '0' -a $((c % n)) -eq '0' ] && printf "\n"
        printf " %3d" "${al[i]}"
        ((c++))
    done
    printf "\n"
    tput cuu 6   ## tput is used for cursor control to move back to top
}

Then you really don't need much else bu a loop to print the array, sleep for some period of time and then call prnarray again to overlay the output with a new shuffle. e.g.
tput sc     ## save cursor position

## call prnarray 3 times with 5 sec. delay between displays
declare -i c=0
while (( c < 3 )); do
    prnarray 3 ${a[@]}
    ((c++))
    sleep 5
done

tput rc     ## restore cursor position

Example Use/Output
The array will print in the same spot every 5 seconds with the same elements shuffled to different positions within the array.
$ sh randomshuf.sh
  33  30  34
  86  98  48
  94  89  80
  50  57  34
  11  45  57
  80  42  22

Give it a shot and let me know if you have any questions.
Note: to make it 3x6 change the lines:
 tput cuu 3

and
prnarray 6 ${a[@]}

With those changed your output would resemble:
$ sh randomshuf.sh
  85   9  45  14  18  16
   6  59  43  19  29  58
   7  89  18  72  29  29


text:
Q: Incorrect value of $.post. Selection in JQuery I have file delete.php witch contains
<?php
$folder = "./fak/";
$filename = $_POST['name'];
unlink($folder.$filename);
?>

and index.html file

    <button class="delete" value="1.png"> delete img </buttom>

    <button class="delete" value="2.png"> delete img </buttom>

And here is my problem, no matter which button I insert delete.php remove 1.png. When I insert button once more jQuery alert that the file 1.png don't exist.
So my problem is in selection correct value and after execute php file clear value 'name'

A: $(".delete").attr() will retrun first always, replace with
   $(".delete").click(function(){
      $.post("delete.php",
      {
        name:$(this).attr("value")
      },
      function(data, status){
        alert("data:"+ data + "\n Status:" + status)
        location.reload();
      });


text:
Q: Swift - Completed Game Center Achievements I have an 'endless' game, where the user has to get as high a score as possible. I have made some achievements, for when they reach 30, 60, 90 points, etc. However, when the user reaches those scores, no banner is shown to say that they have completed the achievement, nor is it shown as completed in Game Center.
How do I do this?
This is my code:
func checkAchievements() {
    var identifier : String? = nil
    var percentComplete : Double = 0
    switch(score)
    {
    case 30:
        identifier = "30"
        percentComplete = 100.0
    case 60:
        identifier = "60"
        percentComplete = 100.0
    case 90:
        identifier = "90"
        percentComplete = 100.0
    case 120:
        identifier = "120"
        percentComplete = 100.0
    case 150:
        identifier = "150"
        percentComplete = 100.0
    default:
        identifier = nil
    }
    if identifier != nil {
        let achievement = GKAchievement(identifier: identifier)
        achievement.showsCompletionBanner = true
        achievement.percentComplete = percentComplete
    }
}

A: I have never used the GK module but while you have instantiated a GKAchievement object, I don't see your call to report/record it with Game Center. Where is achievement.reportAchievementWithCompletionHandler: ?


text:
Q: How to capture black and white video using in iPhone
Possible Duplicate:
Recording video in Black and White
How to capture the black and white video

I am developing iPhone application. In this application i need to capture the video that video format is black and white video. I trying to solve this last one week. I don't know how solve this. If anybudy know how to capture the black and white video, here post your commands. give some example link and code also, It's needful for development.
Thanks in Advance.

A: coreimage (ios 5 or higher) have many of the video/image filters that can be configured to attain dramatic effects including the one you are looking for (b&w).
checkout the documentation for the same:
https://developer.apple.com/library/mac/documentation/graphicsimaging/Conceptual/CoreImaging/index.html


text:
Q: Using Java to query Active Directory to find available CIFS shares Here is the scenario:
I have several CIFS partitions which AD-based users can mount and use to access their files etc.
Now we have a requirement to expose this to users via Java-based Web application. So ideally when the users log in; he/she should be able to see which all CIFS partitions he has access to. This would mean that that Java application should be able to query Active Directory server via LDAP or such to identify which all CIFS partitions are available and the respective ACLs.
So the question is:

*

*Can we use LDAP(Java-based library) to query AD to find out which
users can access which CIFS shares?

*Is there any other way to do so from a Java application?

A: There's no builtin way to publish CIFS partitions, or their respective ACLs, to AD.  So you need to publish it yourself.  There's basically two options:

*

*Publish it in AD.  This requires extending the schema, i.e. creating a cIFSPartition class with two attributes, path and users.  You would then have to find a Java library that can perform LDAP queries (I see a lot of questions about Spring LDAP here).  You would probably need to make a webpage to help create and manage these cIFSPartition objects.

*Store it on the webserver.  You have lots of options here, like a text file or database.  This way, you don't have to worry about LDAP.


text:
Q: Как использовать Protocol Buffer без файлов Есть примеры где наглядно показывается как мне сохранить данные в файл и считать их, не могу понять как мне эти данные просто передать к примеру просто закрепив в посте, или просто передать этот класс в другой метод.
AddressBook.Builder addressBook = AddressBook.newBuilder();

// Read the existing address book.
try {
  addressBook.mergeFrom(new FileInputStream(args[0]));
} catch (FileNotFoundException e) {
  System.out.println(args[0] + ": File not found.  Creating a new file.");
}

// Add an address.
addressBook.addPerson(
  PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
                   System.out));

// Write the new address book back to disk.
FileOutputStream output = new FileOutputStream(args[0]);
addressBook.build().writeTo(output);
output.close();

A: Используйте не FileInputStream/FileOutputStream, а другие уместные в вашем случае потоки ввода/вывода. Например это могут быть ByteArrayInputStream и ByteArrayOutputStream:
// пишем
ByteArrayOutputStream baos = new ByteArrayOutputStream();
addressBook.build().writeTo(baos);
byte[] data = baos.toByteArray();

// читаем
AddressBook addressBook = AddressBook.parseFrom(new ByteArrayInputStream(data));

Или, например, OutputStream HTTP-соединения:
HttpURLConnection conn = (HttpURLConnection) new URL("http://...").openConnection();
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/octet-stream");
addressBook.build().writeTo(conn.getOutputStream());

Впрочем, для работы именно с байт-массивом документация предлагает готовые методы:

byte[] toByteArray();: сериализует сообщение и возвращает массив байтов.
static Person parseFrom(byte[] data);: парсит сообщение из массива байтов.

То есть что-то вроде:
// пишем
byte[] data = addressBook.toByteArray();

// читаем
addressBook = AddressBook.parseFrom(data);


text:
Q: How do we get Canonical to fix their certificates? I can't access Ubuntu Wiki I'm getting certificate errors when accessing Ubuntu Wiki. This is forcing me and I assume others who have rigorous security with their web browsing to create exceptions for these sites.
They have inappropriate certificates from GoDaddy that doesn't match their URLs. This is preventing me access (without intervention at the firewall).
Can this be fixed with a new certificate or must I (and everyone else that is security conscious) make an exception at the firewall?
Here's the error:
Untrusted Website
While trying to retrieve the URL:
https://wiki.ubuntu.com/Raid (Add exception for this URL)
Status
Hostname doesn't match
Subject
/O=*.canonical.com/OU=Domain Control Validated/CN=*.canonical.com
Issuer
/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certificates.godaddy.com/repository/CN=Go Daddy Secure Certification Authority/serialNumber=07969287
SHA1 Fingerprint
FB:99:C5:CA:22:9F:FD:A9:5D:AF:C1:EB:64:BA:AE:CC:97:DA:7F:02
MD5 Fingerprint
89:95:3B:97:07:FC:0D:3E:41:D4:92:34:42:18:61:71
Valid from
Jun 12 05:00:31 2012 GMT
Valid until
Jun 17 21:08:04 2013 GMT


text:
Q: Dynamic SQL Query To Temp Table In SSIS I am attempting to create a global temp table based off of a dynamic SQL query. I am using an execute SQL task. Thus far, whenever I execute it, the temp table is not created. Below is my script. I have altered my connection property so that it retains the connection and I set the delay validation to true in the data flow task. When I query for the global temp table, the object  doesn't exist.
        drop table if exists ##HOCExp

    DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
    SET @columns = N'';
    SELECT  @columns += N', p.' + QUOTENAME(ShortLabel)
    FROM (SELECT p.ShortLabel FROM dbo.TECHEnumValue AS p
    JOIN dbo.CNTHospitalOrClinicExposure AS o
    ON p.EnumValue = o.MPLEntityExposureBasis
    where p.MyEnumType_ID = 610 and p.ShortLabel <>''
    GROUP BY p.ShortLabel) AS x;
    SET @sql = N'
    SELECT EntityFK, ' + STUFF(@columns, 1, 2, '') + '
    into ##HOCExp
    FROM
    (
    SELECT p.ShortLabel
    , o.MPLEntityExposureUnit
    , concat(o.MyInsuredItemHospitalOrClinic_ClassID
    , o.MyInsuredItemHospitalOrClinic_ID) as EntityFK
    FROM dbo.TECHEnumValue AS p
    INNER JOIN dbo.CNTHospitalOrClinicExposure AS o ON p.EnumValue = o.MPLEntityExposureBasis
    where p.EnumValue <>0 and p.MyEnumType_ID = 610 and o.MyInsuredItemHospitalOrClinic_ID <>0
    ) AS j
    PIVOT
    (
    SUM(MPLEntityExposureUnit) FOR ShortLabel IN ('
    + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
    + ')
    ) AS p;';
    --PRINT @sql;
    EXEC sp_executesql @sql;
    select * from ##HOCExp


text:
Q: Updated spring security context not available in session on redirect Updated spring security context not available on redirect
In one of my controllers - before redirect - I execute the following code:
Credential oldCredential = (Credential) authentication.getCredentials();
            Authentication authenticationToken = new AuthenticationToken(new Credential(oldCredential.getCookieValue(), oldCredential.getPassword()),
                    updatedAccountDetails);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

When I inspect the authentication object after setting it I see the authentication context is correctly updated. After executing the code above I redirect.
After the redirect completes the security context loaded is the old one! That is: when I inspect the security context it contains not the new authentication token.
If I do the following for test - I add the  setAttributE(...) after setAuthentication(...) - I get the new authenticationToken in my session but under (obviously) a different key: test. I tried a couple of strategies for the SecurityContextHolder (MODE_THREADLOCAL, MODE_INHERITABLETHREADLOCAL, MODE_GLOBAL) although I think the default MODE_THREADLOCAL is suited for my application.
request.getSession(false).setAttribute("test", authenticationToken);

The strange thing is that if I debug and check in SecurityContextPersistenceFilter the HttpSessionSecurityContextRepository I see that after the redirect the loaded context is actually the new one! For some reason - unknown to me at this moment - this load is however at some later point replaced(?) with the old security context.

A: Make sure that you've called setAuthenticated(true) otherwise the security context is not updated.