text:
Q: ActionListeners JMenuItems - Cross classes I'm making a very poor attempt at ActionListeners here.
I'm trying to use ActionListeners to run code from in another class (AddForm.java) once a JMenuItem (in MainMenu.java) is clicked.
First, here's the code: MainMenu.java
package carparksystem;

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.awt.event.*;

public class MainMenu extends JFrame
{
public MainMenu()
{
    JMenuBar mainMenu = new JMenuBar();
    JMenu main = new JMenu("Menu");

    mainMenu.add(main);

    JMenuItem addCar = new JMenuItem("Add Car");
    addCar.setActionCommand("Add");
    main.add(addCar);
    //addCar.addActionListener();

    JMenuItem removeCar = new JMenuItem("Remove Car");
    removeCar.setActionCommand("Remove");
    main.add(removeCar);

    JMenuItem searchCars = new JMenuItem("Search Cars");
    searchCars.setActionCommand("Search");
    main.add(searchCars);

    setJMenuBar(mainMenu);

    /*
    //Add action listener for the Add Car button
    addCar.addActionListener
    (
        new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    MainMenu.windowClosed();
                }
            }
    );
    */
}
}

AddForm.java:
package carparksystem;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.JFrame;

public class AddForm extends JFrame
{
public AddForm()
{
    JLabel regNumLabel = new JLabel("Registration Number:");
    JLabel highValLabel = new JLabel("High Value?");
    JLabel largeLabel = new JLabel("Large Vehicle?");

    JRadioButton btnYesHighVal = new JRadioButton("Yes", false);
    JRadioButton btnNoHighVal = new JRadioButton("No", true);
    JRadioButton btnYesLarge = new JRadioButton("Yes", false);
    JRadioButton btnNoLarge = new JRadioButton("No", true);

    ButtonGroup highVal = new ButtonGroup();        //allows just one radio button from the group to be selected
    highVal.add(btnYesHighVal);
    highVal.add(btnNoHighVal);

    ButtonGroup largeCar = new ButtonGroup();       //allows just one radio button from the group to be selected
    largeCar.add(btnYesLarge);
    largeCar.add(btnNoLarge);

    JTextField regNumField = new JTextField();

    JButton addCar = new JButton("   Add  ");
    JButton addCancel = new JButton("Cancel");

    GroupLayout addLayout = new GroupLayout(getContentPane());      //chosen to display components in group layout
    getContentPane().setLayout(addLayout);
    addLayout.setAutoCreateGaps(true);
    addLayout.setAutoCreateContainerGaps(true);

    addLayout.setHorizontalGroup(addLayout.createSequentialGroup()
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(regNumLabel)
            .addComponent(highValLabel)
            .addComponent(largeLabel))
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(regNumField)
            .addGroup(addLayout.createSequentialGroup()
                .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(btnYesHighVal)
                .addComponent(btnYesLarge))
            .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(btnNoHighVal)
                .addComponent(btnNoLarge))))
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(addCar)
            .addComponent(addCancel))
    );

    addLayout.setVerticalGroup(addLayout.createSequentialGroup()
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
            .addComponent(regNumLabel)
            .addComponent(regNumField)
            .addComponent(addCar))
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(addLayout.createSequentialGroup()
                .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(highValLabel)
                    .addComponent(btnYesHighVal)
                    .addComponent(btnNoHighVal))
                .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(largeLabel)
                    .addComponent(btnYesLarge)
                    .addComponent(btnNoLarge)))
                .addComponent(addCancel))
        );

    setSize(375, 150);
    setTitle("Add Car");
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}

On the main frame I have drawn a series of shapes which will appear on the Frame at first. And there will be a JMenu above this with the JMenuItems Add, Remove and Search Cars in the menu.
Once these Add Remove and Search 'menu buttons' are clicked they will open the corresponding form which will allow the user to input data.
When I run my code with and without the action listeners, it runs as normal but the menus don't link at all. It's as if they have no meaning?

A: Some basic issues:

*

*If one class is to have an effect on another, it will need a reference to that other class so that it can all its methods.

*Thus if your MainMenu class needs to change the state of the AddForm class, then one way for this to occur is for MainMenu will need an AddForm field, and more importantly, that field must reference the current active AddForm object.

*An even better program structure is to use an M-V-C or Model-View-Control structure where the two views are connected by a shared model, but this may be a bit advanced for your simple program. Still if you want to follow best practices, this would be the way to go. This example shows a more simple View-Control idea that also could work.

*It's usually a bad idea for a GUI to have multiple top-level windows, which for Java means multiple JFrames. Better to have one main window and other views that can be swapped in it if need be with a CardLayout, or that can be displayed in dialog windows if need be. Please check out The Use of Multiple JFrames, Good/Bad Practice?.

For a simple non-MVC example, you could have one class calling methods of the second. Assume a JPanel that holds a JList called View1 that has a public method, addItem(String item) that adds items tot he JList's model:
public class View1 extends JPanel {
   private static final String PROTOTYPE = String.format("%50s", " ");
   private DefaultListModel<String> listModel = new DefaultListModel<>();
   private JList<String> list = new JList<>(listModel);

   public View1() {
      list.setPrototypeCellValue(PROTOTYPE);
      list.setVisibleRowCount(8);
      JScrollPane scrollPane = new JScrollPane(list);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      add(scrollPane);
   }

   public void addItem(String item) {
      listModel.addElement(item);
   }
}

Consider a second JPanel class, View2, that holds a JTextArea and a JButton and an instance of View1. This second class could then call the addItem(...) method of View1:
public class View2 extends JPanel {
   private View1 view1;
   private JTextField textField = new JTextField(10);

   public View2(View1 view1) {
      Action addItemAction = new AddItemAction();
      this.view1 = view1;
      add(textField);
      add(new JButton(addItemAction));
      textField.setAction(addItemAction);
   }

   private class AddItemAction extends AbstractAction {
      public AddItemAction() {
         super("Add Item");
         putValue(MNEMONIC_KEY, KeyEvent.VK_A);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         view1.addItem(textField.getText()); // *** calls view1's method here
         textField.selectAll();
      }
   }
}

You then could create the two classes, passing View1 into View2's constructor
  View1 view1 = new View1();
  View2 view2 = new View2(view1);

And then put one into a JFrame the other into a non-modal JDialog and display.  For instance:
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class SimpleGuis {
   private static void createAndShowGui() {
      View1 view1 = new View1();
      View2 view2 = new View2(view1);

      JFrame frame = new JFrame("SimpleGuis");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(view1);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

      JDialog dialog = new JDialog(frame, "View2", ModalityType.MODELESS);
      dialog.add(view2);
      dialog.pack();
      dialog.setLocationByPlatform(true);
      dialog.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class View1 extends JPanel {
   private static final String PROTOTYPE = String.format("%50s", " ");
   private DefaultListModel<String> listModel = new DefaultListModel<>();
   private JList<String> list = new JList<>(listModel);

   public View1() {
      list.setPrototypeCellValue(PROTOTYPE);
      list.setVisibleRowCount(8);
      JScrollPane scrollPane = new JScrollPane(list);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      add(scrollPane);
   }

   public void addItem(String item) {
      listModel.addElement(item);
   }
}

class View2 extends JPanel {
   private View1 view1;
   private JTextField textField = new JTextField(10);

   public View2(View1 view1) {
      Action addItemAction = new AddItemAction();
      this.view1 = view1;
      add(textField);
      add(new JButton(addItemAction));
      textField.setAction(addItemAction);
   }

   private class AddItemAction extends AbstractAction {
      public AddItemAction() {
         super("Add Item");
         putValue(MNEMONIC_KEY, KeyEvent.VK_A);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         view1.addItem(textField.getText());
         textField.selectAll();
      }
   }
}


text:
Q: Is there a way to run multiple spring boot context at the same time for integration test? I have many test class In my application. I use liquibase to create my database and dbunit to insert data. I use testng suit to run all test. The trouble comes when I active multithreading to run all classes together.
I want to run all test class in multithreading and each test class must have it's contexte and it's database.
I tried to create multiple spring-datasource.xml where I give the information of the database to use. So each test class has it's datasource config.
Here is the head of my test classes.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
@ContextConfiguration(locations = {
        "/config/datasource/Spring-Datasource2.xml",
    })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class })

redpajama_set_name: RedPajamaStackExchange


text:
Q: java question on creating small reports I need to do a really simple tool that prints reports.
To emphasize I want to be as simple and create it as easier as possible.
I have never looked into reports up today, and would like to ask on an advice on what libraries to use.
The tool will be really simple, i.e. a swing app that a user puts data in a JTable and saves the data.
My thought is to save the data in XML file.
What would be the best way to create a report of the data? I am planning to use multiple of these xml files to create the report.
This is just a first thought so, any design advice/guidance is also welcome
UPDATE:
A user from his machine inputs data e.g.
|Date| Name| Job |Description| Result| Reason|Cost| Current Status

In a jtable and gives many rows of this kind.  Submits to a central PC and this info is
is saved in an XML file as a single XML element.
This file can have many of these elements from 1 or N users.  Note that the input is small, and the file will be small. I.e. no high requirements
From this file I would like to get a report analytically, after some processing on the data, on a description of all these entries and sums on cost.
My only intent is to provide a nice summary in a format easy to understand/view.

A: You should have a look to the Birt project

A: ...And the winner is iReport!!

A: JTable provides a full implementation of printing for its contents, as discussed in Printing Support in Swing Components.

A: There are different Java libraries available for generating reports. The important question is, what format are you expecting the reports in ?
Jasper, which we have used extensively in our project, does a lot of cool stuff.
If you want excel, apache poi is effective.
iText does pdf generation.


text:
Q: Get Device Location - Google Assistant I am using @assistant/conversation and I need to get the user's device location in one of the handlers. I can't find any documentation about this. There used to be permission helpers in actions sdk which could be used to get the exact location, but there is no information about implementing this in the conversational actions and nothing about requesting permissions in the Fulfillment Migration Docs as well. This is what I am trying to implement. Permissions
I also found this question which is still unanswered.


