text:
Q: ASP.NET Core 2.1 Areas routing not working I have this folder structure for my new Area

This is how I set it up in my startup:
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapRoute(
      name: "areas",
      template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    );
});

This is how I created my basecontroller
namespace App.Areas.Applications.Controllers
{
    [Area("Applications")]
    [Authorize]
    public abstract class ApplicationsBaseController : Controller
    {

    }
}

My ApplicationsController then inherits the BaseController
However, when I set a link like this

Applications

This is the link that shows up in my url https://localhost:44338/Applications?area=Applications and I get a page cannot be found.
What did I miss when setting up my Area?
EDIT:
When I add [Route("Applications/[controller]")] after my [Area("Applications")], I get this error

An unhandled exception occurred while processing the request.
  AmbiguousActionException: Multiple actions matched. The following
  actions matched route data and had all constraints satisfied:
App.Areas.Applications.Controllers.ApplicationsController.Index (App)
  App.Areas.Applications.Controllers.ApplicationsController.Create (App)
  App.Areas.Applications.Controllers.ApplicationsController.NewRole
  (App)

A: Put it before the default route... like this
app.UseMvc(routes =>
{
 routes.MapRoute(
  name: "areas",
  template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
});

A: IMO, you should create Controller folder to the specific views. Otherwise, it will fail when there are multiple controllers in the Applications area.
Anyway, for returning the views just in Views Folder, try to configure the AreaViewLocationFormats to specify the views search location.
        public void ConfigureServices(IServiceCollection services)
    {
        //rest services
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();
        services.Configure<RazorViewEngineOptions>(o =>
        {
            o.AreaViewLocationFormats.Add("/Areas/{2}/{0}" + RazorViewEngine.ViewExtension);
        });
    }

A: I realized what the issue was. In each controller, I needed to declare [Area="AreaName"] in the top before anything else so that the routing worked.
Thank you everyone for your help.

A: There is another option which does bring some clarification in terms of meta data of the code:
Using MapAreaRoute extension method in
Namespace: Microsoft.AspNetCore.Builder
Here is an example:
          routes.MapAreaRoute(
                name: "AdminArea",
                areaName: "Admin",
                template: Admin/{controller=Home}/{action=Index}/{id?}");

It is available from .NET Core 1.0
Microsoft documentation

A: you can use simple solation
Extension
public static class AreaExtension
{
    public static string AreaUrl(this IHtmlHelper helper, string action,  params string[] parameters)
    {
        var viewContext = helper.ViewContext.RouteData.Values;

        string controller = (string)viewContext["controller"],
         area = (string)viewContext["area"];
        return GenerateUrl(action, controller, area, parameters);
    }

    public static string AreaUrl(this IHtmlHelper helper, string action, string controller, params string[] parameters)
    {
        var viewContext = helper.ViewContext.RouteData.Values;

        string area = (string)viewContext["area"];
        return GenerateUrl(action, controller, area, parameters);
    }

    public static string AreaUrl(this IHtmlHelper helper, string action, string controller, string area, params string[] parameters)
        => GenerateUrl(action, controller, area, parameters);

    private static string GenerateUrl(string action, string controller, string area, params string[] parameters)
    {
        if (action == null)
            throw new ArgumentNullException(nameof(controller));
        if (controller == null)
            throw new ArgumentNullException(nameof(action));

        string urlParams = string.Empty;

        if (parameters != null && parameters.Length > 0)
            urlParams = "?" + string.Join("&", parameters);

        return "/" + string.Join("/", area, controller, action) + urlParams;
    }
}

Usage
Incluse namespase AreaExtension in _ViewImports.cshtml

Applications

This AreaExtension have 3 overload


text:
Q: Ícone personalizado não aprece no Google Maps Estou desenvolvendo um aplicativo que carrega um mapa com algumas marcações personalizadas, essas marcações funcionam perfeitamente, porém a propriedade icon não está funcionando.
Já testei colocar os ícones do próprio Google, tentei deixar o ícone padrão de marcação, porém nada funcionou
 function criaMapa(lojas) {
            var map = new google.maps.Map(element[0], {
                center: {lat: -34.397, lng: 150.644},
                zoom: 5,
                disableDefaultUI: true
            });

            var marker = [];
            var infowindow = [];

            $.each(lojas.data, function (idx, obj) {
                var latLng = new google.maps.LatLng(obj.Loja_vch_Latitude, obj.Loja_vch_Longitude);

                marker[idx] = new google.maps.Marker({
                    position: latLng,
                    title: obj.Loja_vch_Titulo,
                    animation: google.maps.Animation.DROP,
                    icon: 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png',
                    map: map
                });

                var infowindow = new google.maps.InfoWindow();

                var sBalaoConteudo = '\

\

' + obj.Loja_vch_Titulo + '
\

' + obj.Loja_vch_Descricao + '
\

';

                infowindow.setContent(sBalaoConteudo);

                google.maps.event.addListener(marker[idx], 'click', function () {
                    infowindow.open(map, marker[idx]); // click on marker opens info window
                });

            });

            var infoWindow = new google.maps.InfoWindow({map: map});

        }

        $http({
            method: 'POST',
            url: webservice + 'Loja/Listar'
        }).then(function successCallback(response) {
            criaMapa(response);
        });

Agradeço a ajuda desde já

A: O problema está em um desses dois lugares:
1- Retorno do seu webservice (variável Loja) -> Debugue e verifique exatamente o que está sendo retornado.
2- element[0] -> Verifique se essa variável realmente possui a div container do mapa
Eu substituí essas duas variáveis para testar o seu exemplo e funcionou normalmente.
Segue o exemplo funcional do que você quer:
http://jsfiddle.net/T78Hd/419/

A: Descobri o que é, o CSS da Google estava adicionando uma propriedade de max-height, impedindo que a imagem aparecesse, então tive que setar essa propriedade, ai funcionou perfeitamente.
Obrigado pela ajuda de todos

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding Gapful number in javascript

A number is gapful if it is at least 3 digits long and is divisible by the number formed by stringing the first and last numbers together.
    The smallest number that fits this description is 100. First digit is
    1, last digit is 0, forming 10, which is a factor of 100. Therefore,
    100 is gapful.

Create a function that takes a number n and returns the closest gapful
  number (including itself). If there are 2 gapful numbers that are
  equidistant to n, return the lower one.
Examples gapful(25) ➞ 100
gapful(100) ➞ 100
gapful(103) ➞ 105

so to solve this i wrote the code that loops from the given number to greater than that and find out if it is or not by
function getFrequency(array){
    var i=array
    while(i>=array){
        let a=i.toString().split('')
        let b=a[0]+a[a.length-1]
        b= +b
        if(i%b==0) return i
        i++
    }
}
console.log(getFrequency(103))

Thats fine but what if the gapful number is less than the number passed in the function ?
like if i pass 4780 the answer is 4773 so in my logic how do i check simultaneoulsy smaller and greater than the number passed ?
I am only looping for the numbers greater than the number provided in function

A: You can alternate between subtracting and adding. Start at 0, then check -1, then check +1, then check -2, then check +2, etc:

const gapful = (input) => {
  let diff = 0; // difference from input; starts at 0, 1, 1, 2, 2, ...
  let mult = 1; // always 1 or -1
  while (true) {
    const thisNum = input + (diff * mult);
    const thisStr = String(thisNum);
    const possibleFactor = thisStr[0] + thisStr[thisStr.length - 1];
    if (thisNum % possibleFactor === 0) {
      return thisNum;
    }
    mult *= -1;
    if (mult === 1) {
      diff++;
    }
  }
};
console.log(
  gapful(100),
  gapful(101),
  gapful(102),
  gapful(103),
  gapful(104),
  gapful(105),
  gapful(4780),
);

A: You could take separate functions, one for a check if a number is a gapful number and another to get left and right values and for selecting the closest number.

function isGapful(n) {
    if (n < 100) return false;
    var temp = Array.from(n.toString());
    return n % (temp[0] + temp[temp.length - 1]) === 0;
}

function getClosestGapful(n) {
    var left = n,
        right = n;

    while (!isGapful(right)) right++;

    if (n < 100) return right;

    while (!isGapful(left)) left--;

    return n - left <= right - n
        ? left
        : right;
}

console.log(getClosestGapful(25));   //  100
console.log(getClosestGapful(100));  //  100
console.log(getClosestGapful(103));  //  105
console.log(getClosestGapful(4780)); // 4773


text:
Q: Updating a Model in asp.net mvc Our project manager has asked us to refactor an app that was using the Repository Pattern (it was done using Nerddinner as example) to now use a service Layer.
My problem now is that Im not sure how to Update a Model cause the UpdateModel method is supposed to be used in the controller... whats a recomended approach to updating a model using repository pattern along with a service layer??
please help

A: I would suggest you 'hide' your current Repository Pattern inside your service layer. Data access code should not be visible to the clients of the service.
You can implement a collection of DTOs that will be returned from service layer or accepted as parameters. Those objects can be just POCOs to hold the data in a database-agnostic way.
DTOs are usually accompanied by Adapters for translation to/from your data access classes (that represent tables). This approach allows you to change database schema without changing service layer interface.
You can treat those DTOs as models in MVC, if your project is simple and data for your views matches the service layer DTOs. You can also define your models in MVC project and let controller or another set of adapters translate models into DTOs.
My preferred design includes model that are declared in MVC (Models folder) that work with strongly-typed views. UpdateModel method then works with those classes. Next controller or ModelAdapter creates an instances of Service Layer DTOs and passes them to services. DTO adapters inside services are then responsible to populate data access classes from repository pattern.


text:
Q: Cocoa - Multiple NSControls working but not NSTextFields I am new to using interface builder, and am building for Mac OS X. I have a NSTableView in my main window, the NSTableCellView subclasses of which each have their own set of controls. All of these controls (there are sliders, buttons, etc.) work properly (they call the appropriate action method when I use them), except the NSTextFields, which for some reason I can't even select or edit. The setting in IB clearly indicate they should be editable. The view controller supports the NSTextFieldDelegate protocol, and I've implemented the -(BOOL)acceptsFirstResponder method in the view controller to return YES.
Why aren't the text fields responsive?

A: For whatever the reason, turning off (row) highlighting solves the problem, as specified in https://stackoverflow.com/questions/7101237/respond-to-mouse-events-in-text-field-in-view-based-table-view. I'm not sure what to do if one wanted highlighting, however...


text:
Q: Mysql update date relative to specific column update I have a users_settings table on my db in which I store some data about the user. For some of that data I need to keep track of last modification, for example:

+--------------+-------------+
| Field        | Type        |
+--------------+-------------+
| feel         | varchar(10) |
| feel_last    | timestamp   |
| other        | varchar(10) |
| other_last   | timestamp   |
+--------------+-------------+

When I update the row with a new feel value I want to automatically write the current timestamp, is it possible to achieve this directly from mysql or I need to set the timestamp directly in the update query from my backend?

Update 1
As suggested I need to use a trigger, I written this trigger but there is some syntax error, can you help me to identify the error?
CREATE TRIGGER users_feel_last BEFORE UPDATE ON users
FOR EACH ROW BEGIN
  IF NEW.feel <> OLD.feel THEN
    SET NEW.feel_last := now();
  END IF;
END;

UPDATE 2

*

*For who use AWS RDS: the parameter "log_bin_trust_function_creators" isn't enabled by default, to create triggers it's necessary, here a small guide to set it: https://aws.amazon.com/it/premiumsupport/knowledge-center/rds-mysql-functions/

Now, thanks to James answer I created the trigger, it works well
DELIMITER $$
CREATE TRIGGER before_feel_last_update
    BEFORE UPDATE ON users
    FOR EACH ROW
BEGIN

if(old.feel<>new.feel)
then
 set new.feel_last=current_timestamp;
elseif( old.feel = NULL )
then
 set new.feel_last=current_timestamp;
end if;

END$$
DELIMITER ;

A: A trigger is not necessary in MySQL.  This functionality is happily built in.  You can define the table as:
create table users (
    . . .,
    update_datetime datetime default current_timestamp on update current_timestamp
);

You can read about this default in the documentation.

A: You can use the below trigger on BEFORE UPDATE
BEGIN

if(old.feel<>new.feel)
then

 set new.feel_last=current_timestamp;

end if;

END


text:
Q: How to open another JInternalframe from JInternalframe within the same desktop pane I have a JInternalframe (tab_items) inside a desktop pane. I want to open another JInternalframe (frm_add_items) within the same desktop pane, whenever user clicks the popup menu in tab_items. How can I do this?
//class tab_items

public class tab_items extends JInternalFrame implements MouseListener,DocumentListener,ActionListener{

    DS co= new DS ();
    JPanel panel1;
    JScrollPane pane;
    DefaultTableModel model= new DefaultTableModel();
    JTable tbl= new JTable(model);
    JLabel lbl_search;
    JTextField txt_search;
    JPopupMenu pop;
    JMenuItem mi_add,mi_edit, mi_del;

    public tab_items(){

        panel1= new JPanel();
        panel1.setLayout(null);

        //popupmenu
        pop=new JPopupMenu();
        mi_add=new JMenuItem("Add new record");
        mi_edit=new JMenuItem("Edit record");
        mi_del=new JMenuItem("Delete record");
        add(pop);

        pop.add(mi_add);
        mi_add.addActionListener(this);
        mi_add.addMouseListener(this);
        pop.add(mi_edit);
        mi_edit.addActionListener(this);

        pop.add(mi_del);
        mi_del.addActionListener(this);

      //     try{
       //         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
       //     }catch(Exception ex){}

           initcomponents();
           setVisible(true);
           setSize(700,500);
           setLocation(100,150);
           setTitle("List Of Items");
           setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

     public void initcomponents(){

     try{
         model.addColumn("ID");
         model.addColumn("Item Name");
         model.addColumn("Cost Price");
         model.addColumn("Selling Price");
         model.addColumn("Qty");

         tbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         PreparedStatement pstat=co.con.prepareStatement("Select * from tbl_items ORDER BY itemid ASC");
         ResultSet rs=pstat.executeQuery();
            while(rs.next()){
                model.addRow(new Object[]{rs.getInt(1), rs.getString(2).trim(), rs.getString(3).trim(), rs.getString(4).trim(),rs.getInt(5)});
            }
        }catch(Exception ex){}

     // SETTING COLUMN WIDTH
           TableColumnModel model=tbl.getColumnModel();
            model.getColumn(0).setPreferredWidth(50);
            model.getColumn(1).setPreferredWidth(400);
            model.getColumn(2).setPreferredWidth(100);
            model.getColumn(3).setPreferredWidth(100);
            model.getColumn(4).setPreferredWidth(50);

        // adding panel

         add(panel1);
         panel1.setBounds(0,0,800,600);

         //scrollpane initialize
        int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
        int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
        pane=new JScrollPane(tbl, v, h); //table included in scrollpane
        panel1.add(pane);
        pane.setBounds(0,50,700,400);
        tbl.addMouseListener(this);

        lbl_search= new JLabel();
        lbl_search.setIcon(new ImageIcon(getClass().getResource("/img/btn_search_up.png")));
        panel1.add(lbl_search);
        lbl_search.setBounds(5,10,25,20);

        txt_search=new JTextField();
        panel1.add(txt_search);
        txt_search.setBounds(35,10,200,20);
        txt_search.getDocument().addDocumentListener(this);
        /*
        btn_add= new JButton();
        btn_add.setIcon(new ImageIcon(getClass().getResource("/img/add-button-md.png")));
       //   btn_add.setHorizontalAlignment(SwingConstants.CENTER);
       //  btn_add.setText("Add");

        add(btn_add);
        btn_add.setBounds(665, 125, 65, 65);

        btn_edit= new JButton();
        btn_edit.setText("Update");
        add(btn_edit);
        btn_edit.setBounds(665, 200, 65, 65);

        btn_delete=new JButton();
        btn_delete.setText("Delete");
        add(btn_delete);
        btn_delete.setBounds(665, 275, 65, 65);
      */

    }

    public void mouseClicked(MouseEvent e) {}
    public void mousePressed(MouseEvent me){maybeShowPopup(me);}
    public void mouseReleased(MouseEvent me){maybeShowPopup(me);}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    private void maybeShowPopup(MouseEvent e){
        if (e.isPopupTrigger()){
            pop.show(e.getComponent(),e.getX(), e.getY());
        }
}

   public void update(DocumentEvent de){

                       Document doc=(Document)de.getDocument();
            int length=doc.getLength();
            String str=null;
            try
            {
                str=doc.getText(0,length);
            }
            catch(Exception ex)
            {
                            JOptionPane.showMessageDialog(null, "Error in retreiving Search Length\n"+ex);
            }

                        try
                {
                                        Class.forName("com.mysql.jdbc.Driver");
                                        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dstore","root","");
                    PreparedStatement pstat=con.prepareStatement("select * from tbl_items where itemid LIKe '"+str+"%' OR itemname LIKe '"+str+"%' ORDER BY itemid ASC");
                                        ResultSet rs=pstat.executeQuery();
                                        model.setRowCount(0);
                                        while(rs.next()){
                                            model.addRow(new Object[]{rs.getInt(1), rs.getString(2).trim(), rs.getString(3).trim(), rs.getString(4).trim(),rs.getInt(5)});
                                        }

                }
                catch(Exception ex)
                {
                    JOptionPane.showMessageDialog(null,"ERROR IN DOCUMENT LISTENER.\nCannot Fetch Records"+ex);
                }

    }
    public void insertUpdate(DocumentEvent de) {
    update(de);
    }
    public void removeUpdate(DocumentEvent de) {
    update(de);
    }
    public void changedUpdate(DocumentEvent de) {
    update(de);
    }

    public void actionPerformed(ActionEvent ae) {

       if(ae.getSource()==mi_add){

    //   frm_add_item ob= new frm_add_item();
    //   ob.show();
      // dp.add(ob);

       }else if(ae.getSource()==mi_edit) {

       }else {

       }

    }

}

#//class frm_main ( it contains desktop pane)#

A: Several issues raised by your fragment bear closer scrutiny:

*

*Use Action to encapsulate functionality.

*Don't extend JInternalFrame needlessly; use a factory method.

*Don't use setBounds(); use a layout manager.

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyVetoException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

//** @see http://stackoverflow.com/a/18556224/230513 */
public class Test {

    private JDesktopPane jdp = new JDesktopPane() {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(600, 400);
        }
    };
    private NewAction newAction = new NewAction("New");

    public Test() {
        createAndShowGUI();
    }

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

    private void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        newAction.actionPerformed(null);
        frame.add(jdp);
        frame.pack();
        frame.setVisible(true);
    }

    private void createInternalFrame(int x, int y) {
        final JInternalFrame jif =
            new JInternalFrame("Test" + x, true, true, true, true);
        jif.setLocation(x, y);
        JPanel jp = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(256, 128);
            }
        };
        JPopupMenu popup = new JPopupMenu();
        jp.setComponentPopupMenu(popup);
        popup.add(new JMenuItem(newAction));
        jp.add(new JButton(newAction));
        jif.add(jp);
        jif.pack();
        jdp.add(jif);
        jif.setVisible(true);
        try {
            jif.setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.err);
        }
    }

    private class NewAction extends AbstractAction {

        private int i;

        public NewAction(String name) {
            super(name);
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
            i++;
            createInternalFrame(50 * i, 50 * i);

        }
    }
}