text:
Q: Apply function based upon column index to data frame I am trying to apply a certain function to groups of columns from a data frame based upon a 'design' vector containing the column indices that are part of the same experimental design 'group' (i.e. replicates). My observations are the rows, my sampling points are the columns.
The design vector designates which columns should group together:
designvector <- c(rep(1,2), rep(2,3), rep(3,3), rep(4,2), rep(5,2), rep(6,2),
                       rep(7,2), rep(8,2), rep(9,2))

A small example of the data frame to which I want to apply the function is:
structure(list(`1` = c(4381L, 608L, 7648L, 458L, 350L, 203L),
`1` = c(6450L, 1389L, 4896L, 526L, 920L, 352L), `2` = c(1966L,
59L, 492L, 5291L, 1401L, 133L), `2` = c(6338L, 281L, 2649L,
4718L, 1281L, 377L), `2` = c(12399L, 578L, 3094L, 1787L,
1180L, 541L), `3` = c(9629L, 554L, 7299L, 2819L, 1314L, 497L
), `3` = c(11329L, 709L, 3720L, 2909L, 1929L, 655L), `3` = c(11319L,
535L, 5212L, 2191L, 1239L, 633L), `4` = c(7427L, 8637L, 894L,
2L, 782L, 120L), `4` = c(6748L, 9139L, 431L, 28L, 871L, 224L
), `5` = c(7125L, 11819L, 1728L, 9L, 607L, 313L), `5` = c(8651L,
11022L, 442L, 96L, 728L, 249L), `6` = c(17879L, 3402L, 319L,
6L, 1226L, 489L), `6` = c(20859L, 2648L, 463L, 10L, 1189L,
408L), `7` = c(13457L, 1124L, 9386L, 18L, 635L, 367L), `7` = c(16292L,
1732L, 6552L, 20L, 1022L, 431L), `8` = c(9035L, 5887L, 185L,
11L, 550L, 1814L), `8` = c(14831L, 5833L, 570L, 8L, 1089L,
1462L), `9` = c(22023L, 2254L, 5212L, 63L, 555L, 1254L),
`9` = c(16887L, 2491L, 4949L, 68L, 921L, 983L)), .Names = c("1",
"1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "5", "6", "6",
"7", "7", "8", "8", "9", "9"), row.names = c(NA, 6L), class = "data.frame")

However, using ddply I get an error which I do not really understand:
 ddply(abmat.sum,.(designvector),mean) gives the following output:
designvector V1
1            1 NA
2            2 NA
3            3 NA
4            4 NA
5            5 NA
6            6 NA
7            7 NA
8            8 NA
9            9 NA
Warning messages:
1: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
3: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
4: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
5: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
6: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
7: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
8: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
9: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA

I am clueless as to what I am doing wrong here.
Any suggestions using ddply or other methods then for-looping over the dataframe are welcome.

A: The problem is that abmat.sum is in the wrong form (it is "wide" rather than "long", as required by ddply).  Use melt to fix that.
library(reshape2)
abmat.sum_long <- melt(abmat.sum)
abmat.sum_long$variable <- as.numeric(abmat.sum_long$variable)

You also need to pass summarise to ddply.
library(plyr)
ddply(abmat.sum_long, .(variable), summarise, mean_value = mean(value))


text:
Q: missing required module 'SwiftShims' error generated by Xcode in project I copied my project in a running state but the copied project doesn't work for me although the actual project is running fine. When I build my copied project it gives me the following error:

I have cleared the cache and the derived data but the build still fails.
Does anyone have an idea what might cause this issue? Thanks in advance.

A: *

*Goto your project folder

*Delete the contents inside the DerivedDataXcode folder.

*Clean the project

*Run.

A: I had the same error, but the reason turned out to be having different iOS versions specified as Podfile's platform :ios and as my project's deployment target.

A: If you are using CocoaPods, open yourProject.workspace instead of yourProject.xcodeproj.

A: SwiftShims is a module defined in the standard library. It shouldn't be missing. I think it's because your DerivedData path changed, and now the compiler can't find its cache anymore.

A: If you're working with SPM, deleting the .build folder and re-running swift build solves the issue for me.

A: Did you try to remove the cache ?
rm -rf /Users/abdulrehman/Desktop/StudentMentor/DerivedData/ModuleCache/DLJPQMLQI1Q/

(I might have wrong copied your file path. So feel free to type it manually if there is nothing to remove at this path)

A: I had the same issue...and after a lot of trial and error, the following worked for me..

*

*Open your Xcode Workspace File -> Project_name(directory option on left) -> build settings -> Excluded Architectures -> Select 'Any iOS simulator SDK' and type arm64 in front of that ( for both build and release).

*Repeat the same procedure for pods

*Go to VS code and delete pod-lock and pod folder

*open podfile and Paste the following code right above "target 'name-tvOS' do" in podfile.
post_install do |installer| flipper_post_install(installer) installer.pods_project.build_configurations.each do |config| config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64" end end end
(Note: some of the code body form above may already be there. In that case replace that part with this.)

*Save it and run 'pod install' in your project's terminal.

*go back to xcode and clear build (Cmd+Shift+K) and then build your project (Cmd+B)
Hopefully it will build without any issues.. Happy Coding!

A: You may get this error if you rename the project directory.
For your reference, I was using Flutter, so
flutter clean

It was solved with.

A: I have once encountered for a private local pod, which somehow Cocoapod set the lib product name as eg. "MyLib-6c4b1003" -- with a prefix in hex.
This random hex somehow changed, but the project Other Link Flags still using the old one. I did the search to find out the references to the old hex and deleted them, run pod install and the right name will be used.
I still cannot understand why there is this random hex in the prefix, but seems like Cocoapods setting up of the project could reference to the wrong one.

A: I had a similar issue when I wanted to remove Alamofire  from Cocoapods.
then it needs to delete something:
target -- Build Settings -- Other Swift Flags
This junk of code worked for me.

A: It happened to me when I was running the release version and switched back to the Debug version with Product > Scheme > edit schemes.
Deleting derived data didn't help.
But simply doing Product > Clean Build Folder and restarting XCode fixed the issue.

A: In case you see this error in the preview canvas and the diagnostics "mtime changed":
'/var/folders/kv/t_w2wdds3m1_0lr02hcp3dgw0000gn/C/clang/ModuleCache/12TRQXIDQ8QQD/SwiftShims-2TTN5UXQBRCCQ.pcm' was built: mtime changed
Delete all .pcm files in that folder and hit try again.
The folder on your machine will be different. Copy the location and run:
rm <paste path here>/*.pcm

A: You can delete your Derived Data from Terminal by this simple command:
  rm -rf ~/Library/Developer/Xcode/DerivedData/*


text:
Q: Problem to open Multi Threading sessions with IPs I want to write script to scan subnet, take List of IPs and open Multi-Thread sessions to scan ALL those IPs in same time for open ports:
import socket
import subprocess
import sys
import threading

from netaddr import IPNetwork
from datetime import datetime

List_IP = ['33.45.48.0','33.45.48.1' ]

def subnet_port_scan(subnet):

   remoteServerIP = socket.gethostbyname(subnet)

   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   result = sock.connect_ex((subnet, 22))

   if result == 0:
       print ("Port 22 is Open", subnet)
       sock.close()
   else:
       print ("Port 22 is Closed", subnet)
       sock.close()

for function in List_IP:
   my_thread = threading.Thread(target=subnet_port_scan,args=List_IP)

   my_thread.start()

   print("Session")

my_thread.join()

Right now if i use more then 1 argument in List_IP it shows me error:
TypeError: subnet_port_scan() takes 1 positional argument but 2 were given

I need to be able to use 10-100 IPs and open sessions with all if them at same time, but i don't understand how to do that.
Please have a look and let me know what i'm missing.
Thank you

A: Yes, you're passing in each var in the list as an argument, aka 2 arguments. You can add each thread to a list, start them all, and then join them all which is generally how I use multiprocessing. Try something like this to give you an idea of how that might work--
import threading

print('start')
List_IP = ['33.45.48.0','33.45.48.1' ]
threads = []

def subnet_port_scan(subnet):
  print("thread called: ", subnet)

for x in List_IP:
  my_thread = threading.Thread(target=subnet_port_scan, args=(x,))
  threads.append(my_thread)

for y in threads:
  print('starting', y)
  y.start()

for z in threads:
  print('joining ', z)
  z.join()

print("Session")

A: Found solution:
for function in List_IP:
my_thread = threading.Thread(target=subnet_port_scan,args=(function, ))
my_thread.start()
Did not put proper arguments.


text:
Q: Magento 2.2.5 Override sales order item block not working We are working on Magento 2.2.5, override the \Magento\Sales\Block\Order\Items class method _prepareLayout but it is not working showing error.
File : etc\module.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Kh_Test" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Sales"/>
        </sequence>
    </module>
</config>

File : etc\di.xml
<preference for="Magento\Sales\Block\Order\Items" type="Kh\Test\Block\Order\Items" />

File : Kh\Test\Block\Order;
<?php

namespace Kh\Test\Block\Order;

class Items extends \Magento\Sales\Block\Order\Items
{

    protected function _prepareLayout()
    {
        $this->itemsPerPage = $this->_scopeConfig->getValue('sales/orders/items_per_page');

        $this->itemCollection = $this->itemCollectionFactory->create();
        $this->itemCollection->setOrderFilter($this->getOrder());
        $this->itemCollection->filterByParent(null);

        /** @var \Magento\Theme\Block\Html\Pager $pagerBlock */
        $pagerBlock = $this->getChildBlock('sales_order_item_pager');
        if ($pagerBlock) {
            $pagerBlock->setLimit($this->itemsPerPage);
            //here pager updates collection parameters
            $pagerBlock->setCollection($this->itemCollection);
            $pagerBlock->setAvailableLimit([$this->itemsPerPage]);
            $pagerBlock->setShowAmounts($this->isPagerDisplayed());
        }

        return parent::_prepareLayout();
    }

}
Error:

1 exception(s): Exception #0 (Exception): Notice: Undefined property:
  Qfix\Gst\Block\Order\Items::$itemCollectionFactory in
  .../app/code/Kh/Test/Block/Order/Items.php on line 12


text:
Q: Remove every third element from a list In this code piece I print the index numbers in a list.
x = '1 2 3 4 67 8'
x = list(map(int, x.split()))
# something here with modulo??
print(x)

Output:
[1, 2, 3, 4, 67, 8]
I want to output
[1, 2, 4, 67]
So the 3th element, 6th, 9th etc...

A: Iterate the list and keep index value which is not multiple of 3
[value for key,value in enumerate(x,1) if key%3!=0 ]


text:
Q: communication between two people without refresh the page message should be display each other communication between two people without refresh the page message should be display each other,but below code after refresh only display the message each other please help me any one
view page

                                    <?php foreach ($customer_to_supplier as $row) { ?>
                                        <?php
                                        if ($row->From == 'customer') {
                                            ?>

                                                    <?php if (empty($roww->buyer[0]) || empty($roww->buyer)) { ?>
                                                        <img src="<?php echo base_url(); ?>images/default.jpg" class="img-circle" width="30px" height="30px"/>

                                                    <?php } else { ?>
                                                        <img src="<?php echo 'data:image;base64,' . $roww->buyer; ?>" class="img-circle" width="30px" height="30px"/>

                                                    <?php } ?>

                                                        <?php $timestamp1 = strtotime($row->msg_sent_time); ?>
                                                        <?php $mesgtimming = date(' D-h:i A', $timestamp1); ?>

                                                            <a href="#" data-toggle="tooltip" data-placement="right" title="<?php echo $mesgtimming; ?>"><?php echo $row->message; ?>

                                        <?php } else { ?>

                                                        <?php $timestamp1 = strtotime($row->msg_sent_time); ?>
                                                        <?php $mesgtimming = date(' D-h:i A', $timestamp1); ?>

                                                            <a href="#" data-toggle="tooltip"  data-placement="left" title="<?php echo $mesgtimming; ?>"><?php echo $row->message; ?>

                                            <?php
                                        }
                                    }
                                    ?>

 <form class="form-horizontal msg_fixed_bottom send_message_form" id="data_form"  method="POST" role="form" action="#">

                                        <input type ="hidden" name="suppid" id="suppid" value="<?php echo $row->supplier_id; ?>" class="form-control" />
                                        <input type ="hidden" name="proid" id="proid" value="<?php echo $row->product_id; ?>" class="form-control" />
                                        <input type ="hidden" name="custid" id="custid" value="<?php echo $row->Customer_id; ?>" class="form-control" />

                                        <input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />

                                            <button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>

                            </form>

controller
$id = $_GET['id'];
        $data['customer_to_supplier'] = $this->Profile_model->customer_to_supply($id);
        $this->load->view('messageview', $data);

Model
public function customer_to_supply($id) {

    $this->db->select('*');
    $this->db->from('communication');
    $this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = communication.supplier_id');
    //$this->db->join('customer_otherdetails','communication.Customer_id=customer_otherdetails.customerid_fk');
    $this->db->join('customer_registration', 'communication.Customer_id=customer_registration.id');

    $array = array('communication.product_id' => $id, 'communication.supplier_id' => $this->session->id);
    $this->db->where($array);
    $this->db->order_by("msg_sent_time");
    $query = $this->db->get();
    $results = [];
    if ($query->num_rows() > 0) {

        $results = $query->result();
    }
    return $results;
}

script
 $(document).ready(function () {

                $('#data_form').on('submit', function (e) {

                    var form_data = $(this).serialize();

                    $.ajax({
                        type: "POST",
                        url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
                        data: form_data,
                        success: function (data)
                        {
                            scrollDown();
                            var message = $("#messagee").val();

//                           $('#chat_log').append('

' + message + '

');
                            $('#chat_log').append('

' + message + '

');

                            $('#messagee').val('');

                        },
                        error: function ()
                        {
                            alert('failed');
                        }
                    });

                    e.preventDefault();
                });
                scrollDown();
                function scrollDown() {
                    $('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 200);
                }
            });
        </script>

A: in your model customer_to_supply() function change with following code
public function customer_to_supply($id, $time = null, $type = null) {
    $this->db->select('*');
    $this->db->from('communication');
    $this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = communication.supplier_id');
    $this->db->join('customer_registration', 'communication.Customer_id=customer_registration.id');

    $array = array('communication.product_id' => $id, 'communication.supplier_id' => $this->session->id);
    $this->db->where($array);

    if($time != '')
        $this->db->where('unix_timestamp(msg_sent_time) >', $time, false );

    if($type != '')
        $this->db->where('From', $type );

    $this->db->order_by("msg_sent_time");
    $query = $this->db->get();
    $results = [];
    if ($query->num_rows() > 0) {

        $results = $query->result();
    }
    return $results;
}

and in your script add following code
var last_time = $("#last-time").val();
getMessages = function() {
    var self = this;
    console.log(last_time);
    var url = '<?php echo base_url(); ?>index.php/Profile_cntrl/get_message/customer/<?=$_GET['id']?>/'+last_time;
    $.getJSON(url, function(data){
        console.debug(data);
        if(data.status) {
            last_time = data.next_time;
            $("#last-time").val(data.next_time);
            $('#chat_log').append(data.message);
            scrollDown();
        }

        setTimeout(function(){
            getMessages();
        }, 5000);
    });
}
getMessages();

In your view page. You have to do some alteration as follow

*

*Add $msg_sent_time = ''; before foreach

*Add $msg_sent_time = $row->msg_sent_time; after foreach open

*Add Following html code after foreach function close

<input id="last-time" value="<?=strtotime($msg_sent_time);?>">

A: For a chat and similar needs, there is Laravel + Echo npm package
See here:
https://laravel.com/docs/5.3/broadcasting#installing-laravel-echo


text:
Q: How to set frequency, channel and bit rate while writing wav file Here is my code used to record audio and write the audioclip as wav
 public void startRec()
     {
         aud = Microphone.Start ( null, false, 10, 16000 );

     }
 public void stopRec()
     {
         Microphone.End(null);
         Save ("test",aud);
          }
 public static bool Save(string filename, AudioClip clip) {
         if (!filename.ToLower().EndsWith(".wav")) {
             filename += ".wav";
         }

         string rootpath = Application.dataPath;

         var filepath = rootpath+"/"+filename;

         Debug.Log(filepath);

         // Make sure directory exists if user is saving to sub dir.
         Directory.CreateDirectory(Path.GetDirectoryName(filepath));

         using (var fileStream = CreateEmpty(filepath)) {

             ConvertAndWrite(fileStream, clip);

             WriteHeader(fileStream, clip);
         }

         return true; // TODO: return false if there's a failure saving the file
     }

 static void ConvertAndWrite(FileStream fileStream, AudioClip clip) {

         var samples = new float[clip.samples];

         clip.GetData(samples, 0);

         Int16[] intData = new Int16[samples.Length];
         //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]

         Byte[] bytesData = new Byte[samples.Length * 2];
         //bytesData array is twice the size of
         //dataSource array because a float converted in Int16 is 2 bytes.

         const float rescaleFactor = 32767; //to convert float to Int16

         for (int i = 0; i<samples.Length; i++) {
             intData[i] = (short) (samples[i] * rescaleFactor);
             Byte[] byteArr = new Byte[2];
             byteArr = BitConverter.GetBytes(intData[i]);
             byteArr.CopyTo(bytesData, i * 2);
         }

         fileStream.Write(bytesData, 0, bytesData.Length);
     }

     static void WriteHeader(FileStream fileStream, AudioClip clip) {

         var hz = clip.frequency;
         var channels = clip.channels;
         var samples = clip.samples;

         fileStream.Seek(0, SeekOrigin.Begin);

         Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
         fileStream.Write(riff, 0, 4);

         Byte[] chunkSize = BitConverter.GetBytes(fileStream.Length - 8);
         fileStream.Write(chunkSize, 0, 4);

         Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
         fileStream.Write(wave, 0, 4);

         Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
         fileStream.Write(fmt, 0, 4);

         Byte[] subChunk1 = BitConverter.GetBytes(16);
         fileStream.Write(subChunk1, 0, 4);

         UInt16 two = 2;
         UInt16 one = 1;

         Byte[] audioFormat = BitConverter.GetBytes(one);
         fileStream.Write(audioFormat, 0, 2);

         Byte[] numChannels = BitConverter.GetBytes(channels);
         fileStream.Write(numChannels, 0, 2);

         Byte[] sampleRate = BitConverter.GetBytes(hz);
         fileStream.Write(sampleRate, 0, 4);

         Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2
         fileStream.Write(byteRate, 0, 4);

         UInt16 blockAlign = (ushort) (channels * 2);
         fileStream.Write(BitConverter.GetBytes(blockAlign), 0, 2);

         UInt16 bps = 16;
         Byte[] bitsPerSample = BitConverter.GetBytes(bps);
         fileStream.Write(bitsPerSample, 0, 2);

         Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
         fileStream.Write(datastring, 0, 4);

         Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
         fileStream.Write(subChunk2, 0, 4);

         fileStream.Close();
     }

I have used the script from this link https://gist.github.com/darktable/2317063 to save audio file. The above code records a wav file and save but when we try to play it back the audio quality and modulation of recorded voice is changed but it plays the recorded one.
I need to convert this wav file to base 64 and pass it it to ispeech api but it says as bad audio data. so we contacted the support team of ispeech they said us to set sample rate = 16khz bit rate = 16 bit channel = mono
But I tried to set these values but couldn't able set in this code Iam new to unity and c# so any help to solve this thanks in advance.


text:
Q: How to check if still connected to the network set by setProcessDefaultNetwork() I have the following code that sets the default network of my internet connection.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    NetworkCallback networkCallback = new NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            boolean result = ConnectivityManager.setProcessDefaultNetwork(network);
            Log.d(TAG, "success? " + result);
        }
    };
    NetworkRequest networkRequest = builder.build();
    connMgr.requestNetwork(networkRequest, networkCallback);
    connMgr.registerNetworkCallback(networkRequest, networkCallback);
}

This works properly. However, later on, when I check using the following code:
ConnectivityManager connMgr = (ConnectivityManager)
    context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfoMobile =
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

networkInfoMobile.isConnected();  // returns false!

This always returns false. What am I doing wrong?

A: What I did is I saved the network provided by onAvailable() callback. Then later, I checked the connectivity thru:
NetworkInfo networkInfo = connMgr.getNetworkInfo(networkFromOnAvailable);
networkInfo.isConnected();