A: You have to add later JInternalFrame in parent of first JInternalFrame. For example you add first JInternalFrame in JDesktopPane as
    JdesktopPane.add(JInternalFrame_obj1);
    JInternalFrame_obj1.toFront();

Then click on a button to add another JInternalFrame. If button is placed on other than shown JInternalFrame
    JdesktopPane.add(JInternalFrame_obj2);
    JInternalFrame_obj2.toFront();

If button is placed on JInternalFrame_obj1 add
    this.getParent().add(JInternalFrame_obj12);
    JInternalFrame_obj2.toFront();


text:
Q: If it possible connect Loadbalancers DNSname to Route53 using AWS Cloudformation template? What I trying to connect is Loadbalancer DNS name to to Route53.
Lets look on example.
Here is Loadbabancer from template in Resource:
"RestELB" : {
        "Type" : "AWS::ElasticLoadBalancing::LoadBalancer",
        "DependsOn": "AttachGateway",
        "Properties": {
            "LoadBalancerName": {"Fn::Join": ["",["Rest-ELB-", {"Ref": "VPC"}]]},
            "CrossZone" : "true",
            "Subnets": [{ "Ref": "PublicSubnet1" },{ "Ref": "PublicSubnet2" }],
            "Listeners" : [
                {"LoadBalancerPort" : "80", "InstancePort" : "80","Protocol" : "HTTP"},
                {"LoadBalancerPort" : "6060", "InstancePort" : "6060","Protocol" : "HTTP"}
            ],
        }
    },

And Here is Route53:
"ApiRecordSet" : {
      "Type" : "AWS::Route53::RecordSet",
      "Properties" : {
        "AliasTarget" :{
          "DNSName" : [
            {"Fn::Join": ["", [{"ElasticLoadBalancer": "DNSName"},"."]]}
          ],
          "EvaluateTargetHealth" : "Boolean",
          "HostedZoneId" : "String"
        },
        "HostedZoneName" : "example.net.",
        "Comment" : "A records for my frontends.",
        "Name" : "api.example.net.",
        "Type" : "A",
        "TTL" : "900",
      }
    }

Just to put {"ElasticLoadBalancer": "DNSName"} didn't work. Can someone to suggest or give me correct way to add this?
Thanks!

A: Most likely you want to get the attribute DNSName for the LoadBalancer whose reference is RestELB. So you will need something with Fn::GetAtt like (untested)
   "ApiRecordSet" : {
      "Type" : "AWS::Route53::RecordSet",
      "Properties" : {
        "AliasTarget" :{
          "DNSName" : { "Fn::GetAtt" : [ "RestELB", "DNSName" ]},
          "EvaluateTargetHealth" : "Boolean",
          "HostedZoneId" : "String"
        },
        "HostedZoneName" : "example.net.",
        "Comment" : "A records for my frontends.",
        "Name" : "api.example.net.",
        "Type" : "A"
      }
    }

A: For anyone reading this answer in 2018, I got mine working using CanonicalHostedZoneNameID and not CanonicalHostedZoneID
"MyRecordSet": {
      "Type": "AWS::Route53::RecordSet",
      "Properties": {
        "HostedZoneName" : "example.com.",
        "Name": "abc.example.com.",
        "Type": "A",
        "AliasTarget": {
            "HostedZoneId" : {"Fn::GetAtt": ["MyELB", "CanonicalHostedZoneNameID"]},
            "DNSName": {"Fn::GetAtt": ["MyELB", "DNSName"]},
            "EvaluateTargetHealth": "false"
        }
      }
    }

A: Be sure to read the CloudFormation documentation on the AWS::Route53::Recordset AliasTarget type:
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html
This is how it looks in my CloudFormation when creating an alias target for an ELB:
"Route53LoadBalancerAlias" : {
      "Type" : "AWS::Route53::RecordSet",
      "Properties" : {
          "AliasTarget" : {
          "DNSName" : { "Fn::GetAtt" : [ "ELB", "DNSName" ]},
          "EvaluateTargetHealth" : False,
          "HostedZoneId" : { "Fn::GetAtt" : [ "ELB", "CanonicalHostedZoneID" ]}
        },

For load balancers, use the canonical hosted zone ID of the load balancer. For Amazon S3, use the hosted zone ID for your bucket's website endpoint. For CloudFront, use Z2FDTNDATAQYW2. For a list of hosted zone IDs of other services, see the relevant service in the AWS Regions and Endpoints.

A: YAML for deploying a RecordSet referencing an ELB deployed in the same template.
  Route53RecordSet:
    Type: AWS::Route53::RecordSet
    Properties:
      Name: !Ref HostName
      HostedZoneId: !Ref HostedZoneId
      Type: A
      AliasTarget:
        DNSName: !GetAtt ElasticLoadBalancer.DNSName
        HostedZoneId: !GetAtt ElasticLoadBalancer.CanonicalHostedZoneIDe


text:
Q: slideUp slideDown animation error i have a div when hovered over and second image slides up and when the mouse leaves it slides back down, the animation is exactly how i want it but if you mouse in and out too quickly without the letting the animation finish it bugs and will only go to the height which you left the animation. Any help would be really helpful been looking at different blogs for days on it and i can't seem to find a fix, I'm using prototype and sciptaculous here's my code:
$('mid_about_us').observe('mouseenter',function() {
$('about_us_mo').slideDown({duration: 0.5});
});
$('mid_about_us').observe('mouseleave',function() {
$('about_us_mo').slideUp({duration: 0.5});
});

#about_us_mo{
position: absolute;
float: left;
bottom: 452px;
left: 4px;
z-index:99999;
overflow: hidden;

}

A: You need to use the Scriptaculous Effects Queue.
Your handlers are firing immediately and asynchronously as soon as the events happen, so when the events happen very quickly the handlers overlap and conflict with each other. What you really want is for them to line up in a queue and execute sequentially, as soon as the one before them is finished.
Here's a really good article about it:
http://script.aculo.us/docs/EffectQueues.html
Your code will look like this:
$('about_us_mo').slideDown({duration: 0.5, queue: 'end'});

You can also do things like create multiple effect queues if they interfere with each other. The article does a good job explaining all of it.
HTH
-Ken


text:
Q: Rails: jQuery ajax() is returning all the html The response I'm getting from the ajax is the entire html instead of the form.serialize(). Why this is happening? How do I get only the form.serialize()?
Also, I tried put json in the dataType but then the response return an error.
Thanks
/test.html.erb
<form name="boleto_form" action="" id="boleto-form">
  <input type="text" name="name" id="name" value="Guilherme Bordignon" required>
  <input type="text" name="cpf" id="cpf" value="03310782018" required>
  <input type="submit" name="buy_button" id="buy-button" value="Comprar">
</form>

test.js
dados = $('#boleto-form').serialize();

console.log(dados);

$.ajax({
    method: "POST",
    url: "payments",
    data: dados,
    dataType: "text",
    success: function(response) {
        console.log('lol' + response);
    },
    error: function(response) {
        console.log(response);
    }

});

routes.rb
  resources :orders do
    get '/payments', to: 'payments#test'
    post '/payments', to: 'payments#test'
  end

console
lol<!DOCTYPE html>

    <title>Mypg</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="QKESaecu5iy7gzgqYlGpkns5UUPaoIgMVC464a12z2ycjNFn9CbB+HxFTWnbTAU57xa/djbFhKz+ml6wzLpo5Q==" />

    <link rel="stylesheet" media="all" href="/assets/application.debug-2ff85327b45ccfcb08b5825f21ab8b6d5ee67197751ab00ed866ea21a87f647c.css" data-turbolinks-track="reload" />

    <form name="boleto_form" action="" id="boleto-form">

Dados do comprador

    Nome
    <input type="text" name="name" id="name" value="Guilherme Bordignon" required>

  <input type="text" name="cpf" id="cpf" value="03310782018" required>
  <input type="submit" name="buy_button" id="buy-button" value="Comprar">
</form>


text:
Q: Calculate number of characters of my xp:inputText control I have my xp:inputText control bound to a viewscope. Now I would like to remove the disable property from a button when the user has entered 10 characters but the onkeypress or onchange event (server) only seem to submit something when I leave the input control.
How can I resolve this server side?

A: If you do go for a client side solution, put something like this into your page or custom control at the bottom of the page.
<xp:scriptBlock>
setInterval(function () {
  if(XSP.getElementById("#{id:textInputFieldName}").val().length > 9) {
    XSP.getElementById("#{id:submitButtonName}").removeAttr("disabled");
  } else {
    XSP.getElementById("#{id:submitButtonName}").attr("disabled", "disabled");
  }
}, 500); //Runs every 0.5s
</xp:scriptBlock>

This runs every 500 milliseconds and checks the length of your text input is greater than 9 characters.  If it is, it removes the disabled attribute of your button otherwise it keeps the attribute on.  This approach works even if people copy and paste data into the field whereas a solution that uses keypress may not pick up a paste event.
You will need to change the ids for your elements.

A: On the serverside you cuould use the onkeydown event and disable the button from the partial refresh.
<xp:inputText id="inputText1">
    <xp:eventHandler event="onkeydown" submit="true"
        refreshMode="partial" refreshId="button1">
        <xp:this.action><![CDATA[#{javascript:print("keydown")}]]></xp:this.action>
    </xp:eventHandler>
</xp:inputText>

<xp:button value="Label" id="button1"></xp:button>


text:
Q: Only Clients can write to RAFT leader -- choke point I dont see a huge advantage of RAFT in implementing distributed DBs. If the clients can only write to the leader then that leader still becomes the choke point -- or the single point of failure. Ideally, I would want a way in which multiple clients can write to multiple DBs and then the DBs synchronize amongst themselves. That would help scale up things because no single DB acts as the choke point. Is there a way to do that?

A: In many raft consensus algorithm,  the leader of cluster / the controller is responsible for managing the cluster health, while in your question you suggested that it introducing a bottleneck,  it is just not true , as there could be a "leader" to each data segment inside the data store which the client will work against it. If we are taking for example about kafka, the clients are working against the leader of the topic's partition , which could be any broker inside the cluster , and the data is replicated to the in sync followers, it is not related to the leader/controller of the cluster

A: Appache Kafka has brought in KRaft mode that avoids the dependency on Zookeeper as an improvement.
Even in the case of Docker, in order to manage the global cluster state, the Raft Consensus Algorithm is implemented by manager nodes while the Docker Engine runs in swarm mode.
There are many other DBs that use raft algorithm. HashiCorp already use it.
Typically, if the cluster's leader crashes due to some reason or does not have a leader, a random node based on the election process shall become a candidate one the election timeout gets over.
Raft is a distributed consensus protocol that meets a key requirement of achieving consensus in distributed systems . This shall involve multiple servers agreeing, deciding on values. In simple terms, it will be like they would need majority of servers to be available for deciding. This in turn operates by electing a leader in the cluster.
In case of Push model the leader takes the responsibility to keep track of replication process in the cluster. You can also make changes in code such that you have Pull model used where the follower takes care of its own replication.


text:
Q: How to save the state of toggle button android I need to save the information about the toggle button when the user kill the app or restarted i want to display the previous state of the button Thanks
 public class MainActivity extends ActionBarActivity {
    ToggleButton toggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android.support.v7.app.ActionBar menu = getSupportActionBar();
        menu.setDisplayShowHomeEnabled(true);
        menu.setLogo(R.mipmap.ic_launcher);
        menu.setDisplayUseLogoEnabled(true);

    }
    @Override
    protected void onResume() {
        super.onResume();
        toggle = (ToggleButton) findViewById(R.id.togglebutton);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    enableNotifications();
                } else {
                    makeDialog();
                }
            }
        });
    }

A: Use shared prefernces for the same.
togButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                     int notification_status = Integer.parseInt(mPreferences.getString("status", "-1"));
                    SharedPreferences.Editor editor=mPreferences.edit();
                    Log.i("notification_status="+notification_status,"888");
                    if(notification_status==-1){
                          editor.putString("status", "1");
                          holder.notification_btn.setBackgroundResource(R.drawable.notification_on);
                          //do your stuff
                    }else if(notification_status==1){
                        editor.putString("status", "0");
                        holder.notification_btn.setBackgroundResource(R.drawable.notification_off);
                        //do your stuff
                    }else if(notification_status==0){
                        editor.putString("status", "1");
                        holder.notification_btn.setBackgroundResource(R.drawable.notification_on);
                        //do your stuff
                    }
                    editor.commit();
                }
            });