Cheers!


text:
Q: Trigger NavigationLink through tap on Annotation in Mapkit I would like to trigger a NavigationLink through a tap on a Annotation in Mapkit. I am able to set a bool, that a certain annotation was tapped, but i never was able to call a SwiftUI View through it.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            guard !(annotation is MKUserLocation) else {
                return nil
            }

            let identifier = "Annotation"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

            if annotationView == nil {
                annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)

                annotationView?.canShowCallout = true

                annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            } else {
                annotationView?.annotation = annotation
            }

            return annotationView
        }

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
            let selectedAssistance = self.parent.assistances.first {
                    $0.location.location?.coordinate == view.annotation?.coordinate
            }

            guard selectedAssistance != nil else {
                return
            }

            self.parent.selectedAssistance = selectedAssistance?.serverId ?? ""
            self.parent.presentSheet = true
        }

A: I made it, by calling my own MapView in a ZStack, and placed a NavLink behind it, which is active on a Binding


text:
Q: Accessing Kivy layout size in kvlang I have the following code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class TestGUI(BoxLayout):
    pass

class TestApp(App):
    def build(self):
        return TestGUI()

if __name__ == '__main__':
    TestApp().run()

and the corresponding .kv file:
#:kivy 1.9.1

<TestGUI>:
    temp_size: (0.5 * x for x in self.size)
    canvas.before:
        Color:
            rgba: (1, 0, 0, 1)
        Rectangle:
            size: self.temp_size

The code does not run, throwing:
TypeError: 'NoneType' object is not iterable

due to the last line of code in the kv file. It seems that self.size is not initialized when temp_size is declared, but this raises a few questions.

*

*Why am I allowed to iterate through self.size when declaring temp_size if it is a NoneType object?

*Also, why does the code work perfectly fine when I replaces the last line with size: (0.5 * x for x in self.size) instead of using a variable?

*Also, how can I circumvent this issue and assign variables based on the value of self.size?

A: What happens here is basically this:
[x for x in None]

and why is it like that you can read in this bug report. It's because the canvas isn't available yet and the properties seem to be calculated after it's created, therefore - if no canvas, then value == garbage.
To fix it you have to do it in the canvas itself like this and not outside in a property, because the canvas is built first:
<TestGUI>:
    canvas.before:
        Color:
            rgba: (1, 0, 0, 1)
        Rectangle:
            size: (0.5 * x for x in self.size)

I'm not sure what do you mean by the last question, though I think it might be either using properties after the canvas is already available, or using values from Config if you intend to use Window and not Widget size, or set the property in __init__ and use it later in kv.
The latter one might be the best thing for you, but don't forget to:

*

*initialize with some values (ListProperty([0, 0])) otherwise the Rectangle will just kill the app

*use super(), for inheritance reasons

Example:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty
Builder.load_string('''
<TestGUI>:
    canvas.before:
        Color:
            rgba: (1, 0, 0, 1)
        Rectangle:
            size: self.temp_size
''')

class TestGUI(BoxLayout):
    temp_size = ListProperty([0, 0])

    def __init__(self, **kwargs):
        super(TestGUI, self).__init__(**kwargs)
        print(self.size)
        self.temp_size = [0.5 * x for x in self.size]

class TestApp(App):
    def build(self):
        return TestGUI()

if __name__ == '__main__':
    TestApp().run()


text:
Q: Align TextView inside an image Background of shape Rectangle in different screen sizes I want to align a textview inside a rectangular image in away that it works perfectly in every screen size and in different density screens.
you can see that in the link provided below that "COMMITMENT" is going out of the rectangular box.
I tried layout_marginTop but it only works on a particular device. alignment changes if the device is changed.
Suggest me some solution:
http://justlikethatapps.com/Screenshot.png

A: if you want to make that text in that square box then u need to give margin and that margin must come from dimension file  ...and make different dimens file for different screen support..see this image
your main target is mdpi then first make dimens of mdpi ..if margin top is 20 for mdpi then it would be 30 for hdpi and 40 for xhdpi it works


text:
Q: Crash validating iOS receipts I released a game on the App Store, and I'm getting several crashes in the following code while verifying receipts:
-(BOOL)isTransactionAndItsReceiptValid:(SKPaymentTransaction *)transaction
{
    if (!(transaction && transaction.transactionReceipt && [transaction.transactionReceipt length] > 0))
    {
        // Transaction is not valid.
        return NO;
    }

    // Pull the purchase-info out of the transaction receipt, decode it, and save it for later so
    // it can be cross checked with the verifyReceipt.
    NSDictionary *receiptDict       = [self dictionaryFromPlistData:transaction.transactionReceipt];
    NSString *transactionPurchaseInfo = [receiptDict objectForKey:@"purchase-info"];

    ...

The issue is that receiptDict is not a NSDictionary, so the code crashes down the road.  How can this be? Is there some other form the transaction.transactionReceipt can take? An error?
It's happen very rarely, maybe 1% of my users that try and buy something? Is this result of people hacking it?
I've put a check in to make sure it's and NSDictionary, but of there is a deeper issue, I'd like to find that.

A: So as developer.apple states

The contents of this property are undefined except when
  transactionState is set to SKPaymentTransactionStatePurchased.

So you should always check the transactionState of the transaction, if the transaction state is equal to SKPaymentTransactionStatePurchased then you can get the data from transactionReceipt as a dictionary.
Also consider that the data sent and received from App store is JSON format and you should use a JSON parser to retrieve it.

A: We've just added receipt validation to our projects. You can check out the ios version here: https://github.com/soomla/ios-store


text:
Q: how to stop navigator to reload view? I'm new to flutter and have a question about navigator.
I have 2 views one called Home and List. I created a drawer that is persistent in these two views. In each view I'm creating a reference to Firebase using FutureBuilder. The problem I'm running into is that every time I go to either Home or List initState is being called again. I believe the problem comes from selecting the page from the drawer. My question How can I still move to different pages without having to called InitState everytime I change screens.
title: Text('Go to page 1'),
        onTap: () {
          Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => Listdb()));

This is where I think the screen rebuilds itself. Is there a way to avoid rebuilding?
Thank you for your help!

A: You can use the AutomaticKeepAliveClientMixin to prevent reloading everytime you change page, combining with PageView for better navigation. I'll included an example here:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

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

class _MyHomePageState extends State<MyHomePage> {
  final PageController _pageController = PageController();

  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Header'),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('Item 1'),
              onTap: () {
                _pageController.jumpToPage(0);
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                _pageController.jumpToPage(1);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
      body: PageView(
        controller: _pageController,
        children: <Widget>[
          PageOne(),
          PageTwo(),
        ],
      ),
    );
  }
}

class PageOne extends StatefulWidget {
  @override
  _PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    print("From PageOne - This will only print once");
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.red,
    );
  }
}

class PageTwo extends StatefulWidget {
  @override
  _PageTwoState createState() => _PageTwoState();
}

class _PageTwoState extends State<PageTwo> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    print("From PageTwo - This will only print once");
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.blue,
    );
  }
}


text:
Q: Is there a plug-in sample for Firefox 5 written in C++? I've seen several examples, but for libraries with Gecko 1.9.2 or earlier, how do I create a plugin for Firefox 5 in C++?
The strange thing is that the official website just to gives me examples for Firefox v. 1.5 through v. 3.6 which is why I have experienced some difficulty.

A: You're better off using ctypes.


text:
Q: Generate a configuration file with an entry for each selection using Inno Setup Based on what I pick in Inno Setup, the installer should add an entry containing package name followed by , into config.ini
And extract the right premade config files (that are stored in the installer) needed for the few specific setups into the Config folder.
There are plenty of programs like Chrome/Firefox which don't need any parameters or additional configs to install.
Desired config.ini file syntax:
<package1>, <package2 /X /Y /Z>, <package 3> ...

Etc.
Where <packageX> is a string value tied to the checkboxes in the installer selection menu.
After Inno Setup completes, it should run a batch file.
Bonus points: Again.. not only output the config.ini, BUT also extract necessary premade configs set-up for the specific program into a folder C:/NKsetup/Config/

A: Add each each of your packages as a component to the Components section. Then in the Files section, you can choose what files get installed based on the components selected. For the packages list config file, you need to code that with use of the WizardIsComponentSelected function.
[Setup]
DefaultDirName=C:\some\path

[Types]
Name: "custom"; Description: "-"; Flags: iscustom

[Components]
Name: "sqlserver"; Description: "Microsoft SQL server"
Name: "chrome"; Description: "Google Chrome"
Name: "firefox"; Description: "Mozilla Firefox"

[Files]
Source: "install.bat"; DestDir: "{app}"
Source: "common-config.ini"; DestDir: "{app}"
Source: "sqlserver-config.ini"; DestDir: "{app}"; Components: sqlserver
Source: "browsers-config.ini"; DestDir: "{app}"; Components: chrome firefox

[Run]
Filename: "{app}\install.bat"; StatusMsg: "Installing..."

[Code]

procedure CurStepChanged(CurStep: TSetupStep);
var
  ConfigPath: string;
  Packages: string;
begin
  if CurStep = ssPostInstall then
  begin
    if WizardIsComponentSelected('sqlserver') then
    begin
      Packages := Packages + ',sql-server-express /X /Y /Z';
    end;
    if WizardIsComponentSelected('chrome') then
    begin
      Packages := Packages + ',chrome';
    end;
    if WizardIsComponentSelected('firefox') then
    begin
      Packages := Packages + ',firefox';
    end;

    // Remove the leading comma
    if Packages <> '' then
    begin
      Delete(Packages, 1, 1);
    end;

    ConfigPath := ExpandConstant('{app}\config.ini');
    // This is not Unicode-safe
    if not SaveStringToFile(ConfigPath, Packages, False) then
    begin
      Log(Format('Error saving packages to %s', [ConfigPath]));
    end
      else
    begin
      Log(Format('Packages saved to %s: %s', [ConfigPath, Packages]));
    end;
  end;
end;