A: Use shared preferences as following class
public class YourPreferenes {

    private Context mContext;
    private SharedPreferences mPrefs;
    private static YourPreferenes mYourPreferenes;
    private YourPreferenes(Context ctx){
        mContext = ctx;
        mPrefs = mContext.getSharedPreferences("ATSPreferenes", Context.MODE_PRIVATE);
    }

    public static ATSPreferenes getInstance(Context ctx){
        if(mYourPreferenes == null){
            mYourPreferenes = new YourPreferenes(ctx);
        }
        return mYourPreferenes;
    }

    public void setButtonState(boolean btnstate){
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean("btnstate", btnstate);
        editor.commit();
    }

    public boolean getButtonState(){
        return mPrefs.getBoolean("btnstate", false);
    }
}

And get your saved togalbutton stat even you kill your app.


text:
Q: Vidyo.io media bridge recorder does not work I am developing an application using the vidyo platform (https://vidyo.io). In particular, I am trying to record the videoconference using the Media Bridge Docker.
I have followed these two tutorials:
media-bridge-integration
hot-to-record-with-media-bridge
In both scenarios, I am able to create and start the recorder, but at the end, I do not find the "recording.flv" file (that should have been generated by the recorder).
I have checked from the point of view of the participants, and they see the recorder. In fact, the message "Recorder joined" is showed in all the participants' views.
I have installed the Media Bridge Docker on Ubuntu Server 16.04.3 LTS.
Has someone the same problem?
Thank you in advance.

A: [Solved]
The recorder was working correctly, but the file recording.flv was saved inside the my_vidyombws container instead of my_mediabridge.


text:
Q: website not loading on IOS, Why do I get "The Site can't be reached" response? I have a wordpress site working fine on Windows and android.  However it doesn't work on ios (Safari or Chrome).
I've tried the usual clearing cache / running in cognito mode and still no luck.   This is an image from an emulator in chrome (The same as what I am getting on a physical device):

It sits behind an AWS ELB.  There is a listener on port 80 that just does a redirect to port 443.   If I remove this then the site displays with no problem albeit unsecure on port 80.  The redirect works fine on windows and Mac desktop and also on Android.  So I think the problem is a certificate issue but I just dont know what else to do.  The certificate is being marked as perfectly valid everywhere else it is being used.
I've even tried on multiple ios devices and I get the same problem.  Any ideas?


text:
Q: remove blanks from strsplit in R > dc1
  V1                V2
1 20140211-0100     |Box
2 20140211-1782     |Office|Ball
3 20140211-1783     |Office
4 20140211-1784     |Office
5 20140221-0756     |Box
6 20140203-0418     |Box
> strsplit(as.character(dc1[,2]),"^\\|")
[[1]]
[1] ""    "Box"

[[2]]
[1] ""             "Office" "Ball"

[[3]]
[1] ""             "Office"

[[4]]
[1] ""             "Office"

[[5]]
[1] ""    "Box"

[[6]]
[1] ""    "Box"

How do i remove the blank ("") from strsplit results.The result should look like:

[[1]]
[1] "Box"

[[2]]
[1] "Office"    "Ball"

A: You can check use lapply on your list. I changed the definition of your strsplit to match your intended output.
dc1 <- read.table(text = 'V1                V2
1 20140211-0100     |Box
2 20140211-1782     |Office|Ball
3 20140211-1783     |Office
4 20140211-1784     |Office
5 20140221-0756     |Box
6 20140203-0418     |Box', header = TRUE)

out <- strsplit(as.character(dc1[,2]),"\\|")

> lapply(out, function(x){x[!x ==""]})
[[1]]
[1] "Box"

[[2]]
[1] "Office" "Ball"

[[3]]
[1] "Office"

[[4]]
[1] "Office"

[[5]]
[1] "Box"

[[6]]
[1] "Box"

A: You could use:
library(stringr)
str_extract_all(dc1[,2], "[[:alpha:]]+")
[[1]]
 [1] "Box"

[[2]]
 [1] "Office" "Ball"

[[3]]
 [1] "Office"

[[4]]
 [1] "Office"

[[5]]
 [1] "Box"

[[6]]
 [1] "Box"

A: I do not have a global solution, but for your example you could try :
strsplit(sub("^\\|", "", as.character(dc1[,2])),"\\|")
It removes the first | (this is what the regex "^\\|" says), which is the reason for the "", before performing the split.

A: In this case, you can just remove the first element of each vector by calling "[" in sapply
> sapply(strsplit(as.character(dc1[,2]), "\\|"), "[", -1)
# [[1]]
# [1] "Box"

# [[2]]
# [1] "Office" "Ball"

# [[3]]
# [1] "Office"

# [[4]]
# [1] "Office"

# [[5]]
# [1] "Box"

# [[6]]
# [1] "Box"

A: Another method uses nzchar() after unlisting the result of strsplit():
out <- unlist(strsplit(as.character(dc1[,2]),"\\|"))

out[nzchar(x=out)] # removes the extraneous "" marks

A: library("stringr")

lapply(str_split(dc1$V2, "\\|"), function(x) x[-1])

[[1]]
[1] "Box"

[[2]]
[1] "Office" "Ball"

[[3]]
[1] "Office"

[[4]]
[1] "Office"

[[5]]
[1] "Box"

[[6]]
[1] "Box"

A: This post is cold but if this helps someone:
strsplit(as.character(dc1[,2]),"^\\|") %>%
               lapply(function(x){paste0(x, collapse="")})


text:
Q: How to add a Column ContextMenu in the WPF DataGrid I'm trying to add a context menu to a column in the WPF datagrid and don't quite see how this is possible.  I know how to add one to the datagrid, but I would like to have different menu items based on the column as well have the menu click event be aware of column or better yet the cell that the context menu was chosen for.
My ultimate goal is to create a context menu that has a "Clear" menu item which will be used to null out the data in that column.  I don't want an empty string or false in the case of a check box column, I want the underlying data to be nulled out.  If anyone has a suggestion on a reusable way to do this that would be much appreciated as well.
Thanks much!

A: Another option is to set the column headers to a TextBlock (or some other control that can handle a ContextMenu).
So you could say:
// Create a context menu
var cm = new ContextMenu();
cm.Items.Add(new MenutItem{Header="SampleItem"});

// Create a textblock with your header text and link the context menu
var tb = new TextBlock{Text="My Column Name"};
tb.ContextMenu = cm;

// Set the grid column header to your textblock
grid.Columns[0].Header=tb;

A: i add a context menu to the cells like this
  <!--Cell ContextMenu-->
  <ContextMenu
     x:Key="cellContextMenu">
     <MenuItem
        x:Name="menuFillUp"
        Click="menuFillUp_Click"
        Header="Fill _Up" />
     <MenuItem
        x:Name="menuFillDown"
        Click="menuFillDown_Click"
        Header="Fill _Down" />
  </ContextMenu>

and set it as so
  <!--DataCell Style - Adds ContextMenu-->
  <Style
     TargetType="{x:Type dg:DataGridCell}">
     <Setter
        Property="ContextMenu"
        Value="{DynamicResource cellContextMenu}" />
  </Style>

then i add a context menu to the column header using the following context menu
  <!--Show Hidden Columns ContextMenu-->
  <DataTemplate
     x:Key="menuItemColumnShow">
     <MenuItem
        x:Name="menuShowColumn"
        DataContext="{Binding Path=.}"
        Header="{Binding Path=Tag.Code}"
        Click="menuShowColumn_Click" />
  </DataTemplate>

  <!--Column ContextMenu-->
  <ContextMenu
     x:Key="columnContextMenu">
     <MenuItem
        x:Name="menuHideColumn"
        Click="menuHideColumn_Click"
        Header="Hide _Column" />
     <MenuItem
        x:Name="showMenu"
        Header="Show"
        ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ResultEditorGrid}}, Path=HiddenColumnCollection}"
        ItemTemplate="{StaticResource menuItemColumnShow}">
        <MenuItem.Style>
           <Style
              BasedOn="{StaticResource {x:Type MenuItem}}"
              TargetType="{x:Type MenuItem}">
              <Style.Triggers>
                 <DataTrigger
                    Binding="{Binding RelativeSource={RelativeSource self}, Path=Items.Count}"
                    Value="0">
                    <Setter
                       Property="Visibility"
                       Value="Collapsed" />
                 </DataTrigger>
              </Style.Triggers>
           </Style>
        </MenuItem.Style>
     </MenuItem>

     <MenuItem
        Header="_Add  Item"
        Command="local:MyCommands.AddTItem"
        CommandTarget="{Binding Path=PlacementTarget, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" />
  </ContextMenu>

      <!--ColumnManagerCell Style - Adds ContextMenu - Tool Tip Style for Marking Scheme Preview-->
  <Style
     TargetType="{x:Type dg:DataGridColumnHeader}">

     <Setter
        Property="ContextMenu"
        Value="{DynamicResource columnContextMenu}" />
  </Style>

(im using a wierd mix of commands and click events, the code kind of evolved :)
what the above code does is give me dynamic menus on the column headers. i have a hidden column collection on my derived grid, and i show shich columns are hidden/shown in the context menu on the column, and i have a seperate context menu for the cells in the grid.
you can find which column was clicked on by
 private void menuHideColumn_Click(object sender, RoutedEventArgs e) {

     //move thru the visual tree to get the context menu
     DependencyObject dep = (DependencyObject)e.OriginalSource;
     while ((dep != null) && !(dep is ContextMenu)) {
        dep = VisualTreeHelper.GetParent(dep);
     }
     if (dep == null) { }
     else {
        //we have a context menu, cast it
        ContextMenu contextMenu = (ContextMenu)dep;
        if (contextMenu.PlacementTarget is DataGridColumnHeader) {
           DataGridColumnHeader header = contextMenu.PlacementTarget as DataGridColumnHeader;
           //get the grid to hide the column
           myDerivedGrid.HideColumn(header.Column);
        }
     }
  }

i may have missed a few things, feel free to make a comment and ill try to fill in the detail.


text:
Q: MQTT topic name design to handle multiple "same" things In my current IOT project. I will be using multiple ESP8266s (3) to send data and receive actions. Each MCU will be in charge of monitoring different aquariums around the house. I have thought of structuring my topics like the following:
"Data" topics will follow the same structure, for example to retrieve temperature data:
esp8266/aquarium/aquarium_id/temperature/dht11