text:
Q: Anorm with Java 8 Date/Time API I try to save timestamp field to postgresql using anorm. In scala code date/time stored as instance of java.time.Instant (someTime variable)
DB.withConnection() { implicit c =>
    SQL("INSERT INTO t_table(some_time) values ({someTime})").on('someTime -> someTime)
}

But anorm can't work with it now (Play 2.3.7).
What is the best way to make it work?

A: I believe most people are using JodaTime so might explain why its missing. If its not part of Anorm you can write your own converter.
This is untested but it would look something like below
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.TimeZone

import anorm._

object InstantAnormExtension {
  val dateFormatGeneration = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss-Z")

  implicit def rowToDateTime: Column[Instant] = Column.nonNull { (value, meta) =>
    val MetaDataItem(qualified, nullable, clazz) = meta
    value match {
      case ts: java.sql.Timestamp => Right(ts.toInstant)
      case d: java.sql.Date => Right(d.toInstant)
      case str: java.lang.String => Right(Instant.from(dateFormatGeneration.parse(str)))
      case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass) )
    }
  }
  implicit val dateTimeToStatement = new ToStatement[Instant] {
    def set(s: java.sql.PreparedStatement, index: Int, aValue: Instant): Unit = {
      if(aValue == null) {
        s.setTimestamp(index, null)
      } else {
        s.setTimestamp(index, java.sql.Timestamp.from(aValue) )
      }
    }
  }
}


text:
Q: my homepage keeps loading in IE9 this is odd, if you open my site using IE9: http://daluyon-resort.com.
My homepage keeps loading and my menu's dropdown options doesn't show but if you view other pages it works fine. All my dropdown works properly.
Don't have an idea what might be causing this problem.
Hope anyone had encountered this problem before..


text:
Q: Pass the returned value of a function as a property to json using EventSubscriber I've built an api using JMS serialize bundle. Moreover, I have an entity Ticket, which has a repository called TicketRepository. This repository contains the following method:
/**
 * @param Ticket $object
 *
 * @return string
 */
public function findByTicketDeadline($object)
{
  // some logic
}

My goal: Pass The returned value of this function to json using EventSubscriber.
Here is my class TicketSerializationSubscriber
 class TicketSerializationSubscriber implements EventSubscriberInterface
{

    /**
     * @param ObjectEvent $event
     */
    public function onPostSerialize(ObjectEvent $event)
    {
        /** @var JsonSerializationVisitor $visitor */
        $visitor = $event->getVisitor();
        $visitor->setData('ticketDeadline', 'TEST TICKET'); // WORKS

        /** @var Ticket $ticket */
        $ticket = $event->getObject();
        /** @var TicketRepository $ticketRepo */
        $ticketRepo = $event->getObject();

        $visitor->setData('TESTING', $ticketRepo->findByTicketDeadline($ticket));

//        $visitor->setData('uri',
//                $this->router->generate('ticket_api_show', [
//                    'ticketDeadline' => $ticketRepo->findByTicketDeadline($ticket)
//                ])
//        );

    }

    public static function getSubscribedEvents()
    {
        return array(
            array(
                'event' => 'serializer.post_serialize',
                'method' => 'onPostSerialize',
                'class' => 'CMS3\CoreBundle\Entity\Ticket', // if no class, subscribe to every serialization
                //'class' => 'CMS3\CoreBundle\Repository\TicketRepository', // if no class, subscribe to every serialization
                'format' => 'json', // optional format
                //'priority' => 0, // optional priority
            ),
        );
    }

}

When I passed the repository method to $visitor->setData() function, I get this error:

A: Your current code is failing because $ticketRepo = $event->getObject(); is returning the Ticket object as in the line above it, not the expected TicketRepository.
You will need to inject the EntityManager or Repository (if you have repositories as a service) into your TicketSerializationSubscriber::__construct() to retrieve the TicketRepository.
Assuming you have autowire enabled for the directory containing TicketSerializationSubscriber.
use Doctrine\ORM\EntityManagerInterface;

class TicketSerializationSubscriber implements EventSubscriberInterface
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
         $this->em = $em;
    }

    public function onPostSerialize(ObjectEvent $event)
    {
        /** @var JsonSerializationVisitor $visitor */
        $visitor = $event->getVisitor();

        $ticket = $event->getObject();
        if (!$ticket instanceof Ticket) {
            //ensure object is of expected type
            return;
        }

        /** @var TicketRepository $ticketRepo */
        $ticketRepo = $this->em->getRepository(Ticket::class);

        $visitor->setData('TESTING', $ticketRepo->findByTicketDeadline($ticket));
        //...
    }

    //...

}

If not using autowire you will need to manually add it to your TicketSerializationSubscriber service declaration arguments.
#app/config/services.yml

services:
    #...

    TicketSerializationSubscriber:
        public: false
        arguments: ['@doctrine.orm.entity_manager']
        tags:
            - { name: kernel.event_subscriber }
            #...

Be sure to clear and warmup the Symfony cache after making the changes.


text:
Q: Manually changing the route parameters leads to inconsistent user interface Here is a plunker to play with:
https://plnkr.co/edit/qTjftING3Hk2fwN36bQa?p=preview
Everything works well, except when you manually change the id parameter in the url bar, because then the projects dropdown does not show the new projectId as current project. This happens when the user saves an url as favorite link and copy/paste it into the url bar! A common case I would say!
To fix this I can listen to route.params changes in the TestsListComponent and add a check with a sharedService/EventEmitter wheter the changed id exists in that dropdown. The bool return value existsProjectId inside the TestsListComponent decides wether I should redirect to the /projects page because the id did not exist.
But honestly, redirecting from the TestsListComponent is too late at least from a user experience perspective, because the route projects/:id/tests is already activated.
How would you fix that misbehavior?
P.S.

*

*Maybe there is kind of a global params change I can listen to and check the path and its id inside the ProjectsListComponent, that would help!

*If someone knows how to edit the url bar of the plunkr in window mode to test that inconsistency please let me know how you made that readonly url bar editable... even copying the url into a new tab does not work, as I get a plunkr not found error... =>
ANSWER

*

*Load the plunkr and activate window mode

*In window mode copy/paste the url into a new tab

*When that is the pasted url: https://run.plnkr.co/LhwcQjzWHsRUda8H/projects/1/schoolclasses

*Make it that url:
https://run.plnkr.co/LhwcQjzWHsRUda8H/#/projects/1/schoolclasses

*and change param:
https://run.plnkr.co/LhwcQjzWHsRUda8H/#/projects/2/schoolclasses

*If you dont add the hash then you get a not found 404.

A: There is no global params change one can subscribe to.
One approach is to locate the route and its params starting from the root router:
console.log('router', this.router.routerState.root.firstChild.firstChild && this.router.routerState.root.firstChild.firstChild.snapshot.params);

This can be done within this.router.events.subscribe((val) => { or within a router guard like canActivate or resolve https://angular.io/docs/ts/latest/guide/router.html#!#guards

A: Update your app.routes.ts file like below and use HashLocationStrategy, for reference: HashLocationStrategy
import {Routes, RouterModule} from '@angular/router';
import ProjectListComponent from './projects-list.component';
import TestsListComponent from './tests-list.component';
import OverviewComponent from './overview.component';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

export const routes: Routes = [
    { path: '', redirectTo: 'projects', pathMatch: 'full' },
    {
        path: 'projects', component: ProjectListComponent,
        children: [
            { path: ':id', redirectTo: ':id', pathMatch: 'full' },
            {
                path: ':id', component: OverviewComponent,
                children: [
                    { path: '', redirectTo: 'tests', pathMatch: 'full' },
                    { path: 'tests', component: TestsListComponent },

                ]
        ]
    }
];

export const appRoutingProviders: any[] = [
    {
        provide: LocationStrategy,
        useClass: HashLocationStrategy
    }
];

export const routing = RouterModule.forRoot(routes);

A: I'm not sure if i correctly understand your question, anyway here is my plunkr.
  this.router.events.subscribe(event => {

        if (event instanceof RoutesRecognized)
        {
          var first=event.state.root.firstChild.firstChild;
          var id = first && event.state.root.firstChild.firstChild.params['id'];
          console.debug('recognized', id);
          this.currentProject = this.projects[+id-1];

          console.log(this.currentProject);
        }
  });

Just navigate to #/projects/1/tests.


text:
Q: Issue with jQuery UI Dialog when modal is set to TRUE I'm developing an ASP.NET WebForm application with Visual Studio 2008 SP1 and C#.
I have the following ASPX page:

    <title></title>

    <form id="form1" runat="server">

        <asp:Button ID="TreeNew" runat="server" Text="Nuevo"
            OnClientClick="ShowDialog();return false;" onclick="TreeNew_Click"/>
        <asp:Label ID="Message" runat="server"></asp:Label>

All form fields are required.

            <asp:RadioButtonList ID="ContentTypeList" runat="server">
                <asp:ListItem Value="1">Text</asp:ListItem>
                <asp:ListItem Value="2">Image</asp:ListItem>
                <asp:ListItem Value="3">Audio</asp:ListItem>
                <asp:ListItem Value="4">Video</asp:ListItem>
        </asp:RadioButtonList>

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    </form>

When modal is set to true the page stars to grow (I know that because both scroll bars are getting smaller, vertical bar faster than horizontal bar).
Looking inside page source code I see that the following div is outside forms tag:

If I set modal to false, the error doesn't happen. I think the problem is that the div working as modal is outside the form.
What do you think?

A: Set this style it will solve the issue

A: I think you are right, the overlay is to fade out the rest of the page, but as you see just go in to whateer theme you are using and you could probably hack the ui-widget-overlay class to not grow as much, must say it looks very strange with the 65089 pixels height. you could try to set the max-height to maybe 100%.

A: Found this that fixed it for me in IE 8 here :
"The changing of the position CSS property for class .ui-widget-overlay from absolute to fixed corrected the scroll bar issue for us but caused a memory bleed and hanging in IE 6. I found a work around for this by doing the following in a CSS file:
.ui-widget-overlay { position: fixed; }
.ui-widget-overlay { _position: absolute; }

The first entry is used to correct the scroll bar issue in IE 8 and works fab. The second entry with the "_" is picked up in IE 6 only and sets the position back to absolute as we never had a scroll bar issue in IE 6.

A: Try doing this in the dialog's close event (before the dialog destroy()s the overlay):
div.data('dialog').overlay.$el.css({height: 0, width: 0});

I think it has something to do with the fact that the jQuery UI overlay object reuses the DIV rather than deleting it.


text:
Q: How does one get Emacs Python interpreter to work properly I find the standard Ubuntu Emacs Python interpreter not particularly good to work with. Consider this small program in Emacs:
print ['hello'] * 10000

with C-c C-p and C-c C-r with the code block marked I get a slow output in the Python interpreter window.
If I try to stop the output with C-x o C-c C-c I get a very slow response with Emacs running with close to 100% load. After some time I get KeyboardInterrupt, but then any input at the Python prompt is terrible slow. This makes Emacs Python close to useless for me to work with.
I wonder if there is any kind of setup I am missing?

A: I can confirm that Emacs in general slows down when you look at very long lines, lines >= 10,000 characters. There is no easy fix. Emacs was designed as a text editor, where source code rarely goes above 200 lines.
The "solution" is to turn a blind eye to long lines. For example, when running print ["hello"] * 10000, you can "look away" by going to the top of the buffer (M-<). The command will run much faster, in my experience it went about 10x faster by doing this.
After it's printed out all the text, Emacs is still slow because the line is still in view. A simple way to scroll it out of view is print "\n" * 50.
In general, I try to avoid printing long lines. For example, if print a happens to print out a lot, I might change it to print "\n".join(a) or print a[:10].

A: Following the suggestion of @j-f-sebastian about sys.displayhook and repr() size in the above comment here is a few attempts:
from __future__ import print_function
import sys, textwrap
sys.displayhook = lambda value: print("\n".join(textwrap.wrap(repr(value), 80))) if type(value) == list else sys.__displayhook__(value)

The above wraps lines and is still slow to show data, but after it is shown the prompt is faster to respond.
The below simply limits the output for all types:
from __future__ import print_function
import sys
sys.displayhook = lambda value: print(repr(value)[:200])

Here is a slightly more informative version (and with a longer output):
from __future__ import print_function
import sys
sys.displayhook = lambda value: print(repr(value)) if len(repr(value)) < 1000 else print("%s ..." % repr(value)[:997])

To reset:
sys.displayhook = sys.__displayhook__


text:
Q: Observable not repeating I'm trying to repeat() an action in an observable but it is not performing it more than once.
Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> e) throws Exception {
            // **** Code Here is not repeating ****
            e.onNext(pullMessagesFromServer());
        }
    })
    .repeat()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .map(new Function<String, JSONArray>() {
        @Override
        public JSONArray apply(String s) throws Exception {
            return JsonParser.parseString(s);
        }
    })
    .subscribe(new Observer<JSONArray>() {
        @Override
        public void onNext(JSONArray arr) {
            // **** Code Here is not repeating ****
        }
    });
}