"Action topics", the topics the MCU subscribes to receive commands, for example:
aquariumcontroller/aquarium_id/action/water

The topic which the aquarium subscribes to to updte the MCU's params:
aquariumcontroller/aquarium/aquarium_id/params

The aquariumcontroller is the MQTT client written in Python. This is the entity that will be sending actions and handling messages received. I have two questions, are my topics correctly named and structured to handle multiple aquariums? Also as I will have a Controller, isn't it better to also have a database which will contain the aquariums info like the topics for this specific aquarium and the params or will i run into problems if i persist topics when i change the aquarium ID?
Thank you

A: What you mentioned will work.
You can also have a common topic that everyone subscribes to and use JSON format to send data. In JSON format you can mention necessary identifiers and actions.
{
    "aquarium_id": "xxx",
    "operation": "temperature_read",
    "value": "24.5"
}

For every aquarium_id you can have an individual topic. The advantage of this scheme is that aquarium controller will only receive message that are associated with it however their will be a added complexity where by you have to pre-populate aquarium_id in your server.
{
    "operation": "temperature_read",
    "value": "24.5"
}

You should ideally have a database to store aquarium_id and its relevant properties (something like master record). With database you can also store you readings and action to get an historical view of your data. You can use postgres as DBMS.


text:
Q: Why typeof undefined is return string? When I run from the browser
typeof undefined

I got "undefined" string. That is why? Most of the time I check my variable something like
if (a == 'undefined') {
  do something
}

is I am checking my variable a is equal to undefined? I don't understand about that. Can someone explain me? Another way to check undefined in javascript?

A: Because that is how typeof  works:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
if (a == undefined) { // instead its a type comparison

A: typeof get's you the type as a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

A: undefined just happens to be a global name that holds the undefined value.
Quoting the linked page,

undefined is a property of the global object, i.e. it is a variable in global scope.
  The initial value of undefined is the primitive value undefined.

typeof always returns a string describing the value of the name passed to it.

A: The typeof operator returns a string indicating the type of the unevaluated operand.
It changes like this
Undefined   :"undefined"
Null    :"object"
Boolean :"boolean"
Number  "number"
String  :"string"
Host object (provided by the JS environment)    :Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms):    "function"
Any other object    :"object"

DOC


text:
Q: Take cell value from a cell containing a function/formula
From the picture, I want to find the distance traveled.
My formula @ cell O83 looks something like : =$M83- $M82. But O83 returns Zero.
Note: column M82 contains a formula.
Question: how do I extract and use just the value from a function?

A: Your problem is the formatting that you might have applied on the cell O82
See the example below

If you remove the formats on the problematic cells you'll see the correct results.

To do so select all the range O82:O100 and click on clear formats from home tab.


text:
Q: Javascript function does not execute when called I have the following code:
function firstQuote(){
  jQuery.ajax({
    url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
    type: 'GET',
    dataType: "jsonp",
  });

  function mycallback(json){
    document.getElementById('quote').innerHTML = json[0].content;
  }
};
window.onload = firstQuote;

It is a simple function, but it is not being executed. If I take the code outside of the function it works perfectly. I'm stuck at it for some time now. Please, could someone help me?

A: You're trying to define the callback inside the firstQuote function. (If you look at the error console, you'll see "[Error] ReferenceError: Can't find variable: mycallback".) Separate those functions to put mycallback on the global scope:

function mycallback(json) {
  document.getElementById('quote').innerHTML = json[0].content;
}

function firstQuote() {
  jQuery.ajax({
    url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
    type: 'GET',
    dataType: "jsonp",
  });
};
window.onload = firstQuote;