What gives? Thanks! New to Rxjava and it's confusing me somewhat. :(

A: From my comment: repeat operates if the source completes. Add e.onComplete().
Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> e) throws Exception {
            // **** Code Here is not repeating ****
            e.onNext(pullMessagesFromServer());
            e.onComplete();
        }
    })
    .repeat()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .map(new Function<String, JSONArray>() {
        @Override
        public JSONArray apply(String s) throws Exception {
            return JsonParser.parseString(s);
        }
    })
    .subscribe(new Observer<JSONArray>() {
        @Override
        public void onNext(JSONArray arr) {
            // **** Code Here is not repeating ****
        }
    });
}

The reason for this is that the Observable protocol is potentially asynchronous, that is, events may arrive over time. Therefore, just because your code stopped signalling events, the library can't know there won't be any further events. You have to be explicit about indicating no more values will be emitted when using create(). Generally, you can use other factory methods such as fromCallable that will make sure a single generated value will be properly signaled:
Observable.fromCallable(new Callable<String>() {
        @Override
        public String call() throws Exception {
            // **** Code Here is not repeating ****
            return pullMessagesFromServer();
        }
    })
    .repeat()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .map(new Function<String, JSONArray>() {
        @Override
        public JSONArray apply(String s) throws Exception {
            return JsonParser.parseString(s);
        }
    })
    .subscribe(new Observer<JSONArray>() {
        @Override
        public void onNext(JSONArray arr) {
            // **** Code Here is not repeating ****
        }
    });
}


text:
Q: Calling method inside timers timer Elapsedevent I want to know is it always required to put lock keyword when we are calling method inside timers elapsed to achieve thread safety of that method.
I have a code that is not using any shared variable and calling inside Elapsedevent.
Do I need to lock it or it will be fine since the threads are having their own stack.
Here is my Elapsedevent code,
void t_Elapsed(object sender, ElapsedEventArgs e)
{
    Test t = new Test();
    t.Process();
}

class Test
{
    public void Process()
    {
        // do ingsome processing using only local variables.
    }
}

A: If a method which doesn't uses shared state, that is inherently thread safe. You don't need a lock at all.


text:
Q: Using getopt() to get values passed from the command line I am writing a Python script to create directories for a given term and course. I would like to make use of the Python modules os, sys, and getopt (with both short and long form options) so that the running script would look like:
>python directory.py –t fall2013 –c cs311-400
>python directory.py –-term fall2013 –-class cs311-400

The code that I have write now looks like this:
import os
import sys
import getopt

term = ""
course = ""

options, args = getopt.getopt(sys.argv[1:], 't:c:', ['term=', 'course='])

for opt, arg in options:
    if opt in ('-t', '--term'):
        term = arg
    elif opt in ('-c', '--course'):
         course = arg

After this, I have a function that takes in the term and course an uses os.mkdir and such:
def make_folders(term, course):
    if not os.path.isdir(term + course):
        os.mkdir(term + course)
        path = os.path.join(term + course, "assignments")
        os.makedirs(path)

        path = os.path.join(term + course, "examples")
        os.makedirs(path)

        path = os.path.join(term + course, "exams")
        os.makedirs(path)

        path = os.path.join(term + course, "lecture_notes")
        os.makedirs(path)

        path = os.path.join(term + course, "submissions")
        os.makedirs(path)

make_folders(term, course)

For some reason, the folder that gets made only has a name that represents the term rather than both the term and the course. I feel like this might have something to do with my use of getopt, but I'm not certain. Any advice?

A: os.path.join is a clever function. Just pass as many folders as you need:
>>> import os
>>> os.path.join("first", "second", "third")
'first/second/third'

A: When you write term + course, Python concatenates the strings in term and course directly, before os.path.join() even sees them.  That is, if, say, term == "fall2013" and course == "cs311-400", then term + course == "fall2013cs311-400" with nothing in between.
One way around that would be to insert an explicit slash between the term and the course, as in term + "/" + course.  However, since you've presumably been instructed to use os.path.join() (which is a good idea, anyway), you can just pass all the path components you want to join to it as separate arguments and let it take care of joining them for you:
path = os.path.join(term, course, "exams")

Also, a few tips for your assignment, and for good Python coding in general:

*

*While the getopt module is not actually deprecated like rtrwalker claims in the comments, you're probably better off using argparse unless you have to use getopt for some reason (like, say, the assignment tells you to).

*Your code looks very repetitive.  Repetitive code is a "smell" that should suggest the need for a loop, perhaps like this:
dirs = ("assignments", "examples", "exams", "lecture_notes", "submissions")
for folder in dirs:
    path = os.path.join(term, course, folder)
    os.makedirs(path)

A: I'm actually in your class; at least I'm almost positive I am. Was running into this exact problem and was having trouble getting that sub-directory. A google search landed me here! Well, after a few more googles and LOTS of troubleshooting, found the answer to our problem!
os.makedirs(''+term+'/'+course+'')
path = os.path.join(''+term+'/'+course+'', "exams")
os.makedirs(path)

That should clean it up for you and give your your new directory and sub-directories! Good luck with the rest of the assignment.


text:
Q: What does degrees of freedom mean in the context of vibrations?
*

*If you have an $N$ degrees of freedom system what does this mean?

*What is the difference between a 1 and a 2 degrees of freedom system?

A: For example an object can vibrate in one dimension only (e.g $x$, thus $1$ degree of freedom).
Or an object can vibrate in 2 dimensions (e.g $x$ and $y$, $2$ degrees of freedom)
Furthermore an object can vibrate in a rotational sense, a further degree of freedom (in this case an angle lets say $\phi$, in a classical sense and not a quantum-mechanic sense).
References:

*

*http://en.wikipedia.org/wiki/Degrees_of_freedom_%28physics_and_chemistry%29

*http://en.wikipedia.org/wiki/Normal_mode

*http://en.wikipedia.org/wiki/Rotation

*http://en.wikipedia.org/wiki/Molecular_vibration

A: One degree of freedom is a straight line between 2 points. It has no width and no plane in which to vibrate. A line between 2 points involves distance which implies time. Assuming that time is a dimension a straight line requires time and a 2 dimensional plane in which to vibrate. Hence, three dimensions are required to allow the simplest of vibrations. Four dimensions allow a simple vibration to rotate, and so on up. String theory allows more complex wave functions in higher dimensions, each requiring their own manifolds (higher dimensional spaces).


text:
Q: AJAX not working on Django and returning 500 Error I'm trying to send an AJAX request from my template that takes you to a url and runs the view function. However, I'm getting a 500 Error in my console. The error in Django log says: TypeError: delete_appointment() missing 1 required positional argument: 'appointment_id' My view is also using a custom decorator, all required code is below:
Decorator
def user_has_delete(func, redirect_url="Home:Deny"):
    def wrapper(request, *args, **kwargs):
        if request.user.is_anonymous:
            return redirect(redirect_url)
        if request.user.is_authenticated:
            if not request.user.is_denier:
                return redirect(redirect_url)
            else:
                return func(request, *args, **kwargs)
    return wrapper

URL Pattern
path('Vet/DenyAppointment/<int:appointment_id>', views.delete_appointment)

View
@user_has_delete
@never_cache
def delete_appointment(request, appointment_id):
    appointment = get_object_or_404(Appointments, pk=appointment_id)
    appointment.delete()
    return redirect('Dashboard')

Template Portion
{% for appointment in appointments %}

{{ appointment.fullDate }}

{{ appointment.title }}