text:
Q: Images upload error I'm having the following problem. I use input form with four validated text input fields (not allowed to be empty), and three file input fields below on the same form. When I try to upload images which are smaller in size, everything works ok. But when I choose a larger pictures, like 1MB or so, I get the validation error on text input fields even though I filled them.
$ime = mysql_real_escape_string($_POST['ime']);
$mesto = mysql_real_escape_string($_POST['mesto']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$emajl = mysql_real_escape_string($_POST['emajl']);
$opis = mysql_real_escape_string($_POST['opis']);

if ((empty($ime)) || (empty($mesto)) || (empty($telefon)) || (empty($emajl))){echo "Moraju biti uneti podaci u obavezna polja"; exit;}
//unos slike1
if ((($_FILES["slika1"]["type"] == "image/gif")
|| ($_FILES["slika1"]["type"] == "image/jpeg")
|| ($_FILES["slika1"]["type"] == "image/jpg")
|| ($_FILES["slika1"]["type"] == "image/pjpeg")
|| ($_FILES["slika1"]["type"] == "image/x-png")
|| ($_FILES["slika1"]["type"] == "image/png"))
&& ($_FILES["slika1"]["size"] < 2097152))
{
if ($_FILES["slika1"]["error"] > 0)
 {
 echo "Greška: " . $_FILES["slika1"]["error"] . "<br>";
 }
else
 {
$razdvajanje = explode('.',$_FILES['slika1']['name']);
 $ekstenzija = $razdvajanje[1];
$novoime = mysql_real_escape_string($razdvajanje[0]).'_'.time();
 $putanja = 'uploads/' . $novoime . "." . $ekstenzija;
move_uploaded_file($_FILES['slika1']['tmp_name'], $putanja);
 }
 }
 else
 {
 echo "Slika mora biti manja od 2MB i u adekvatnom formatu";

The error I get is "Moraju biti uneti podaci u obavezna polja" even the field is not empty. When I try to upload just one larger image, it also works. It's only not working when I try to upload three 1MB images at the same time.
Just to be clear. Script is working on localhost (XAMPP). I am having issues when uploading to my web hosting server. Also, the script is working when I upload 3 image files that are around 300kb, but when I try to upload 3 files that are around 1MB in size, the process fail at around 60%. I don't think that problem is in size, but in upload time.

A: maybe you need to increase the size allowed in php.ini
or do something like this
ini_set('post_max_size', '10M');
ini_set('upload_max_filesize', '10M');
ini_set('max_file_uploads', '20');

A: You have to set the filesize and override the default size set by PHP:
Something like this:
$size1=$_FILES["uploaded_file"]["size"]/1024;
$max_allowed_file_size = 50000;

if($size1 >= 0)
{
    if($size1> $max_allowed_file_size )
    {
    $err[]= "\n Size of file should be less than $max_allowed_file_size";
    }
}

Just modify your script with the filesize and you should be fine.

A: Do this:

*

*Search your php.ini. (mine is under /etc/php5/apache2/php.ini)

*Edit "post_max_size" to 5M

*Edit "upload_max_filesize" to 5M

*Edit "max_file_uploads" to 20 (<- this value determines how many files can be uploaded using a single request.)

Hope this helps.

A: I solved a problem by limiting image size to 500kb. It works now. I mean, I did not solve the problem, I avoided it.


text:
Q: Complicated batch rename file problem I did find the program pyRenamer, but I don't seem to understand it.
I have hundreds of files with name like
main.php?g2_view=core.DownloadItem&g2_itemId=6027&g2_serialNumber=3
here actually only the itemId and the serialNumber does change.
serialNumber is 1 or 2 or 3.
I just need to rename them with file suffix jpg, and something like "downloaditem".

A: If you have all of these items in the same program, use this script to rename each of them to 'download%.jpg' replacing % with a number.
Replace the 'main.php*' with '*' if not all of the file names start with 'main.php'.
This script assumes that your files are in your Download directory (folder), Change '$HOME/Downloads' to whatever folder they are in.
cd "$HOME/Downloads"
num=0
for item in main.php*; do
    mv "$item" "download${num}.jpg"
    num="`expr "$num" + 1`"
done

Or this one-line version if you want:
cd "$HOME/Downloads"; num=0; for item in main.php*; do mv "$item" "download${num}.jpg"; num="`expr "$num" + 1`"; done

You can run that command in a terminal. Open a terminal with CTRL+ALT+T then copy the one-line version and paste it into the terminal with CTRL+SHIFT+V.


text:
Q: Kotlin - conditional chaining of methods Is there a way to chain optionally a method in Kotlin, like for example on a FuelManager class, where I would like to have body method as an optional thing, so this would be a request with a body method:
val (_, response, data) = manager
      .request(Method.POST, url)
      .timeoutRead(2_000)
      .timeout(1_000)
      .header("Content-Type" to "application/json")
      .header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
      .body(payload.toString())
      .responseString()

So, here I would like to check if payload exists, then I would add body method, if not I would not add body to a request. Request without body method.
val (_, response, data) = manager
          .request(Method.POST, url)
          .timeoutRead(2_000)
          .timeout(1_000)
          .header("Content-Type" to "application/json")
          .header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
          .responseString()

A: I agree with Sweepers comment, that apply may be nicer to use here, e.g.:
val (_, response, data) = manager.apply {
          request(Method.POST, url)
          timeoutRead(2_000)
          timeout(1_000)
          header("Content-Type" to "application/json")
          header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
          if (!payload.isNullOrBlank())
             body(payload.toString())
     }.responseString()

Inserting an if-statement is relatively straight-forward in that case.
If you can't trust that what you have follows fluent API best practice (i.e. returning the actual instance again), you may instead use also something as follows:
val (_, response, data) = manager
          .request(Method.POST, url)
          .timeoutRead(2_000)
          .timeout(1_000)
          .header("Content-Type" to "application/json")
          .header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
          .let {
            if (!payload.isNullOrBlank()) it.body(payload.toString())
            else it
          }
          .responseString()

I.e. putting the if-statement inside the scope functions let or run.

A: I think this should do the job
val (_, response, data) = manager
      .request(Method.POST, url)
      .timeoutRead(2_000)
      .timeout(1_000)
      .header("Content-Type" to "application/json")
      .header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
      .apply {
          if(!payload?.toString().isNullOrBlank()) {
            body(payload.toString())
          }
      }
      .responseString()

See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html

A: Like people have said, long chains can be hard to read (especially if you start adding a bunch of logic into them), so it might be better to break it down into some well-named functions instead
val (_, response, data) = manager.apply {
          request(Method.POST, url)
          timeoutRead(2_000)
          timeout(1_000)
          header("Content-Type" to "application/json")
          header("X-API-Key" to ctx.conf.get(ConfValues.ApiSecret))
          addBodyIfRequired(payload)
     }.responseString()

private fun WhateverManager.addBodyIfRequired(payload: Payload) =
    apply { if (!payload.isNullOrBlank()) body(payload.toString()) }

That way it reads a little clearer, and if you ever need to tweak the logic it can happen in that separate function, and your builder still looks nice and clean. You tend to see this kind of thing in functional programming, where you can have long pipelines of operations, but you create small functions you can chain together in a neat and readable way
Plus with extension functions, you can kinda rewrite how the builder looks - say if you wanted to combine the two timeout calls into one, with named parameters. It's definitely a personal preference thing, but it can really help when there's a lot happening and you want to keep it concise!

A: You can use isNullOrBlank() "Returns true if this nullable char sequence is either null or empty or consists solely of whitespace characters."


text:
Q: Hibernate Statistics statement count - incorrect I have a bidirectional one to many relationship as follows. And in my test, I insert one parent and 3 children entities. Then I count the number of prepared statements. Hibernate tells me it's 6 but in the log I see only 4 insert statements logged. Why is this happening?
public class Order {
    @Id
    private Long id;

    @OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Line> lines = new ArrayList<>();

    public void addLine(Line line) {
        lines.add(line);
        line.setOrder(this);
    }
}

public class Line {
    @Id
    private Long id;

    @ManyToOne
    private Order order;
}

Test
@Test
    public void test() {
        Statistics stat = entityManager.unwrap(Session.class).getSessionFactory().getStatistics();
        Line line1 = Line.builder().lineNbr("1").build();
        Line line2 = Line.builder().lineNbr("2").build();
        Line line3 = Line.builder().lineNbr("3").build();
        Order order = Order.builder().orderNbr("1").lines(new ArrayList<>()).build();
        order.addLine(line1);
        order.addLine(line2);
        order.addLine(line3);

        repo.saveAndFlush(order);
        assertEquals(4, stat.getEntityInsertCount());
        assertEquals(4, stat.getPrepareStatementCount()); // this fails. Hibernate says it's 6
    }

This is what I see in the log:
Hibernate: insert into orders (order_nbr, id) values (?, ?)
Hibernate: insert into line (line_nbr, order_id, id) values (?, ?, ?)
Hibernate: insert into line (line_nbr, order_id, id) values (?, ?, ?)
Hibernate: insert into line (line_nbr, order_id, id) values (?, ?, ?)

927500 nanoseconds spent preparing 6 JDBC statements;
2732200 nanoseconds spent executing 4 JDBC statements;
2118000 nanoseconds spent executing 2 JDBC batches; -------- what is this?

A: The first Line insert counts as normal statement, the following two count as batch inserts i.e. they reuse the same statement or use JDBC batching. Not sure if they are still counted as prepared statements as well, but I think so.


text:
Q: Visual Studio Shortcut for Automatically Creating Constructors from an Inherited Class Say I am inheriting from a class with several "overloaded" constructors.
By any chance is there a short cut in Visual Studio which writes the constructors in the derived class with the same signatures as in the default class for me, with boilerplate code which calls MyBase.New(...) and plugs in the arguments for me?
EDIT:  As far as I can find there is no such shortcut built-in, however there is one in resharper as suggested by Raymond.

A: I don't know about a shortcut in a standard Visual Studio installation, but if you install the excellent Resharper plugin from jetBrains, it is Alt-Insert, C. I don't develop without it.


text:
Q: How can I change the white background in the file manager? I would like to change the white background of my file manager. (I really searched everywhere and tried a lot of things.)
I was trying to change CSS files of my theme (GTK2 & GTK3 folders) and I tried others themes too, but no luck so far.
I wish to change the "eye-killing" white to grey, In Windows you could just change that easily with the theme changer.
In Xubuntu (I'm using XFCE), this seems impossible.I switched back to Ubuntu, but there I couldn't change this, even they're using same principles.

Could anyone give me a hint where I change this annoying white background?
Thanks in advance.

A: You can try to change the "gtk_color_scheme" (gtk-2)  or "default color scheme"(gtk-3) defined in the "gtkrc" or "gtk.css" files of your theme.
AS vasa1 explains in this answer, there are advantages to keep the themes in you ~/.themes folder.Because will be user-specific and not system-wide and you do not need sudo to edit them.
Here you have an example.
In this case I'm running Xubuntu 13.04 with the default them "Greybird".I only edit the gtkrc file (gtk-2) because Thunar (As far as I know) is a gtk-2 application.
1) Open a Terminal window and type:

*

*sudo mousepad /usr/share/themes/Greybird/gtk-2.0/gtkrc
Search for the line nuber 6, and change the base_color from #fcfcfc to #CECECE

BEFORE:

gtk_color_scheme  =
  "bg_color:#CECECE\nselected_bg_color:#398ee7\nbase_color:#fcfcfc" #
  Background, base.

AFTER:

gtk_color_scheme  =
  "bg_color:#CECECE\nselected_bg_color:#398ee7\nbase_color:#CECECE" #
  Background, base.

2) Logout and Login to see the changes.
BEFORE:

AFTER:

Also you can edit the file gtk.css for the (gtk-3) applications.

*

*sudo mousepad /usr/share/themes/Greybird/gtk-3.0/gtk.css
You can change the @define-color base_color from #fcfcfc to #CECECE
NOTE: This is just an example, please change the settings according to your needs.
Hope it helps.

A: I found a great answer in another post How do I change to a theme not listed in the Appearance screen?
oh, and this still applies to ubuntu 16.04, which I have running...
just install gnome-tweak-tool and my newly installed dark themes were there (or whatever non-white bkgd themes you choose to install), they apply to thunar, nautilus, system monitor bkgds...... phew.....


text:
Q: VSC C#: Referencing Microsoft DLLs I'm trying to port a C# .NET Core project from Visual Studio 2019 to Visual Studio Code, although I have no experience with using VSC for C#. I managed to set up NuGet references using dotnet add package, however I cannot wrap my head around importing DLLs that are already present in Windows, such as System.Windows.Forms.
This has been done via a GUI menu in VS19, however that cannot be the case with Powershell commands. Futhermore, I used a Microsoft.Windows.Compatibility package to get it working on .NET Core, rather than .NET Framework. I attempted using dotnet add package System.Windows.Forms along dotnet add package Microsoft.Windows.Compatibility, however, after dotnet run, I get the following errors in the Terminal:

warning NU1701: Package 'System.Windows.Forms 4.0.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework '.NETCoreApp,Version=v3.1'. This package may not be fully compatible with your project.

Unhandled exception. System.BadImageFormatException: Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Reference assemblies should
not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (0x80131058)
File name: 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' ---> System.BadImageFormatException: Cannot load a reference assembly for execution.

How can I get this working in Visual Studio Code?


text:
Q: Why is the top level package being removed? Python I created aPython package for one of the projects I'm currently working on. The top package is called integration, and inside there's another called testcases and the name of the test. I installed the modules via pip: produced a pip wheels dist, and installed. Also, there's a top level script called integration that's copied to the command line.
The directory structure looks like:
project/
    __init__.py
    integration/
         README.md
         __init__.py
         integration # script
         testcases/
              __init__.py
              foo_test.py
              bar_test.py

So, from the command line, after a pip install, I run:
integration --wait-time 1

Everything goes smooth till it starts to import the packages:
*** Update *****
# os.getcwd() : /home/ubuntu/project
*****
2016-02-17 17:03:25 - project - INFO - Module: integration.testcases.bar_test
2016-02-17 17:03:25 - project - INFO - class_str: BarTest
2016-02-17 17:03:25 - project - INFO - class_data: [u'bar_test', u'py']
2016-02-17 17:03:25 - project - ERROR - Failed to instantiate class integration.testcases.bar_test
Traceback (most recent call last):
  File "/usr/local/bin/integration", line 131, in load_class
    module = importlib.import_module(module_path)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named testcases.bar_test
2016-02-17 17:03:25 - project - ERROR - No module named testcases.bar_test
Traceback (most recent call last):
  File "/usr/local/bin/integration", line 131, in load_class
    module = importlib.import_module(module_path)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)

Sure I didn't try to load testcases.bar_test: I passed integration.testcases.bar_test. Doing the same thing in the terminal I'm successful:
ubuntu@ip-10-3-6-9:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> module = importlib.import_module('integration.testcases.bar_test')
2016-02-17 17:10:00 - easyprocess - DEBUG - version=0.2.2
2016-02-17 17:10:00 - pyvirtualdisplay - DEBUG - version=0.1.5

Here's the source code for the method that imports those classes:
try:
   # filename -> bar_test.py
   # class_str -> BarTest
   class_data = filename.split(".")
   current_path = "{0}.{1}".format("integration.testcases", class_data[0])
   module_path = self.format_path(current_path)
   self.log.info("Module: %s" % module_path)
   module = importlib.import_module(module_path)
   return getattr(module, class_str)
except Exception, e:
   self.log.exception("Failed to instantiate class %s" % module_path)
   self.log.exception(e)

format_path(path) only replaces '/' by '.', nothing else, so
foo/bar/bat -> foo.bar.bat

I wonder why importlib is using testcases.bar_test instead of integration.testcases.bar_test. Any clues?

A: The fact that you are running this from /home/ubuntu does matter. The way Python iterpreter search for modules is described here
Investigate where does it look for them in your case with:
import sys
print sys.path

If /home/ubuntu/project1 is not there then import integration.whatever will fail.
Then you have 3 options:
- put your entry script in /home/ubuntu/project1 folder
- add /home/ubuntu/project1 to PYTHONPATH environment variable
- add /home/ubuntu/project1 to sys.path  within your entry script


text:
Q: Stress test a Server via by launching multiple processes I need to stress test a Server with around 3000 users conecting to it concurrently via SyncML Clients. For simulation of each user, a application needs to be launched which then connects to the server and does some operations.
Each user corresponds to each process.
The process is unix based and does http transactions based on SyncML Protocol.
I need to run the load for these 3000 processes for an hour or so.
Can you suggest best industry methods to fulfil such requirements?
Can JMeter or Locust help me in this?
Regards

A: You can definitely use Locust for this.
I wouldn't recommend starting processes to generate the load (even though it's possible), mainly because you won't get detailed statistics on what requests are made, how long they take to complete, etc.
Either you could just manually do the HTTP POST requests containing the SyncML data with the built in Locust HTTP client, or you could actually take something like pysyncml, and make your own SyncML client that reports the requests it does to Locust. It's fairly simple to do, you can read more about it, and see example, on the documentation page about custom clients.

A: Yes, JMeter can do this, though it's not clear to me what exactly the unix based processes needs to do.
JMeter can natively make HTTP POST requests and send XML data. Unless you have some very custom logic to make the requests, stick to JMeter on it's own.
If you must, you CAN execute a local process, but then you're severely limiting the number of users you can simulate per machine.
http://jmeter.apache.org/usermanual/component_reference.html#OS_Process_Sampler