{{ appointment.day }}

                            <button type="submit" class="theme" id='{{ appointment.id }}' onclick="deleteAppointment({{ appointment.id }})">Delete Appointment</button>

                    {% endfor %}

AJAX

A: Fixed. I wasn't sending data in my AJAX just appending the appointment id in url. Then I needed to configure my decorator to accept additional parameters.


text:
Q: Android sending push notification through .net webservices I am using following webservice for sending Push notification from Android. When I call this webservice first time, it takes so much time and push notification is not delivered on Android Device. It happens only when called from Android. It works perfectly as webservice.
[WebMethod]

    public string SendGcm(String serviceKey,String registrationId ,string message) {
        WebClient wc=new WebClient();
        wc.Headers.Add("Authorization", "key=" + serviceKey);
        NameValueCollection nameValues=new NameValueCollection
            {
                {"registration_id", registrationId},
                {"collapse_key", Guid.NewGuid().ToString()},
                {"data.payload", message}
            };

        var resp=wc.UploadValues("https://android.googleapis.com/gcm/send",
                    nameValues);

        var respMessage = Encoding.Default.GetString(resp);
                return respMessage;
    }

A: Use this - :
 public void MakeNotificationForAndroid(string DeviceToken, string Body, string Sound, string CustomFrom, string CustomeMsg)
        {
            String DeviceID = "";

            DeviceID = DeviceToken;
            WebRequest tRequest;
            tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/x-www-form-urlencoded";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", "AIzaSyBX1gD47uiVp0W_UjNxhwtVsQCNJYfg5vI"));

            String collaspeKey = Guid.NewGuid().ToString("n");
            //String postData=string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", DeviceID, "Pickup Message", collaspeKey);
            String postData = string.Format("registration_id={0}&data.message={1}&collapse_key={2}&data.sound={3}&data.type={4}", DeviceID, Body, collaspeKey, Sound, CustomeMsg);

            Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            tRequest.ContentLength = byteArray.Length;

            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse tResponse = tRequest.GetResponse();

            dataStream = tResponse.GetResponseStream();

            StreamReader tReader = new StreamReader(dataStream);

            String sResponseFromServer = tReader.ReadToEnd();

            tReader.Close();
            dataStream.Close();
            tResponse.Close();
        }


text:
Q: Can a periodic distribution have an expected value and variance? I have a continuous random variable over a circle, so that the probability density function $\rho(\theta) = \rho(\theta+2\pi)$. I should be able to calculate its expected value and standard deviation, although I may need to define them slightly differently in order to achieve the same intuitive goals. The properties I am looking for are:

*

*The circle statistics should reduce to regular flat-space statistics whenever my PDF is highly concentrated in one part of the circle (because curves locally appear like lines).

*They should transform sensibly under a coordinate shift $\rho(\theta) \rightarrow \rho'(\theta) =\rho(\theta+\phi)$, carrying $E[\rho]\rightarrow E[\rho']=E[\rho]+\phi$ and Var$[\rho]\rightarrow $Var$[\rho']=$Var$[\rho]$. We desire these properties because the angle is an arbitrary coordinate and choice of coordinate system shouldn't determine anything significant about our answers.
How should the expected value and variance be defined so that they satisfy these properties?

A: As suggested by Jim B, The $n$th moment of a circular distribution is defined as,
$$
m_n = \int_\phi^{\phi+2\pi} \rho(\theta) e^{in\theta}\, \mathrm{d\theta},
$$
where $\phi$ is any angle and the probability density $\rho$ is periodic with period $2\pi$. It is illuminating to see how these moments vary with coordinate changes. Rotating $\rho$ by an angle $\varphi$ we have,
$$
m_n' = \int_\phi^{\phi+2\pi} \rho(\theta-\varphi) e^{in\theta}\, \mathrm{d\theta} = e^{in\varphi}\int_{\phi-\varphi}^{\phi-\varphi+2\pi} \rho(\theta') e^{in\theta'}\, \mathrm{d\theta'} = e^{in\varphi}m_n
$$
Where in the last step we used the fact that periodic functions have the same integral over any range that is exactly as long as their period. It is clear that $m_0$ is real and equal to 1 for well-behaved distributions. $m_1$ has a complex argument equal to the average angle, and by $e^{i \varphi}$ transforms as we would expect with rotating coordinate systems. For $n>1$, we can conclude that the complex argument of $m_{n>1}$ cannot be meaningful as a property of $\rho$, as it is not invariant with respect to rotations.
To see how we might recover the "usual" moments from the circular moments, suppose that $\rho(\theta)$ is concentrated in a small region that we may without loss put near $\theta=0$. Expanding $e^{in\theta}$ around that point, we arrive at,
$$
 m_n \approx \sum^\infty_{j=0}\frac{(in)^j}{j!}\int_{-\pi}^{\pi} \theta^j \rho(\theta) \, \mathrm{d\theta}
$$
It is clear that the "usual" moments are all hidden together within $m_n$, summed with weights that depend on $n$. They may be isolated with polynomials of $m_n$ for many $n$, although this is not usually done.


text:
Q: Socket IO client connection status I am developing a chat app using React Native with Socket IO. When the apps goes to background, socket IO is disconnected at server side after approximately 15 seconds. When the apps comes to foreground again, I want to check see if socket io client is connected or not.
Looking through the documents I know there is a function called socket.connected like below:
socket.on('connect', () => {
  console.log(socket.connected); // true
});

and
socket.on('disconnect', () => {
  console.log(socket.disconnected); // true
});

But both these functions will not be called until socket is reconnected. After socket is reconnected, socket.connected returns true and socket.disconnected returns false. I want to check the connection status before socket tries to reconnect. How can I do that?


text:
Q: Array shuffle function not touching last element I am using this function to shuffle a 4 element array. It shuffles the first 3 elements well, shuffling them randomly, but the last element is only sometimes shuffled around with the other three.
public function shuffleArray(objA:Object, objB:Object):int{
    return Math.round(Math.random() * 2) - 1;
}

A: There's nothing really wrong with it. That's random. As mentioned, the algorithm used for Math.random() makes the difference and I don't believe the AS3 algorithm is especially good.
For testing purposes, I ran it a few times in JS and saw very similar things, where a specific index was the same quite a few times in a row. My results were showing 5-10 times in a row, the one of the indexes would be exactly the same. In a few tests, I saw the exact same result appear 11 times in a row. Running it with a higher maxValue (I tried 15) resulted in a much more random outcome, though it still had the same problems. Interestingly, bumping the iterations up seemed to break the pattern. I noticed it became slightly more random as we got higher in tries (I tried 10k).
var maxValue = 4,
    iterations = 100,
    a = [];

for (var i = 1; i <= maxValue; i++) {
    a.push(i);
}

function shuffle(a, b) {
    return Math.round(Math.random() * 2) - 1;
}

for (var i = 0; i < iterations; i++) {
    console.log(a.sort(shuffle));
}

http://jsfiddle.net/KA2tf/1/
I did test the same code in Flash (with some minor alterations for AS3, obviously) and saw mostly similar results (to be expected; I believe Flash and JS use very similar algorithms, if not the same one). There's only 24 different combinations a 4 item array can be sorted. You're bound to get repetition.


text:
Q: What is the Laurent series of $e^{z+z^{-1}}$? (Detailed derivation using Cauchy product of series) We know that:
$$e^{z+z^{-1}}=\underbrace{\left(\sum_{n=0}^{\infty}\frac{z^n}{n!}\right)\cdot\left(\sum_{m=0}^{\infty}\frac{z^{-m}}{m!}\right)}_{=:\alpha}.$$
Now I am having trouble, applying the following (Cauchy product for series) on $\alpha$:
$$\left(\sum_{i=0}^{\infty}a_iz^i\right)\cdot\left(\sum_{j=0}^{\infty}b_jz^j\right)=\sum_{k=0}^{\infty}c_k z^k, \quad c_k=\sum_{l=0}^{k}a_lb_{k-l}. \quad (\ast)$$
My approach was the following:
With ($\ast$) I find that
\begin{align}
\left(\sum_{n=0}^{\infty}\frac{z^n}{n!}\right)\cdot\left(\sum_{m=0}^{\infty}\frac{z^{-m}}{m!}\right) &= \sum_{k=0}^{\infty}c_k, \\
c_k &= \sum_{l=0}^{k}\left(\frac{1}{l!}\frac{1}{(-(k-l))!}\right) \\
&= \sum_{l=0}^{k}\frac{1}{l!(l-k)!},
\end{align}
which results in
$$e^{z+z^{-1}}=\sum_{k=0}^{\infty}\left(\sum_{l=0}^{k}\frac{1}{l!(l-k)!}\right)z^k.$$
The result I am looking for is
$$e^{z+z^{-1}}=\sum_{k=-\infty}^{\infty}\left(\sum_{l=0}^{\infty}\frac{1}{l!(l+k)!}\right)z^k, \quad \forall k\in\mathbb{N}_0.$$
What am I missing?
Also, I suspect that I have to use the following
$$\alpha=\left(\sum_{n=0}^{\infty}\frac{z^n}{n!}\right)\cdot\left(\sum_{m=-\infty}^{0}\frac{z^m}{(-m)!}\right)$$
in order to get a sum from $-\infty$ to $\infty$, but I do not know how.


text:
Q: Does this series converge? If so, to what? i was solving some integral equations and some of them gave series whose convergence am not very sure of.
Problem, if anyone can point how or to what the series converges, i will be more than glad. Am pretty sure about the calculations but then again, if someone smells something fishy, feel free, i will gladly provide the details. Below are the resultant series:
After summing up the terms i get something which looks like a power series but whose convergence am not very familiar with. the terms added are:
$f0=2*(1-e)e^x$
$f1=e^{-x}+e^{-x+1}+e^{-x+2}-e^{-x+3}$
$f2=e^{-x}-2*e^{-x+1}+2*e^{-x+3}-e^{-x+4}$
...
After obtaining more of such terms and adding the first 8
$2*(1-e)e^x - 4e^{-x+1}+16e^{-x+2}-30 e^{-x+3}+30e^{-x+4}$
$+-6e^{-x+5}-24e^{-x+6}+33 e^{-x+7}-21e^{-x+8}+$
$7e^{-x+9}-e^{-x+10}$
Is it safe for me to assume that as the number of terms grows the power of the exponential function also grows and as it is negative, the terms eventually become zero. So it becomes zero the number of functions goes towards infinity?
Thanks alot