text:
Q: What kind of WiFi/network setup do I need? I've got a problem with my network setup that at first seemed pretty easy to solve, but the more I read online the more confused I get ...
I have a modem which pretty much acts as the "center of the network": DHCP server + router + WiFi AP. If only WiFi was required, I could already live with this single device as the coverage is very good in every room of the building. However, I also do have a few network devices that can only be connected to the network via Ethernet (no WiFi), like Philips Hue Bridge first generation. Unfortunately, all of those devices are too far away from the modem to simply plug them in there ...
My first attempt of a solution was to (mis)use a TP-Link TL-WA701ND_v2 running on LEDE as some kind of "WiFi AP-bridge" (if that is the correct term), which would be a WiFi client to the modem and an AP to all WiFi network devices. A simple switch that I connected to the only Ethernet Port of the TL-WA701ND_v2 would provide the non-WiFi-capable devices with network access. This solution did actually work, however, it required having two different WiFi networks (one from the modem, another from the TL-WA701ND_v2). And for some reason that I don't understand, both modem and AP had to have DHCP enabled for this setup to work. Now, while this setup, albeit everything but pretty in its design, did work, unfortunately the TL-WA701ND_v2 could only provide very poor WiFi coverage compared to the modem WiFi. So I got frustrated soon and started looking for another, better solution ...
And that's where I am right now, not quite sure what I actually need, and hoping you guys can help me.
What I want is this: https://wiki.openwrt.org/doc/recipes/bridgedclient One big network, including the modem and the TL-WA701ND_v2. Both should be APs (same SSID, security settings, etc.), but only the modem should be a DHCP server. And devices, obviously, should connect to whichever AP is providing the stronger connection.
^^ Problem is, I can't seem to go with that solution since none of my devices support the legacy WDS (for Atheros chipset).
What I believe I can have is that: https://lede-project.org/docs/user-guide/relay_configuration
^^ Problem is, as far as I understand this setup, while the WiFi would form one big subnet, I would "lose" the LAN port on the TL-WA701ND_v2, effectively putting all devices connected to the switch (which is connected to that LAN port) in another subnet?!
???
So, what solution do I actually need to get what I want?
PS: Please let's try to find one that doesn't involve buying new devices, and instead uses the ones I already have.
Any help is greatly appreciated! Many thanks!

A: The first solution you tried is the recommended solution [creating a bridged AP], however unless both routers support AC [wireless], you're going to have a fairly slow LAN connection limited to 450Mbit/s or 300Mbit/s, depending on the age of hardware.
The best place to find the appropriate help to get your required solution up and running is to either browse the OpenWrt and/or LEDE forums, or create a new thread and copy your post on here to the new thread on the OpenWrt forum

*

*FWIW, OpenWrt will be merging with LEDE, and many of us recommend going with LEDE over OpenWrt (as OpenWrt hasn't had a commit in sometime), however since all devices are different, check out what other users are recommending under your router's thread on OpenWrt's & LEDE's forum.

I also recommend building your own LEDE image, as you can then truly customize the image to your specific needs.

*

*I created a LEDE build environment setup script a while back that will automate most of the manual steps involved in setting up the build environment.  I wrote the script for Ubuntu x64 (preconfigured for 16.04, 16.10, or 17.04)

*

*Line 11: user="<username>"

*Line 67: $ag install $PR1xxx

*

*Where xxx is equal to the variable on lines 48, 51, or 54

*Lines 116 - 133: Comment out, unless your router uses the Marvell-Cesa crypto driver

*Reference:

*

*LEDE Build System Installation

*LEDE Build System Usage

A: There is always the low-fi method: long ethernet cables.
I've been trying out Steam home streaming recently and wifi just wasn't cutting it. I now have a cable running from the ground floor up two flights of stairs and across the house.
Yes, it requires some cable management to make it tidy, but you do get the benefit of simplicity, better bandwidth and reliability, leading to lower latency too, if those matter to you.
Wireless is nice and all, but you can't beat a wire sometimes.


text:
Q: Select only not null columns in SQL Server ColA    ColB    ColC
--------------------
A       null    null
B       null    1
C       null    2

select sum(colB) as sumB, sum(colC) as sumC
from table

I want something like this:
SumC
--------
3

I don't want sumB to appear in my output if it has only null values in it.

A: Try this query
select sum(isnull(colC,0)) as sumC from table

A: You can use this query
if exists ( select * from ( select sum(colB) as sumB,sum(colC) as sumC from table) as d where d.sumB is null)

 select sum(colC) as sumC from table
else
select sum(colB) as sumB,sum(colC) as sumC from table


text:
Q: How to layout items "relatively" instead of absolute position? What is the best way to layout iPhone UI items? Right now I am using CGRectMake and specifying the exact x and y coordinates of every UI item (label, view, button, etc) and adding every UI item to the current view.
One problem I see with this is that if one of the items change height or width, I will have to adjust the x and y coordinates of other UI items, so maintenance will be a challenge.
Is there an alternative to doing this? in HTML/CSS, I am used to just placing items relative to each other using margins, not absolute positioning. What do you recommend I do to keep maintenance easy and stress-free?

A: No. As for as I know, Relative Layout is not possible in iOS. You can use Interface builder to design the UI, which will be easier to position the UI elements.
You can also consider using the autoResizingMask property of UIView. Which is,

An integer bit mask that determines how the receiver resizes itself when its superview's bounds change.

A: I don't think there is an automatic way to achieve this.
I think your only option for this is to write a method, but even this is going to be tricky to work with, you'll need to determine the affected element and know which elements to reposition (see below for an extremely trivial example).
-(void)adjustUIElements:(CGSize)newSize{

    //for example
    button1.frame = CGRectMake(
        (button1.frame.origin.x + newSize.width),
        (button1.frame.origin.y + newSize.height),
        button1.frame.size.width,
        button1.frame.size.height);

    //etc.
}

The great thing about this example is that you can run it any time there's a size change. It'll take a little while to get right but then you can reuse it in any function you see fit.

A: What I have been doing is using global constants to set the height, width, xoffset and yoffsets. Eg. I know I want 2 buttons next to each other, A and B where A is 20, 20 from origin and B is 20 right of A:
Constants.m:
CGFloat buttonHeight = 50, buttonWidth = 100;
CGFloat buttonAXoffset = 20, buttonAYoffset = 0;
CGFloat buttonBXoffset = 20, buttonBYoffset = 0;
CGFloat initialXoffset = 0, initialYoffset = 20;

(And use Constants.h to declare them with extern CGFloat blah)
To draw the buttons, set CGFloat creatorCursorX = initialXoffset, creatorCursorY = initialYoffset; which will be your relative cursor.
Then, just above creating the button A, do creatorCursorX += buttonAXoffset; creatorCursorY += buttonAYOffset;, and use creatorCursorX and creatorCursorY to set its position and buttonHeight and buttonWidth
After creating button A,  do creatorCursorX += buttonWidth;
So when you get to making button B, you already have a cursor which you can use to place button B relative to button A just like above. Add offset before, add size after. And this makes it easy to switch buttons (and other layout items) around.
You can edit this method to place items down the screen as well.
Btw, to start the cursor on a new line, just set creatorCursorX = initialXoffset again and add the Y distance to creatorCursorY
I'm not an expert in this area, but I've found this method to be the most efficient and make it easy to adjust later. No need to sift through code, just shuffle chunks around for order, and go to the Constants.m to change the sizes.

A: I couldn't find anything on the public-facing Apple site about it, but I read on one of the rumor sites that Apple will be introducing a new layout system in Lion called Cocoa Autolayout. Unfortunately, it won't be available for the next iOS release.
I don't want to link to any specific documents, but a search for "Cocoa Autolayout" on your favorite search engine will give you some general information how autolayout works.
If you're a registered iOS developer you should have access to one of the WWDC sessions on the topic.


text:
Q: Does Clojure STM has a relationship with atom and agent forms? I am looking into the Concurrency programming in Clojure .
http://clojure.org/concurrent_programming
I got to know that atom, ref and agent forms are used to maintain program state.
Only ref is used for coordinated updates , so dosync macro is used when performing changes.
So it is obvious that STM engine is involved at this point.
Just wanted to be clear about following doubt I have,

Does Clojure STM has a relationship with atom and agent forms too? or are
  they just utilized  java.util.concurrent.atomic capabilities ?

A: The STM is related to Agents in that send, send-off and send-via, when called inside a dosync block, only take effect once (and if) the transaction successfully commits.
There is no relationship between the STM and Atoms.


text:
Q: How to select all from an excel sheet where a column contains with specific strings I have this
Select * from [Sheet1$]

i use in my vb code in connection with database engine to select all data from an excel sheet.
But this time i would want to select all where column L contains PSM , VNM , TAMD or X00.
Please how do i write the query.
Regards

A: If the question targets only the SQL then you could do this:
"SELECT * FROM [Sheet1$] WHERE L IN ('PSM', 'VNM', 'TAMD', 'X00')"

More help here:
https://www.w3schools.com/sql/sql_in.asp


text:
Q: I don't know how to write a query to display some specific information I am trying to display some information from a SQL database and I don't know exactly how to write the query. I have a table which contains the "name" and the "studentship" of some students. What I have to do is to display the name, the studentship's value and to add another column(alias "Place") which contains the text "first" for the ones who have the studentship equal to 300, "second" for another studentship values. How can I do this? Thank you in advance!

A: You'll use a CASE statement for your place field:
 SELECT name,
     studentship,
     CASE WHEN studentship=300 THEN 'first' WHEN studentship = <another one?> THEN 'second' END as place
 FROM yourtable;

A: Try this:
SELECT NAME, STUDENTSHIP, IF(STUDENTSHIP = 300, 'first', 'second') FROM TABLE

Related question:
How to create virtual column using MySQL SELECT?


text:
Q: Using plaid in google functions is not working So I am using google functions to write a script to auto pay my workers!  In my back end i have stored the public token and account id.. I am trying to use plaid to turn into a stripe token then use stripe to do the transfer! The stripe thing is working but the plaid functions wont return the new stripe bank account number.. any ideas?
plaidClient.exchangePublicToken("public-sandbox-6be57fb5-3286-4bc8-a770-54a16ea39283",
res => {
var accessToken = res.access_token;
// debugging = exchangedata.access_token;
//debugging = err.message;
// Generate a bank account token
plaidClient.createStripeToken(accessToken, snapshot.val().plaid_account_id,
res => {
bankAccountToken = res.stripe_bank_account_token;
stripe.transfers.create({
amount: (Number(appointmentchildSnapshot.val().price)/3).toString(),
currency: "usd",
destination:bankAccountToken,
transfer_group: "ORDER_95"
},(_err, transfer)=> {
// asynchronously called
});
});

A: Make you use  double " " when declaring your client secret and stuff!
In order to test for errors use res.json(Error:responsetowhatfunction you are using)
-- Some bank tokens do not work with Plaid unfortunately in sandbox and they also expire pretty quickly so if its not working create a new token and try again
---With the error log stuff you can keep track of when this happens
   await plaidClient.exchangePublicToken(snapshot.val().plaid_token,
      async (error,response1) => {
        if (error !== null) {
          res.json({error:snapshot.val().plaid_token});
        } else {

        var accessToken = response1.access_token;
        //res.json(accessToken);
       // debugging = exchangedata.access_token;
        //debugging = err.message;
        // Generate a bank account token
       debugging = await plaidClient.createStripeToken(accessToken, snapshot.val().plaid_account_id,
        async (error2,response2) => {

          if(error2!==null){
            res.json({error:snapshot.val().plaid_account_id});

          }else{
          //res.json({error:response2});
         // bankAccountToken = response2.stripe_bank_account_token;
          stripe.transfers.create({
            amount: (Number(appointmentchildSnapshot.val().price)/3).toString(),
            currency: "usd",
            destination:response2.stripe_bank_account_token,
            transfer_group: "ORDER_95"
          },(_err, transfer)=> {
            // asynchronously called
          });
        }


text:
Q: asp.net MVC3 + Visual Web Developer 2010 Express + global.asax + cannot load type I have tried to google this problem and followed many suggestions, such as replacing dll's, re-installing MVC3, and more. Therefore I do try to approach this really great forum, even tough this question has been around here and there. But I think this error is general and I guess can be caused by many reasons.
The Problem:
I have made with Visual Web Developer 2010 Express an asp.net MVC3 web application with 'Internet' template. After many tries, this time I called it 'MvcAnotherTest'. It runs OK on my local machine.
I Re-built the solution and copied these files to my domain root on Windows Web Host account server:
MvcAnotherTest.dll
Global.asax
Global.asax.cs (don't think that it needed but tried with it and without it).
Web.config
System.Web.Routing
System.Web.Mvc
System.Web.Abstractions
System.Web.Helpers
System.Web.WebPages

And also:
Microsoft.Web.Infrastructure
System.Web.Razor
System.Web.WebPages.Deployment
System.Web.WebPages.Razor

But no matter what I do, I get this error below when I try browsing to the site:
Server Error in '/' Application.

Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'MvcAnotherTest.MvcApplication'.

Source Error:

Line 1:  <%@ Application Codebehind="Global.asax.cs" Inherits="MvcAnotherTest.MvcApplication" Language="C#" %>

Source File: /global.asax    Line: 1

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034

I configured the iis to 7 and the asp.net runtime to 4/4.5

A: I am having the same problem...did you solve it?
I had to remove the Global.asax.cs file completely in order for it to function.


text:
Q: Accessing Deleted Question Content I'm a 10k user on Math.SE.  As a human using my browser, I can access deleted questions and view them, just like non-deleted questions.  I'd like to use this access to collect data for a personal project of predicting some kind of "question quality" based on my voting record.  I have retrieved my voting record using a Python script, but accessing the content of questions I've voted on that were later deleted is proving tricky.
My 10k privileges obviously don't extend to Data Explorer access, and using the requests module in Python is (for some reason) locking me out after a couple dozen page requests.
Is there a good way to access the content and metadata of deleted questions on a site where I'm a 10k user?


text:
Q: How do I format each cell in column FOO in Excel if the len() of the cell value is longer then BAR? If this is the wrong place to ask this let me know.
Here is the formula I have right now:
=LEN($A$2)>$AB$11

Applies to:
=$A$2

That works great for the one cell. I need it to apply to each cell in the column.
If it was C# I would do something like this:
foreach(cell in columnA)
{
   if(cell.text.length > (INT)$AB$11.text)
   {
      cell.format(red)
   }
}

In other words how do I format each cell in column FOO if the len() of the cell value is longer then BAR?

A: If you need to generate the formatting programmatically for a large number of cells, you can do it with a macro (VBA), but if you're just looking for a quick and easy solution, you can drop the $'s from your original formula and copy and paste.  In other words:

=LEN(A2)>$AB$11

Applies to A2, but if you copy and paste that into, say, B3, from B2 (that is to say, one cell down from the original), it will update itself to be this:

=LEN(A3)>$AB$11

You can paste across a large range of cells and it will update all of them.  References without dollar signs are relative references, and will be updated in a copy/paste; references with dollar signs are absolute.  I'm presuming, by the way, that AB11 holds a certain parameter you want to compare all cells to.  If you're comparing them all to the single value, leave the dollar signs in that reference.  If you're comparing a column to another column, relative references can do that for you too like this:

=LEN(A2)>$AB11


text:
Q: Is is possible to detect either user has chosen dark mode on iPhone from xcode 10.x I am still using the xcode 10.2.1 and haven't upgraded to xcode 11 because of some other issues. Now I want to detect that users who are using iOS 13 has chosen dark mode or light mode as their app settings.
As per apple document, If developer build app through previous xcode the app would be in light mode by default, which is my case and is fine.
So, is there a way to detect the user current appearance mode.
There is code snippet which I am using:
if #available(iOS 13.0, *) {
            guard(traitCollection.responds(to: #selector(getter: UITraitCollection.userInterfaceStyle)))
                else { return }

            let style = traitCollection.userInterfaceStyle

            switch style {
            case .light:
                print("light")
            case .dark:
                print("dark")
            case .unspecified:
                print("unspecified")
            @unknown default:
                print("unspecified")
            }

        }

But it is always returning unspecified or light.

A: you can use this property to check if current style is dark mode or not:
if #available(iOS 13.0, *) {
    if UITraitCollection.current.userInterfaceStyle == .dark {
        print("Dark mode")
    }
    else {
        print("Light mode")
    }
}


text:
Q: Generate a two dimensional array via LINQ I am trying to create a matrix of doubles, representing a correlation between entities.
Here's how I'm doing it via LINQ
double[][] correlationsRaw = (from e in entitiesInOrder
                              select
                                (from f in entitiesInOrder
                                     select correlations.GetCorrelation(e, f)
                                ).ToArray()).ToArray();

That works fine.
But what I want is a two dimensional array (double[,]), not a jagged array.
Obviously, I can write some nested for loop to convert one into the other.
But is there some elegant LINQ trick I can use here?

A: I don't think there's an easy way of directly returning a multidimensional array from a Linq query... however you could create a function that takes a jagged array and return a multidimensional array :
public T[,] JaggedToMultidimensional<T>(T[][] jaggedArray)
{
    int rows = jaggedArray.Length;
    int cols = jaggedArray.Max(subArray => subArray.Length);
    T[,] array = new T[rows, cols];
    for(int i = 0; i < rows; i++)
    {
        cols = jaggedArray[i].Length;
        for(int j = 0; j < cols; j++)
        {
            array[i, j] = jaggedArray[i][j];
        }
    }
    return array;
}

By the way, it could be an extension method, allowing you to use it in a Linq query...


text:
Q: How does SO implement the diff efficiently? How does it check if the answer is modified or not?

A: I'm almost 100% sure that they use the Longest Common Subsequence algorithm to find changes.

A: Jeff talks about it in a blog post:
Mixing Oil and Water: Authorship in a Wiki World
He provides a link to the paper: An O(ND) Difference Algorithm and its Variations (pdf) and a C# Implementation

A: W.R.T. modified or not -- my money is on a hash of the before text compared to a hash of the edited text.  If they're the same, it wasn't edited (or more accurately "statistically unlikely it was edited").
I can't speak for the diff itself.

A:
How does it check if the answer is modified or not?

Each revision is stored in a PostRevision table, something along the lines of..
PostId    PostBody        PostCreatedAt
1234      My answer is... 2009-01-01 00:00:01
1234      Edited answer.. 2009-01-02 08:04:01
To find out if a question has been edited (and if it needs to show a link to the revisions page), you would just do something like SELECT count(*) FROM PostRevision WHERE PostID=1234
For efficiency, I imagine this data is denormalised, so there would be a NumberOfTimesEdited column in the Posts table


text:
Q: fork mulitple child in one parent I want to fork three child process in one parent.
And the following is my C++ code:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>

using namespace std;

int main()
{
    pid_t pid;
    for (int i = 0; i < 3; i++)
    {
        pid = fork();

        if (pid < 0)
        {
            cout << "Fork Error";
            return -1;
        }
        else if (pid == 0)
            cout << "Child " << getpid() << endl;
        else
        {
            wait(NULL);
            cout << "Parent " << getpid() << endl;
            return 0;
        }
    }
}

Now my output is :
Child 27463
Child 27464
Child 27465
Parent 27464
Parent 27463
Parent 27462

How should I modify my program to get the output like the following?
Child 27463
Child 27464
Child 27465
Parent 27462

What I mean is that these THREE children need to belong to the same ONE parent, can anybody give me some suggestion ?
Thank you all. :)

A: You should exit the execution of the child processes. Otherwise, they continue forking also
pid_t pid;
for(i = 0; i < 3; i++) {
    pid = fork();
    if(pid < 0) {
        printf("Error");
        exit(1);
    } else if (pid == 0) {
        cout << "Child " << getpid() << endl;
        exit(0);
    } else  {
        wait(NULL);
        cout << "Parent " << getpid() << endl;
    }
}

A: There are two issues:

*

*children zero and one continue with the for loop, spawning further processes;

*the "parent" branch terminates instead of continuing with the loop.

The following will produce the output you want:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>

using namespace std;

int main()
{
    pid_t pid;
    for (int i = 0; i < 3; i++)
    {
        pid = fork();

        if (pid < 0)
        {
            cout << "Fork Error";
            return -1;
        }
        else if (pid == 0) {
            cout << "Child " << getpid() << endl;
            return 0;
        } else {
            wait(NULL);
            if (i == 2) {
                cout << "Parent " << getpid() << endl;
            }
        }
    }
}

When I run it, I get
Child 4490
Child 4491
Child 4492
Parent 4489

A: Move your return 0 from the last condition to the middle one:
    if (pid < 0)
    {
        cout << "Fork Error";
        return -1;
    }
    else if (pid == 0) {
        cout << "Child " << getpid() << endl;
        return 0;
    }
    else
    {
        wait(NULL);
        cout << "Parent " << getpid() << endl;

    }

This way the parent will continue to loop, and the children will terminate instead of looping.