text:
Q: Trouble writing my first APEX test class I'm very new to APEX and I'm trying to implement a feature where new contacts added contain a field called Company__c. From this field, a lookup is done to find the Account by the same name, and then associates the two.
My code is as follows:
trigger associateWithAccount on Contact (before insert) {
    if(Trigger.isBefore){
        if(Trigger.isInsert){
                Map<String, String> extMap = new Map<String, String>();
                Set<String> extIdSet = new Set<String>();
                for(Contact c : Trigger.new){
                    extIdSet.add(c.Company__c);
                }
            for(Account a : [select Id, Name from Account where Name IN :extIdSet]){
                extMap.put(a.Id, a.Name);
            }
            for(Contact c : Trigger.new){
                c.AccountID = extMap.get(c.Company__c);
            }
        }
    }
}

I have no idea if that works, I just know it doesn't give me any errors. However, I have no idea how to write the test class to attain the necessary code coverage, nor how to link the trigger and the test class. Any help?
This is my test code so far, but I keep getting an error about the Account__r (which I've never used before):
@isTest
private class TestAssociateWithAccount {
    static testMethod void myUnitTest() {
        Account testAccount = new Account(AccountID='98765', Account='test123');
        insert testAccount;
        Test.startTest();
        Contact testContact = new Contact(Company__c='test123');
        insert testContact;
        Test.stopTest();
        Contact result = [select AccountID, Account__r.Name, Account__r.Account from Contact where Company__c = 'test123' limit 1];
        system.assertEquals(testAccount.AccountID, result.Contact__c);
    }
}

Thanks!
Edit:
Current Trigger Code:
trigger associateWithAccount on Contact (before insert) {
    Map<String, String> extMap = new Map<String, String>();

    for(Contact c : Trigger.new){
        extMap.put(c.Company__c,null);
    }

    for(Account a : [select Id, Name from Account where Name IN :extMap.keySet()]){
        extMap.put(a.Name,a.ID);
    }
    for(Contact c : Trigger.new){
       ID tmp = extMap.get(c.Company__c);
       if(tmp != null)
          c.AccountID = tmp;
    }
}

Current Test Class Code:
@isTest
private class TestAssociateWithAccount {
    static testMethod void myUnitTest() {
        Account testAccount = new Account(ID='5003000000D8cuI', Name='test123');
        insert testAccount;
        Test.startTest();
        Contact testContact = new Contact(Company__c='test123');
        insert testContact;
        Test.stopTest();
         Contact result = [select AccountID, Account.Name from Contact where Company__c = 'test123' limit 1];
        system.assertEquals(testAccount.ID, result.AccountID);
    }
}

A: Not a bad start for your first test class.
believe it or not you seem to understand what A LOT of people do not.
Now to the problem....
Standard fields do NOT have __c or __r appended to them
so the query needs to be:
Contact result = [select AccountID, Account.Name from Contact where Company__c = 'test123' limit 1];
system.assertEquals(testAccount.ID, result.AccountID);

Thinking through this logically:
You are querying for the contact and want to validate the Account related to it is the same as the testaccount...
So you need to grab the same fields that you are setting in your trigger, namely the AccountID field.
Now on to your trigger:

*

*You do not need the first two IF statements. Since the scope of the trigger is only Before Insert it will only fire for that condition. You only need the first two IF statements if the scope of the trigger covers multiple conditions

*The second part of your trigger will not work because you are assigning a Name to an accountID. If the contact__c is a lookup then you can simply copy the ID
Here are two versions
If Company__c is a lookup to account
trigger associateWithAccount on Contact (before insert) {
                for(Contact c : Trigger.new){
                    c.AccountID = c.Company__c;
                }
}

If Company__c is a String Name of an Account
trigger associateWithAccount on Contact (before insert) {
    Map<String, String> extMap = new Map<String, String>();

    for(Contact c : Trigger.new){
        extMap.put(c.Company__c,null);
    }

    for(Account a : [select Id, Name from Account where Name IN :extMap.keySet()]){
        extMap.put(a.Name,a.ID);
    }
    for(Contact c : Trigger.new){
       c.AccountID = extMap.get(c.Company__c);
    }
}


text:
Q: ¿Por que el compilador de Visual C++ lanza errores incluso en las bibliotecas Standar de C++? Desarrolle un UserControl en C# y funciona muy bien, solo por un tema estético, queriendo lograr que dibuje una linea superpuesta sobre múltiples controles contenidos por mi propio control o por controles adyacentes, solución que no encontré en C# y que incluí en una Pregunta anterior , pero que no ha tenido respuesta aun. Después de mucho investigar, he logrado dibujar lineas que se superponen sobre cualquier control, incluso sobre otras ventanas el escritorio, la barra de tareas de windows, en fin sobre toda la pantalla, pero solo lo he logrado hacerlo en C++, para ello es necesario usar #include "Windows.h".
Resulta que cuando he querido convertir mi UserControl en C# a C++, en el siguiente archivo, cuando he incluido la linea indicada y al compilar aunque está incompleto, me ha generado nada menos que 53 errores, pero lo más asombroso es que ninguno de los 54 errores, son en lineas de código escritas por mi, si no en lineas de código correspondientes a:

oleid.h, error C2872: 'IDataObject' : ambiguous symbol C:\Program
Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\objidl.h;
servprov.h, error C2872: 'IServiceProvider' : ambiguous
symbol    c:\program files\microsoft visual studio
8\vc\platformsdk\include\servprov.h;
urlmon.h error C2872: 'IServiceProvider' : ambiguous
symbol    C:\Program Files\Microsoft Visual Studio
8\VC\PlatformSDK\include\urlmon.h;

Ninguno de esos errores es en los archivos escritos por mi, todos errores en archivos de las biblioteacas standars de visual C++, que las instala el propio visual studio y no creo que contengan errores, no he encontrado la explicación de por que sucede esto, me ha sucedido en Visual studio 2005 y en visual studio 2017, que son los que he usado.
#include "StdAfx.h"
#include "Buton_Contenedor.h"
#include "ERRG_PanelColapsableControl.h";
#include "resource.h"
#include "Windows.h" //Esta es la linea que incluí y generó todos lo errores
Buton_Contenedor::Buton_Contenedor(void)
{

}

Buton_Contenedor::Buton_Contenedor(ToolStripButton^ bottonComando, System::Drawing::Image^ ImageExpand,
            System::Drawing::Image^ ImageCollapse,
            Control^ Contenedor)
        {
            this->butonComand = bottonComando;
            this->contenedor = Contenedor;
            this->imageExpand = ImageExpand;
            this->imageCollapse = ImageCollapse;
        }
Buton_Contenedor::Buton_Contenedor(ToolStripButton^ bottonComando, Control^ Contenedor)
        {
            this->butonComand = bottonComando;
            this->contenedor = Contenedor;
        }

Buton_Contenedor::Buton_Contenedor(ToolStripButton^ bottonComando,
            Control^ Contenedor, System::Windows::Forms::TabAlignment alineacion)
        {
            this->butonComand = bottonComando;
            this->contenedor = Contenedor;

            HICON hMyIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDB_BITMAP1));
        }

EDICIÓN: Realice la prueba de comentar la linea //#include "Windows.h", y compile el proyecto con resultado cero error (Rebuild All succeeded), lo descomenté de nuevo y lo compilé y de nuevo generó los 53 errores; es decir incluir esa linea es la que genera los errores, algo que en teoría según la documentación, no veo por que deba ocurrir.

A: Solo cambiar el orden del encabezado del archivo  eliminó todos lo errores, a continuación como estaba en el archivo que provocó los errores.
#include "StdAfx.h"
#include "Buton_Contenedor.h"
#include "ERRG_PanelColapsableControl.h";
#include "resource.h"
#include "Windows.h" //Esta es la linea que incluí y generó todos lo errores

A continuación el orden como lo coloqué, lo que al compilar eliminó todos los errores
#include "Windows.h" //Moví esta linea al primer orden.
#include "StdAfx.h"
#include "Buton_Contenedor.h"
#include "ERRG_PanelColapsableControl.h";
#include "resource.h"

Con ese solo cambio, cambiando el orden, se eliminaron todos lo errores.


text:
Q: Can "should" be a conjunction? In The Economist, I encountered this sentence:

Fortunately, no such fate awaits Americans should the federal government shut down on October 1st.

I cannot understand how the two complete clauses — no such fate awaits Americans and *should the federal government shut down on October 1st — made up this sentence.
Is should a conjunction meaning while?


text:
Q: Set-PnPField -Values @{DependantLookupInternalName=??} Hello SharePoint Peoples,
So I am trying to figure out how to use a lot of the PnP Commands. Getting hung up on Set-PnPField. I have a column already created, and I can Get-PnPField and read it's properties. The property I am interested in editing is DependantLookupInternalNames which look to be the related columns that will be added to a given list if the Lookup column is added to a list.
I know that you can:
$siteField = Get-PnPField -Identity ThisField
if ($siteField) {
    [xml]$schemaXml = $siteField.SchemaXml
    $schemaXml.Field.ShowField = "NewShowField"
    Set-PnPField -Identity ThisField-Values @{SchemaXml=$schemaXml.OuterXml}
}

BUT the DependantLookupInternalNames does not show up in the Xml, and if I try:
$dlin = New-Object System.Collections.Generic.List[String]
$dlin.Add("OtherField1")
$dlin.Add("OtherField2")
$values = @{LookupField = "NewShowField"; DepentantLookupInternalNames = $dlin}

I get the

WARNING: No property 'DepentantLookupInternalNames' found on this field. Value will be ignored.
  WARNING: No property 'LookupField' found on this field. Value will be ignored.

The property names should be correct as that is what Visual Studio Code tells me the property names are when I break point my code there. Is there a reference library for SharePoint Object properties?
Thanks in advance!

A: You can check the FieldLookup properties, the property named "DependentLookupInternalNames".
And you can check the code of the Set-PnPField command.
https://github.com/SharePoint/PnP-PowerShell/blob/master/Commands/Fields/SetField.cs