text:
Q: Flexslider slides won't show on Firefox and Chrome Canary The issue doesn't show up with any other browsers. I have posted the relevant HTML and CSS code. Are there any obvious issues with the code here?
Flexslider in Firefox

Flexslider in IE

Here is the relevant portion of the HTML slide portion of the code:

Latest Blog Posts

                    Random Stuff

                 December 10, 2014

Text

Here is the CSS code:
/* ---------------------------------------------------------------------- */
/*  Flexslider Elements
/* ---------------------------------------------------------------------- */
.slides li {
    position: relative;
}
#carousel li {
    margin-right: 5px;
}
#carousel li img {
    padding: 5px;
    border-style: solid;
    border-width: 1px;
    border-color: #D0D0D0;
    cursor: pointer;
}

.flex-direction-nav a:before {
    font-size: 20px !important;
}
.flex-control-paging li a.flex-active {
    background: rgba(0, 0, 0, 0.4) !important;
}
.flex-control-paging li a {
    background: rgba(0, 0, 0, 0.2) !important;
}
.flex-control-nav {
    bottom: auto !important;
    margin-top: 10px !important;
    position: relative !important;
}

.flexslider {
    background: url("assets/") no-repeat scroll center center #FFFFFF;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
    position: relative;
}
#carousel {
    margin-top: 5px;
}
div.flexslider {
    background: none;
    border: none;
    border-radius: 0;
    box-shadow: none;
    margin: 0;
}
.flex-direction-nav a {
    -moz-transition: none !important;
    -webkit-transition: none !important;
    -o-transition: color 0 ease-in !important;
    transition: none !important;
    background: #222222;
    border: none;
    font-weight: normal;
    margin: 0;
    opacity: 0.5;
    width: 26px !important;
    height: 26px !important;
    line-height: 26px;
    color: #FFFFFF !important;
    text-align: center !important;
    text-shadow: none !important;
}
.flex-direction-nav a.flex-next {
    right: 10px !important;
    font-size: 9px;
}
.flex-direction-nav a.flex-next:before {
    font-family: "fontawesome" !important;
    content: "\f105" !important;
}
.flex-direction-nav a.flex-prev {
    left: 10px !important;
    font-size: 9px;
}
.flex-direction-nav a.flex-prev:before {
    font-family: "fontawesome" !important;
    content: "\f104" !important;
}

Here is the Javascript:
var win = $(window), body = $('body'), scroll_top = win.scrollTop(), screen_height = win.height(), screen_width = win.width(), navbar_height = $('.navbar').outerHeight(), logo_font_size = Math.ceil(parseInt($('.navbar-brand').css('font-size'))), min_height = 40, size = [], navigation_position_top = $('.navbar').position().top, navbar = $('.navbar'), navbar_brand = $('.navbar-brand'), isMobile = false;
// Debounce Function
(function($, sr) {
    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function(func, threshold, execAsap) {
        var timeout;
        return function debounced() {
            var obj = this, args = arguments;

            function delayed() {
                if(!execAsap)
                    func.apply(obj, args);
                timeout = null;
            };
            if(timeout)
                clearTimeout(timeout);
            else if(execAsap)
                func.apply(obj, args);
            timeout = setTimeout(delayed, threshold || 100);
        };
    };
    // smartresize
    jQuery.fn[sr] = function(fn) {
        return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr);
    };
})(jQuery, 'clipresize');
//Main Function
var Main = function() {
    //function to detect mobile or explorer browser and its version
    var runInit = function() {
        if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
            var ieversion = new Number(RegExp.$1);
            if(ieversion == 8) {
                isIE8 = true;
            } else if(ieversion == 9) {
                isIE9 = true;
            }
        };
        if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            isMobile = true;
            body.addClass('isMobile');
        };
        navbar_brand.contents().filter(function() {
            return this.nodeType !== 3;
        }).each(function(i) {
            if($(this).is('img')) {
                size[i] = Math.ceil(parseInt($(this).height()));
            } else if($(this).css('font-size')) {
                size[i] = Math.ceil(parseInt($(this).css('font-size')));
            }
        });
    };
    var runDropdownToggle = function(func, threshold, execAsap) {
        if(isMobile == false) {
            $('.dropdown-toggle').dropdownHover({
                delay: 0
            });
        }
    };
    //Window Resize Function
    var runWindowResize = function(func, threshold, execAsap) {
        //wait until the user is done resizing the window, then execute
        $(window).clipresize(function() {
            screen_height = win.height();
            screen_width = win.width();
            if(screen_width < 979) {
                $('.navbar-default').removeAttr('style');
                navbar_brand.removeAttr('style');
                navbar_brand.contents().filter(function() {
                    return this.nodeType !== 3;
                }).each(function(i) {
                    $(this).removeAttr('style');
                });
            } else {
                navigation_position_top = $('#topbar').outerHeight();

            }
            runElementsPosition();

            animateElements();
        });
    };
    //Set all Animated Elements
    var setAnimations = function() {
        $('.animate-group').each(function() {
            $(this).find('.animate').each(function() {
                runElementsAnimation($(this));
            });
        });
        $('.animate-if-visible').each(function() {
            runElementsAnimation($(this));
        });
    };
    //Search Box Function
    var setSearchMenu = function() {
        $('.menu-search > a').bind('click', function(e) {
            if($('.search-box').is(":hidden")) {
                $('.search-box').css({
                    scale: 0.8,
                    opacity: 0,
                    display: 'block'
                }).transition({
                    scale: 1,
                    opacity: 1
                }, 200, 'easeOutBack');
            } else {
                $('.search-box').transition({
                    scale: 0.9,
                    opacity: 0
                }, 200, 'easeInBack', function() {
                    $(this).hide();
                });
            }
            return false;
            e.stopPropagation();
        });
        $('.menu-search').bind('click', function(e) {
            e.stopPropagation();
        });
        $('html').click(function() {
            if($('.search-box').is(":visible")) {
                $('.search-box').transition({
                    scale: 0.9,
                    opacity: 0
                }, 200, 'easeInBack', function() {
                    $(this).hide();
                });
            }
        });
    };
    //Function to shrink navigation menu when scrolling down
    var runElementsPosition = function() {
        scroll_top = win.scrollTop();
        screen_height = win.height();
        new_navbar_height = navbar_height - scroll_top;
        if(isMobile == false && screen_width > 979) {
            new_logo_font_size = logo_font_size * navbar.outerHeight() / navbar_height;
            if(navigation_position_top > 0) {
                sticky_navigation();
            }
            if(scroll_top == 0) {
                navbar.css({
                    'height': navbar_height,
                    'line-height': (navbar_height - 2) + 'px'
                });
                navbar.find('.navbar-nav').children('li').children('a').css({
                    'height': navbar_height,
                    'line-height': (navbar_height - 2) + 'px'
                });
                body.css({
                    'padding-top': navbar_height + $('#topbar').outerHeight()
                });
                navbar_brand.css('font-size', logo_font_size + 'px');
                navbar_brand.contents().filter(function() {
                    return this.nodeType !== 3;
                }).each(function(i) {
                    if($(this).is('img')) {
                        $(this).css({
                            'height': size[i] + 'px',
                            'width': 'auto'
                        });
                    } else if($(this).css('font-size')) {
                        $(this).css('font-size', size[i] + 'px');
                    }
                });
            } else if(scroll_top < navbar_height && new_navbar_height >= min_height) {
                navbar_brand.css('font-size', new_logo_font_size + 'px');
                navbar_brand.contents().filter(function() {
                    return this.nodeType !== 3;
                }).each(function(i) {
                    if($(this).is('img')) {
                        $(this).css({
                            'height': Math.ceil(size[i] * navbar.outerHeight() / navbar_height) + 'px',
                            'width': 'auto'
                        });
                    } else if($(this).css('font-size')) {
                        $(this).css('font-size', Math.ceil(size[i] * navbar.outerHeight() / navbar_height) + 'px');
                    }
                });
                navbar.css({
                    'height': new_navbar_height,
                    'line-height': (new_navbar_height - 2) + 'px'
                });
                navbar.find('.navbar-nav').children('li').children('a').css({
                    'height': new_navbar_height,
                    'line-height': (new_navbar_height - 2) + 'px'
                });
                body.css({
                    'padding-top': new_navbar_height + $('#topbar').outerHeight()
                });
            } else {
                navbar.css({
                    'height': min_height,
                    'line-height': (min_height - 2) + 'px'
                });
                navbar.find('.navbar-nav').children('li').children('a').css({
                    'height': min_height,
                    'line-height': (min_height - 2) + 'px'
                });
                body.css({
                    'padding-top': min_height + $('#topbar').outerHeight()
                });
                new_logo_font_size = logo_font_size * navbar.outerHeight() / navbar_height;
                navbar_brand.css('font-size', Math.ceil(new_logo_font_size) + 'px');
                navbar_brand.contents().filter(function() {
                    return this.nodeType !== 3;
                }).each(function(i) {
                    if($(this).is('img')) {
                        $(this).css({
                            'height': Math.ceil(size[i] * navbar.outerHeight() / navbar_height) + 'px',
                            'width': 'auto'
                        });
                    } else if($(this).css('font-size')) {
                        $(this).css('font-size', Math.ceil(size[i] * navbar.outerHeight() / navbar_height) + 'px');
                    }
                });
            }
        }
    };
    //Set of functions to manage the animations of the elements
    var animateElements = function() {
        if($('.animate-if-visible').length) {
            $('.animate-if-visible').appear();
            $(document.body).on('appear', '.animate-if-visible', function(e, $affected) {
                // this code is executed for each appeared element
                var element = $(this);
                var animationOptions = element.data('animation-options');
                runAnimationTransition(element, animationOptions);
            });
        }
        if($('.animate-group').length) {
            $('.animate-group').appear();
            $(document.body).on('appear', '.animate-group', function(e, $affected) {
                var element = $(this);
                var animationInterval = 200;
                if( typeof $(this).data('animation-interval') !== 'undefined') {
                    animationInterval = parseInt($(this).data('animation-interval'));
                }
                var totalAnimations = 0;
                var elements = [];

                element.find('.animate').each(function(n) {
                    elements[n] = $(this);
                    totalAnimations++;
                });
                runAnimationGroup(elements, totalAnimations, 0, animationInterval);

            });
        }
        // Force appear. This is suitable in cases when page is in initial state (not scrolled and not resized)
        $.force_appear();
    };
    var sticky_navigation = function() {
        if(scroll_top == 0) {
            navbar.css({

                'top': navigation_position_top + 'px'
            });
        } else if(scroll_top > navigation_position_top) {
            navbar.css({
                'top': 0
            });
        } else if(scroll_top < navigation_position_top && scroll_top > 0) {
            navbar.css({
                'top': navigation_position_top - scroll_top + 'px'
            });
        }
    };
    var runAnimationGroup = function(element, totalAnimations, actual, animationInterval) {
        if(actual < totalAnimations) {
            var animationOptions = element[actual].data('animation-options');
            setTimeout(function() {
                runAnimationTransition(element[actual], animationOptions);
                actual++;
                runAnimationGroup(element, totalAnimations, actual, animationInterval);
            }, animationInterval);
        }
    };
    var runElementsAnimation = function(element) {
        var animationOptions = element.data('animation-options');
        if( typeof animationOptions == 'undefined') {
            animationOptions = new Object;
            animationOptions.animation = "Fade";
        }
        switch (animationOptions.animation) {
            case 'scaleIn':
                element.css({
                    opacity: 0,
                    scale: 0.6
                });
                break;
            case 'scaleToBottom':

                original_height = element.height();

                element.data('original-height', original_height).data('original-width', element.width()).css({
                    opacity: 0,
                    transform: 'translateY(-' + original_height / 2 + 'px); scaleY(0.001)'
                });
                break;
            case 'scaleToRight':

                original_width = element.width();

                element.data('original-height', element.height()).data('original-width', original_width).css({
                    opacity: 0,
                    transform: 'translateX(-' + original_width / 2 + 'px); scaleX(0.001)'
                });
                break;
            case 'scaleToTop':

                original_height = element.height();

                element.data('original-height', original_height).data('original-width', element.width()).css({
                    opacity: 0,
                    transform: 'translateY(' + original_height / 2 + 'px); scaleY(0.001)'
                });
                break;
            case 'scaleToLeft':

                original_width = element.width();

                element.data('original-height', element.height()).data('original-width', original_width).css({
                    opacity: 0,
                    transform: 'translateX(' + original_width / 2 + 'px); scaleX(0.001)'
                });
                break;
            default :
                element.css({
                    opacity: 0
                });
                break;
        }
    };
    var runAnimateProgressBar = function() {
        if($('.animate-bar').length) {
            $('.animate-bar').appear();
            $(document.body).on('appear', '.animate-bar', function(e, $affected) {
                $(this).progressbar({
                    display_text: 'center',
                    use_percentage: true
                });
            });
        }
    };
    var runAnimationTransition = function(element, animationOptions) {
        if( typeof animationOptions == 'undefined') {
            animationOptions = new Object;
            animationOptions.animation = "fadeIn";
        }
        var animationType = animationOptions.animation;
        var animationDelay = animationOptions.delay;
        var animationDuration = animationOptions.duration;
        var animationEasing = animationOptions.easing;
        if( typeof animationType === 'undefined') {
            animationType = "fadeIn";
        }
        if( typeof animationDelay === 'undefined') {
            animationDelay = 0;
        }
        if( typeof animationDuration === 'undefined') {
            animationDuration = 300;
        }
        if( typeof animationEasing === 'undefined') {
            animationEasing = 'linear';
        }
        switch (animationType) {
            case 'scaleIn':
                element.transition({
                    opacity: 1,
                    scale: 1,
                    duration: animationDuration,
                    delay: animationDelay,
                    easing: animationEasing
                });
                break;
            case 'scaleToRight':
            case 'scaleToLeft':
                element.transition({
                    opacity: 1,
                    transform: 'scaleX(1)',
                    duration: animationDuration,
                    delay: animationDelay,
                    easing: animationEasing
                });
                break;
            case 'scaleToBottom':
            case 'scaleToTop':
                element.transition({
                    opacity: 1,
                    transform: 'scaleY(1)',
                    duration: animationDuration,
                    delay: animationDelay,
                    easing: animationEasing
                });
                break;
            default:

                animationDuration = animationDuration / 1000 * 2 + 's';
                animationDelay = animationDelay / 1000 * 2 + 's';
                element.css({
                    opacity: 1,
                    'animation-fill-mode': 'both',
                    'animation-duration': animationDuration,
                    'animation-delay': animationDelay,
                    'animation-name': animationType
                });
                break;
        }
    };
    // Function to display an icon on the images on hover
    var runImageOverlay = function() {
        if($('.image-overlay').length && !$('body').hasClass('isMobile')) {
            $('.image-overlay').hover(function() {
                $(this).transition({
                    opacity: 0.7
                }).find('.circle-icon').css({
                    rotate: '-90deg'
                }).transition({
                    rotate: '0deg',
                    easing: 'easeOutBack'
                }, 400);
                ;
            }, function() {
                $(this).transition({
                    opacity: 0
                });
            });
        }
    };
    // function to initiate FlexSlider
    var runFlexSlider = function(options) {
        $(".flexslider").each(function() {
            var slider = $(this);
            var defaults = {
                animation: "slide",
                animationLoop: false,
                controlNav: true,
                directionNav: false,
                slideshow: false,
                prevText: "",
                nextText: ""
            };
            var config = $.extend({}, defaults, options, slider.data("plugin-options"));
            if( typeof config.sync !== 'undefined') {
                var carousel = {
                    animation: "slide",
                    controlNav: false,
                    animationLoop: false,
                    slideshow: false,
                    prevText: "",
                    nextText: "",
                    asNavFor: slider
                };
                var configCarousel = $.extend({}, carousel, $(config.sync).data("plugin-options"));
                $(config.sync).flexslider(configCarousel);
            }
            // Initialize Slider
            slider.flexslider(config);
        });
    };
    // function to handle SlideBar Toggle
    var runSideBarToggle = function() {
        $(".sb_toggle").click(function() {
            sb_toggle = $(this);
            $("#slidingbar").slideToggle("fast", function() {
                if(sb_toggle.hasClass('open')) {
                    sb_toggle.removeClass('open');
                } else {
                    sb_toggle.addClass('open');
                }
            });
        });
    };
    // function to handle Scroll Top button
    var runScrollTop = function() {
        scroll_top = win.scrollTop();
        scroll_top_button = $('#scroll-top');
        if(scroll_top > 300) {
            scroll_top_button.fadeIn();
        } else {
            scroll_top_button.fadeOut();
        };
        scroll_top_button.off("click").on("click", function(e) {
            $("html, body").animate({
                scrollTop: 0
            }, "slow");
            e.preventDefault();
        });
    };
    // function to be activated when you scroll the page
    var runWindowScroll = function() {
        $(window).scroll(function(e) {
            runScrollTop();
            runElementsPosition();

        });
    };
    //Set of functions for Style Selector
    var runStyleSelector = function() {
        $('.style-toggle').bind('click', function() {
            if($(this).hasClass('open')) {
                $(this).removeClass('open').addClass('close');
                $('#style_selector_container').hide();
            } else {
                $(this).removeClass('close').addClass('open');
                $('#style_selector_container').show();
            }
        });
        setColorScheme();
    };
    var setColorScheme = function() {
        $('.icons-color a').bind('click', function() {
            $('.icons-color img').each(function() {
                $(this).removeClass('active');
            });
            $(this).find('img').addClass('active');
            $('#skin_color').attr("href", "assets/css/theme_" + $(this).attr('id') + ".css");

        });
    };
    //function to save user settings
    var runSaveSetting = function() {
        $('.save_style').bind('click', function() {
            var clipSetting = new Object;

            clipSetting.skinClass = $('#skin_color').attr('href');
            $.cookie("clip-front-setting", JSON.stringify(clipSetting));
            var el = $('#style_selector_container');
            el.block({
                overlayCSS: {
                    backgroundColor: '#fff'
                },
                message: '',
                css: {
                    border: 'none',
                    color: '#333',
                    background: 'none'
                }
            });
            window.setTimeout(function() {
                el.unblock();
            }, 1000);
        });
    };
    //function to load user settings
    var runCustomSetting = function() {
        if($.cookie("clip-front-setting")) {
            var loadSetting = jQuery.parseJSON($.cookie("clip-front-setting"));

            if($('#style_selector').length) {
                $('#skin_color').attr('href', loadSetting.skinClass);
            };
        };
    };
    //function to clear user settings
    var runClearSetting = function() {
        $('.clear_style').bind('click', function() {
            $.removeCookie("clip-front-setting");
            $('.icons-color img').first().trigger('click');

        });
    };

    //function to activate the Tooltips, if present
    var runTooltips = function() {
        if($(".tooltips").length) {
            $('.tooltips').tooltip();
        }
    };
    //function to activate the Popovers, if present
    var runPopovers = function() {
        if($(".popovers").length) {
            $('.popovers').popover();
        }
    };
    return {
        //main function to initiate template pages
        init: function() {
            runInit();
            animateElements();
            setSearchMenu();
            runDropdownToggle();
            runFlexSlider();
            sticky_navigation();
            setAnimations();
            runImageOverlay();
            runAnimateProgressBar();
            runWindowScroll();
            runWindowResize();
            runTooltips();
            runPopovers();
            runStyleSelector();
            runElementsPosition();
            animateElements();
            runSideBarToggle();
            runScrollTop();
            runSaveSetting();
            runCustomSetting();
            runClearSetting();
        }
    };
}();

A: I had the same issue with chrome, after commenting
//animation: "slide",

out, it worked!
HTH

A: The site was simply missing the proper Javascript initialization, and adding the following fixed the issue.

A: Make sure you're initializing the plugin properly with a function such as this:
$('#myId').flexslider();

That said, I'm not sure why it works in one browser and not others.


text:
Q: What is the best way to invoke action in Form1 When Form2 is closed without using ShowDialogue in C# Windows Form Application? I've a project that contain 2 forms e.g. (Form1 , Form2 ).The user should be able to use any of the 2 forms while both of them are visible(i.e. Can use Form1 While Form2 is Open).At the same time when Form2 is closed there is an action that should be invoked in Form1 related to From2_close. I can't use Form2.ShowDialogue as it trap focus only to Form2 but user should be able to edit some data in Form1 while Form2 is loaded. Hope the question is clear, please help. Thanks

A: Handle either the FormClosed or VisibileChanged event.  When one of those events fires you know the form has been closed or hidden and can react accordingly.

A: Your question is not entirely clear, but I think you are trying to send a notification to a given set of forms based on any other forms actions.  This type of notification scenerio can be very easily handled by implementing the Observer Pattern. Basically you have a single object that is the "observer" and it watches subscribers that register with it for messages.  When the observer receives a message from one of its subscribers (ie a form) it then notifies the other subscribers that it received a message.
Hope this helps.

A: ShowDialog creates a modal dialog, which means that no other code in the calling thread will execute until the form closes. In this case, the dialog is blocking the GUI thread on your other form, which means that the user can't use it.
Instead of using ShowDialog to create an instance of Form1 from Form2 (or vice-versa), as I'm guessing you are currently doing it, just instantiate the other form.
Form1's Load handler:
Form2 form2 = new Form2();
form2.Show();

*EDIT
To allow each form to be closed without the other closing or the application exiting, do this:
In Program.cs, you'll see a call to Application.Run that creates a new instance of Form1 and starts the application. Replace that with the code from above, repeated twice, to create Form1 and Form2. After those two calls, add in a plain Application.Run() call.
Then, in each form, handle the FormClosing event by instead exiting the application if both forms are closed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Download location for MAPI33.dll? From where can I download MAPI33.dll. I got the link http://www.mapi33.adexsolutions.com/ from a site but it seems this is not correct.

A: You can find an older version here:
http://g8.cx/mapi/
The newest version must be bought.
I cite:

The following code samples might be
  obsolete. They might not work with
  current version of the mapi33 dll,
  though they will still work using the
  out-of-date (but quite well-working
  and free) version of the mapi33 dll
  included in the samples zip file.
To get up-to-date information about
  the mapi33 dll and to buy the most
  recent version, visit the mapi33
  website at
  http://www.mapi33.adexsolutions.com/

The link to the company homepage seem to be outdated.
The samples link however is not. It can be found under section 4 there or as a direct link here:
http://g8.cx/mapi/ExtendedMapiWithCSharp_sourcecode.zip
I verified that the samples link was working when I wrote this.


text:
Q: "Python was not found" error when it is installed in the Windows Directory I was trying to run the command "python get-pip.py" to install the pip package manager but I got the "Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings" error. The issue is that I do have python installed. I have the file C:\Windows\py.exe which means its installed.
I assume the issue is something related to the System Environment Variables. But what exactly do I need to modify?


text:
Q: Can sessions work without cookies? If so, how does a session work without cookies enabled in PHP? I am searching for main difference b/w session and cookies and when to use session and cookies.Please clarify.Thanks

A: As another user linked to, yes they can, there are config options for php to not use cookies and instead rely on passing the session id as part of the url. You can either do this manually, or ask PHP to do it. If PHP is set to automatically add the ID, then it uses output buffering to replace any urls it detects in your output, it does this by default on certain tags (a, form etc.)
See options here: http://php.net/manual/en/session.configuration.php

session.use_cookies boolean
  session.use_cookies specifies whether the
  module will use cookies to store the session id on the client side.
  Defaults to 1 (enabled).
session.use_trans_sid boolean
  session.use_trans_sid whether
  transparent sid support is enabled or not. Defaults to 0 (disabled).
session.trans_sid_tags string
  session.trans_sid_tags specifies which
  HTML tags are rewritten to include session id when transparent sid
  support is enabled. Defaults to
  a=href,area=href,frame=src,input=src,form= form is special tag.  is added as form variable.

Also heed its warnings:

Note: URL based session management has additional security risks
  compared to cookie based session management. Users may send a URL that
  contains an active session ID to their friends by email or users may
  save a URL that contains a session ID to their bookmarks and access
  your site with the same session ID always, for example. Since PHP
  7.1.0, full URL path, e.g. https://php.net/, is handled by trans sid feature. Previous PHP handled relative URL path only. Rewrite target
  hosts are defined by session.trans_sid_hosts.

Cookies and Sessions
Generally sessions do use cookies. You asked for the difference between sessions and cookies; although not really comparable here is some info on them both:
Cookies
Cookies are a method of storing simple key/value pairs locally within the browsers storage, then can persist between browser restarts, but the user can wipe them. Cookies can not total more than 4KB (see What is the maximum size of a web browser's cookie's key?)
From the docs: http://php.net/manual/en/function.setcookie.php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);

// Print an individual cookie
echo $_COOKIE["TestCookie"];

Sessions
When you call session_start() php checks the cookies to see if it has already set a 'session id', and if not sets one. It then uses this to identify the user/session, and allows you to temporarily save data on the server attributed to this id. each time you call session_start it will populate $_SESSION, and at the end of each script it will save this. This does mean that pages cannot load simultaneously if they both use sessions. some good examples of sessions can be seen here: https://www.w3schools.com/php/php_sessions.asp
Sessions don't have a limit as such, but are limited by other factors (see Maximum size of a PHP session)
Summary

*

*Sessions generally use cookies

*Cookie Data is stored locally, Session Data is stored on server

*Cookie Data size limit is relatively small (4K), Session Data is only limited by other things.

*Cookie Data is just simple key/value pairs, Session data can also be arrays, objects


text:
Q: Which is the most performant way to compare two digits? I need to compare a lot of integer values to equality.
Which method is the fastest?
A)
int a1 = 12345;
int a2 = 54321;
if(a1 == a2)
{
   //do something.
}

B)
int a1 = 12345;
int a2 = 54321;
if( (a1 ^ a2) == 0 )
{
   //do something.
}

A: I suspect first is actually faster anyway. It's not like comparing two integers for equality is an uncommon operation, so I imagine it's pretty well supported :) However, far more importantly it's much, much more readable.
It seems very unlikely to me that comparing integers for equality will be your bottleneck. If you really feel it is, then by all means benchmark what you've got in as realistic a situation as you can, then try various changes (perhaps XOR, perhaps subtraction etc) and remeasure. But do make sure you've actually got something you need to fix before spending time moving away from the most obvious, simple, readable code.

A: The only way to answer a question like this is to measure it, in your specific application and environment.
But do the first and don't worry about it.   There's nothing you're likely to do in C# where this is going to be an issue.
If you're in some bizarre corner case of performance where you really do have better knowledge  about how to compare integers than the MS tools team, then you should be writing in assembler.
Personally, I cannot imagine a scenario where the comparison of two integers in a tight loop will dominate your timing -  the loop and branching overhead is going to be similar or greater than the comparison cost, and even then that assumes that this great block of data has magically appeared in CPU cache without any paging or memory I/O cost.
Rococo substitutions for operations like compares (and set-to-zero and multiply-by-constant powers of two) haven't been appropriate with proper commercial tool chains (craptastic embedded C compilers might still need them) for the best part of 20 years.   It's time to stop thinking about them.

A: I have wrote some code to verify this.
static void Main( string[] args )
{
  int a1 = 123456;
  int a2 = 654321;
  int a3;

  var t = new System.Diagnostics.Stopwatch();
  t.Start();
  for ( int i = 0; i < int.MaxValue; i++ )
  {
    if ( a1 == a2 )
    {
      a3 = a1 + a2;
    }
  }
  t.Stop();

  Console.WriteLine( t.ElapsedMilliseconds );

  t.Reset();

  t.Start();
  for ( int i = 0; i < int.MaxValue; i++ )
  {
    if ( ( a1 ^ a2 ) == 0 )
    {
      a3 = a1 + a2;
    }
  }
  t.Stop();

  Console.WriteLine( t.ElapsedMilliseconds );

  Console.ReadKey();
}

The result is the next:
For the first  6275 milliseconds
For the second 6277 milliseconds
It looks that these methods works identical.
Thanks for your answers.

A: The first one. Because both of them do a comparing operation (==), but the second one uses additional XOR operation.


text:
Q: Google Mobile Ads SDK was initialized incorrectly Not sure why but I am getting this when trying to start the app on an emulator

Also this is what is setup in project/android/app/src/main/AndroidManifest.xml

And here is the initialize code:

Any help would be appreciated

A: Your meta-data tag is not getting recognized. You should have the meta-data tag for ads outside of the activity tag and within the application tag


text:
Q: Не происходит асинхронное выполнение Не происходит асинхронное выполнение запросов. Получение запросов
from flask import request, render_template
from app import app_flask, token_flask, forms
from analytical import database

@app_flask.route('/api', methods=['POST'])
async def api_request():
    token_api = request.json['token']
    repository_path = request.json['repository_path']
    instance_db_client = database.DataBaseHandler()
    print('db-', type(instance_db_client.get_report))
    return await instance_db_client.get_report(repository_path, token_api)

@app_flask.route('/', methods=['GET', 'POST'])
async def main_page():
    if request.method == 'GET':
        form = forms.RepositoryPathForm()
        return render_template('index.html', form=form), 200
    elif request.method == 'POST':
        form = forms.RepositoryPathForm()
        repository_path = request.form['link_repository']
        instance_db_client = database.DataBaseHandler()
        json, code = await instance_db_client.get_report(repository_path, token_flask)
        return render_template('index.html', form=form, json=json), code

@app_flask.errorhandler(404)
async def page_not_found(error):
    return 'Страницы не существует!!', 404

Обращение к постороннему серверу, предполагаю где то тут ошибка
    async def link(self):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(url=self.url, headers=self.headers, json=self.json) as resp:
                    data = json.loads(await resp.read())
                return data
        except requests.exceptions.ConnectionError as e:
            logger.error(f'ERROR500! Ошибка ссоединения с сервером. Исключение: {e}')
            resp_json.query_info.code = 500
            resp_json.query_info.error_desc = 'ConnectionError'
            resp_json.query_info.error_message = str(e)

Тестирую на сервере debian, запущено через nginx и gunicorn.
Для теста запускаю gunicorn с одним worker'ом.
Программа выполняется в синхронном режиме, пока запрос не пройдет другие запросы не принимает.
Возможно что то нужно настроить в gunicorn или nginx, но я к сожалению не нашел. При запуске в отладочном режиме выдает ошибку (но продолжает работать)
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000285CD08FF40>
Traceback (most recent call last):
  File "C:\Users\vi812\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\vi812\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\vi812\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
    self._check_closed()
  File "C:\Users\vi812\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

A: Хоть вы и используете корутины, вся это асинхронность работает в контексте синхронного фреймворка. Здесь смысл асинхронности насколько я понимаю, чтобы в контексте одного запроса получить возможность асинхронно запускать различные функции(получение данных с бд и допустим еще какие-то задачи ввода вывода). Но в целом запросы не обрабатываются асинхронно


text:
Q: How to account for nominal resolution in calibration measurements? I have a real world question but I think it'll be clearer if I phrase it like a "homework" question so here goes*:
A physicist is trying to use a laser measuring device to determine the length of a piece of string with high accuracy. Their device has a nominal resolution of $\pm 10 \mu m$, which the user manual goes on to explain refers to the edges of a triangular probability distribution of where the true value the device reads might lie. That is the readings it outputs are in 10 micron increments and a value of $1,350 \mu m$ actually represents a triangular probability density function centred around $1,350$ with width $\pm 10$ (see diagram below)

The physicist also notices though that the device is inconsistent; when they try to calibrate it by measuring a known length of string, there is some seemingly random noise in the readings. They decide that by taking a few samples of known lengths and seeing how far off the device is, they can find a probability distribution for the typical error in the device and subtract this from the readings to calibrate it.
The experimental setup is simple. For a known length calibration piece of $1000\mu m$, several measurements are taken. These might be as below:

Measurement No
Value ($\mu m$)

1
1050

2
1010

3
980

4
990

5
1010

6
1000

7
1040

8
980

... so clearly there is some rounding owing to the instrument resolution, and some uncertainty from other factors. Using this information, the physicist would like to model the error as a Normal distribution $Err\sim\cal N\left( {\mu,\sigma^2} \right)$ and calculate the most likely values for those parameters...
 * The caveat for asking this in homework style is I may have missed out some important details required to give an answer, so if you need clarification or more details please ask
My approach
Ok so I have 2 approaches:

*

*At first I thought of fitting a normal distribution to the data. This is done by first plotting each measurement and its triangular resolution pdf. I then find $\mu$ (which is just $\bar{x}$, easy to calculate since the resolution error is symmetric). Finally I find the value of $\sigma$ which maximises the overlap between the measurements and the resultant distribution with integration - i.e. maximises the likelihood of observing those measurements weighted by their resolution distributions.

*However I remembered that samples from a normal population are t-distributed - appearing closer to the centre than expected and having a smaller standard deviation than the population would (making the first approach inaccurate). To solve this, I could try and fit a Student t-distribution to my samples, however I wasn't sure how many degrees of freedom to use since my measurements are pdfs, not individual values.

So I'm a bit stumped on how to fit to a t-distribution or what adjustments I need (given the small sample count and large relative resolution error, $\sigma$ I expect will be larger than just the sample standard deviation of the data itself).

A: First things first, in the comments you mentioned there is an offset from the sample mean and the calibration length, implying there is a bias in your measurements. This is very important to understand -- for example, can it be corrected by subtracting a constant value, or by rescaling by a certain factor? My suggestion is to try different calibration lengths, and see how the bias depends on the length of the string. A subtlety here is that you need a way to know the length of your calibration string with at least as much precision as your measuring device, but without using the measuring device you're trying to calibrate; I trust you have a way to do this. Below, I'm assuming you have a way to correct the bias, and apply it to $d_i$. You can also extend all the analysis below to include a "calibration parameter", say by rescaling the data in the likelihood; I can add some comments if you want.
In terms of the error analysis, in the comments you mentioned a Bayesian analysis would be worth doing -- as I mentioned this is on the upper end of the "effort" scale (so this answer is pretty involved!), but the net result will be a flexible framework to get a posterior probability distribution for the length $\ell$, able to incorporate multiple kinds of uncertainty. Before getting stuck in, I'll just mention some simpler (but less rigorous) approaches would be to: (a) look at the standard deviation of the means of the measurements you've done to get a "calibration error" that you can add in quadrature to other uncertainties, (b) fit a Gaussian directly to your observed data with the mean and standard deviation as parameters (this is your option 1 above, and also the first Bayesian model I consider below, but you don't need an MCMC sampler to do this if that's all you need).
If the parameter space is not too large, it's not too much work to code up something that will evaluate the likelihood on a grid and compute/plot the posterior (as well as desired credible intervals), in your favorite programming language (I am partial to python). Alternatively, if you don't want to do that or if you have more than 2 or 3 parameters, it's better to use a sampler. There are several off-the-shelf samplers that are pretty good: emcee is a good MCMC sampler in python, and dynesty is a nested sampler. If you don't know much about samplers, it's probably better to stick with an MCMC sampler to start with, since the way they work is easier to understand and their output is easier to interpret (in my opinion), and also practically speaking it's possible to get intermediate results while the sampler is running (unlike nested sampling).
The main ingredients to a Bayesian analysis are the likelihood and prior.
The likelihood is the probability of the data given the model, $p(d_i|\Theta)$, where $d_i = \{d_1, d_2, \cdots, d_N\}$ are the data (in your case, a list of $N$ observed lengths) and $\Theta$ are the model parameters (we'll consider a few options). My philosophy is to start with a simple model and make it more complicated if it fails. A simple starting point would be to say the combination of the "resolution error" and other errors can be described with a Gaussian distribution:
\begin{equation}
p_{\rm G.L.}(d_i|\ell,\sigma) = \prod_{i=1}^N \frac{1}{\sqrt{2\pi \sigma^2}}e^{-(d_i-\ell)^2/2\sigma^2}
\end{equation}
where "G.L." stands for "Gaussian likelihood" (to be compared with a few other options below), and where the model parameters are

*

*$\ell$: the length of the string -- this is what you want to fit to the data). I am assuming all the data are measurements of the same string, so note that $\ell$ does not depend on the sample number, $i$.

*$\sigma$: the uncertainty -- in our simple model, all uncertainty (the "triangle" resolution, and all other sources of uncertainty) will be folded into this parameter. Again, I'm assuming the uncertainty for each measurement is the same. I'm also assuming the measurements are independent, so there is no covariance.

Regardless of whether or not you decide to make the model more complicated, I would start off by implementing this Gaussian model in your sampler of choice, because it is simple and you want to get your code working on a simple model before extending it.
Another simple model would be to say that the noise comes entirely from the resolution (triangle distribution) error. Again, I think this model is worth coding up even it it is not a perfect fit. In this case, the model is
\begin{equation}
p_{\rm T.L.}(d_i|\ell,\Delta) = \prod_{i=1}^N p_i
\end{equation}
where "T.L." means "Triangle Likelihood", and where the likelihood for a single measurement $p_i$ is
\begin{equation}
p_i =
\begin{cases}
\frac{4}{\ell \Delta }\left(d_i - \ell\right) , \ \ \ell - \frac{\Delta}{2}< d_i < \ell \\
\frac{4}{\ell \Delta }\left(\ell - d_i\right), \ \ \ell < d_i < \ell + \frac{\Delta}{2} \\
0, \ \ {\rm otherwise}
\end{cases}
\end{equation}
The parameters in this case are

*

*$\ell$ (the true length of the string), and

*$\Delta$, the width of the resolution, which you could either assume took the value given by the manufacturer (in which case you would not sample over this parameter but just fix it to its given value), or try to measure from the data by taking it as a free parameter.

Alternatively, you could try to make the model more complicated in various ways. One way would be to say that the data consists of the length plus the noise, $d=n+\ell$, and the noise $n$ consists of two contributions that are added together, $n=n_t + n_g$, where $n_t$ is drawn from the triangle distribution and $n_g$ is drawn from a gaussian distribution. Then your likelihood would look something like
\begin{eqnarray}
p_{\rm M.L.}(d_i|\ell,\sigma,\Delta) &=& \prod_{i=1}^N \int {\rm d} n_t \int {\rm d} n_g \delta(d_i-\ell-n_g-n_t) p_{\rm T.L.}(n_t|\ell,\Delta) p_{\rm G.L.}(n_t|\ell, \sigma) \\
&=& \prod_{i=1}^N \int_{-\Delta/2}^{\Delta/2} {\rm d} n_t p_{\rm T.L.}(n_t|\ell,\Delta) p_{\rm G.L.}(d_i-\ell-n_t|\ell, \sigma)
\end{eqnarray}
where "M.L." means "Mixture Likelihood." The logic of the first line is that we add all possible values of $\ell, n_t, n_g$, consistent with the idea that the data are a sum of these three quantities $d_i=\ell+n_t+n_g$ (this is the integral + delta function). For each possibility, we multiply the probability $p_{\rm T.L.}$ that the "triangle noise" will be $n_t$ with the probability $p_{\rm G.L.}$ that the "Gaussian noise" will be $n_g$. The second line is one way of evaluating the integral over the delta function, but seems natural to me.
Anyway, the point of this discussion is not so much to suggest any one particular model (I would use the first two as training and the third one as my first "real" case, based on what you said in the question and comments). But, to point out the kind of logic you can use to build models of your uncertainty and fit them into a Bayesian framework.
You also need to decide on priors. Generally, a good starting point is to place uninformative priors on your parameters. While there are lots of debates as to what this means, a simple and justifiable choice is to take uniform priors on every parameter.

*

*For $\ell$, you want a wide enough region that the posterior does not "hit the rails" of the range you choose (sometimes this takes some trial and error, running the sampler multiple times). Based on the numbers in your table, a conservative choice would be to take a prior on $\ell$ that ranged from $0$ to twice the "true" value.

*For $\sigma$, taking a range that went from, say, half the observed standard deviation of the sample means, to twice, should probably be sufficient.

*For $\Delta$, as stated above, you could fix it to the manufacturer value. Alternatively, you could try to determine this parameter from the data. If you do the latter, I would choose a uniform prior centered on the manufacturer's value, that was not too broad -- unless you start seeing evidence in the posterior that a much different value is strongly preferred.

Once you code up the likelihood and prior in whatever format is needed by your chosen sampler, run the code and look at the results! The results will take the form of samples drawn from the posterior distribution $p(\Theta|d_i)$ of the parameters given the data, obtained using Bayes theorem
\begin{equation}
p(\Theta|d_i) = \frac{p(d_i|\Theta) p(\Theta)}{p(d_i)}
\end{equation}
where $p(d_i|\Theta)$ is the likelihood (which we discussed in detail), $p(\Theta)$ is the prior (I gave some advice above), and $p(d_i)$ is a normalization constant sometimes called the "evidence" (which you don't need to compute if you are only interested in the probability of different parameters). At the end of the day, I think you will want to construct the "1-dimensional marginalized posterior" for $\ell$. In other words, assuming we work in the G.L. model, you would want to plot
\begin{equation}
p(\ell|d_i) = \int_{\sigma_{\rm min}}^{\sigma_{\rm max}} {\rm d} \sigma p(\ell,\sigma|d_i)
\end{equation}
where $\sigma_{\rm min}$ and $\sigma_{\rm max}$ are the bounds of the prior on $\sigma$.
With the output of the MCMC sampler (samples drawn from the posterior distribution), this procedure can be done by simply histogramming the samples by the value of $\ell$.
Some practical advice on interpreting the output of MCMC samplers (and in particular checking for convergence and other problems that can arise) can be found here:

*

*https://www.ukdataservice.ac.uk/media/307220/presentation4.pdf

*https://machinelearningmastery.com/markov-chain-monte-carlo-for-probability/

*https://arxiv.org/abs/1909.11827


text:
Q: how to pass customer_id from one window to another? I have two windows w_customerorder and w_customerfree and the cusromerorder window has orderid which is identity column.now i want to pass this orderid to the customerfree window which has orderid column while its opening.can any one help me with this?

A: Do you open w_customerfree from w_customerorder?
Then you can use openwithparm(w_customerfree, ll_orderid)
and in the w_customerfree window you write ll_orderid = Message.longparm in the open() event.
Even if you don´t open w_customerfree from w_customerorder you can use the Message.longparm variable. Then you just fill it manually in w_customerorder
Message.longparm = ll_orderid


text:
Q: How to hide / protect WCF URL in JQuery code I am using JQuery to interact with a WCF REST service. I would like to somehow hide or secure the url of my service..but I have no idea how to do this, any help?
function getMyUser() {
        var query = { "pLastName": null };
        query.pLastName = "m";
        var label = document.getElementById("idGetUsersByLastName");

        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "//THE URL I WANT TO HIDE",
                data: JSON.stringify(query),
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function (data) {

                    var zx = 5652;
                    label.innerHTML = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var zx = 5652;
                    MSApp.execUnsafeLocalFunction(function () {
                        label.innerHTML = XMLHttpRequest.responseText;
                    });
                }
            });
        });

    };

I believe something like going back to the server to check what the url is would work but no idea how to implement it.

A: You can't hide it, and knowing that, you should make sure that you do an appropriate level of  authentication you need to in order to prevent tampering/abuse - whether it be rate throttling or authentication.
You can't count on someone just not knowing about it as being good enough security - someone will eventually find it, and they will try to break it.

A: Instead of trying to hide the URL, try to fortify your service script by adding checks for unauthorized activity.


text:
Q: How can I select all elements of a class with a visible parent? EDIT: This selector is correct. There bug must be elsewhere in the code. So this question is no longer relevant.
EDIT2: The real problem was that my parent class had the inline style "display:inline" attached to it, apparently the visible selector doesn't like display:inline. After I took that out it started working.
EDIT3: An inline element with an unset height. JQuery says, anything with a height of zero, is considered invisible, I suppose my element with an unknown height was defaulted to zero.

This is what I have but it doesn't seem to be working..

   $('.parent-class:visible .my-class[state!="done"]')

I want to select all .my-class elements that their .parent-class element is visible.
Thank you!

A: try
 $(".parent-class:visible").children(".my-class[state!='done']").html("i am gone");

here is the fiddle http://jsfiddle.net/XAnqB/7/

A: Your selector should work, and it does work. In your fiddle, you have not included the jQuery library, so it doesn't work there! See this updated fiddle.

A: if you change the framework in jsfiddle to jquery instead of mootools it works

A: You have it so all descendents of the parent are selected.  The space is the "ancestor operator".
If you want only the direct children, use the > operator:
.parent-class:visible  > .my-class[state!="done"]'


text:
Q: Parceable causes Stackoverflow There is two classes, link each other someway. Problem is having Stackoverflow exception if I implements Parceable this way:

RSSFeed.java

 public class RSSFeed implements Parcelable {
    private String title;
    private String link;
    private ArrayList<RSSItem> rssItems;

public RSSFeed() {
    rssItems = new ArrayList<RSSItem>();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeStringArray(new String[] { this.title, this.link });
    Bundle b = new Bundle();
    b.putParcelableArrayList("rssItems", rssItems);
    dest.writeBundle(b);

}

public static final Parcelable.Creator<RSSFeed> CREATOR = new Parcelable.Creator<RSSFeed>() {
    @Override
    public RSSFeed createFromParcel(Parcel in) {
        RSSFeed rssFeed = new RSSFeed();

        String[] data = new String[2];
        in.readStringArray(data);
        rssFeed.title = data[0];
        rssFeed.link = data[1];

        Bundle b = in.readBundle(RSSItem.class.getClassLoader());
        rssFeed.rssItems = b.getParcelableArrayList("rssItems");
        return rssFeed;
    }

    @Override
    public RSSFeed[] newArray(int size) {
        return new RSSFeed[size];
    }
};

RSSItem.java

public class RSSItem implements Parcelable {
private RSSFeed feed;
private String title;

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    Bundle b = new Bundle();
    b.putParcelable("feed", this.feed);
    dest.writeStringArray(new String[] { this.title });
}

public static final Parcelable.Creator<RSSItem> CREATOR = new Parcelable.Creator<RSSItem>() {
    @Override
    public RSSItem createFromParcel(Parcel in) {
        RSSItem rssItem = new RSSItem();

        Bundle b = in.readBundle(RSSFeed.class.getClassLoader());
        rssItem.feed = b.getParcelable("feed");

        String[] dataString = new String[1];
        in.readStringArray(dataString);
        rssItem.setTitle(dataString[0]);

        return rssItem;
    }

    @Override
    public RSSItem[] newArray(int size) {
        return new RSSItem[size];
    }
};

So, it crushes with stackoverflow I guess because it's trying in writeParcel(...) to pass ArrayList<RSSItems> which one in writeParcel(...) try to pass RSSFeed member and again and again. So, the question is how to solve this problem to Parce two classes?

A: You have cycles in your object graph. Your RSSFeed put RSSItems  in the parcel, an RSSItem puts the parent RSSFeed in the parcel. Do not parcel one of these dependencies to kill the cycle. Usually the parent relationship i.e. from item to feed should not be parceled.


text:
Q: limit of functions and the integration Let $f_n:\mathbb{R}\rightarrow\mathbb{R}$ be a sequence of non-negative Lebesgue measurable functions and suppose $\lim_{n\rightarrow \infty}\int_\mathbb{R}f_n=0.$ Then, must it be that $\lim_{n\rightarrow \infty}f_n(x)=0 $ almost everywhere? I can easily prove $\liminf_{n\rightarrow \infty}f_n(x)=0 $ almost everywhere by Fatou's lemma, but it seems somewhat hard to prove the original statement.

A: Consider the characteristic functions of $[0,1],[0,1/2],[1/2,1],[0,1/3],[1/3,2/3],[2/3,1], \dots $


text:
Q: URL expire implementation in SF I am using Survey Force to send survey email to customer. The survey email contains a link which call a VF page from surveyforce app. I want that the customer should be able to fill the survey form only once the link should expire once the user fills the survey

A: You can add a custom checkbox field in the Survey Object and when the user first click the Survey link in email check if the field is marked or not. If the field is marked then don't enable the Survey form.


text:
Q: how to replace a part of a string I have a field that always consists of three values with dots between them.
like:
123456.22.aaa
23455.11.bbb

I would like to write a query that will update only the first part of the above field with a different value, so I will have them like:
111111.22.aaa
222222.11.bbb

That is - replace only the first part - up to the first dot of the field.
How can I get the first part out of this string?
note: there is no pattern for this value, I cannot search for a similar string and replace it. The only indication is that I need to replace the sub-string up to the first ..

A: For this very specific format, use substring_index with -2 as the last parameter:
select concat('new value.', substring_index('123456.22.aaa', '.', -2))
-- new value.22.aaa


text:
Q: Exclude files while generating war in jenkins I am using maven clean install inside jenkins.
My war file contains a folder named ".ebextensions".
I written three different jobs in jenkins.
One is for production and one is for testing and one is for development.
I want to exclude some files inside '.ebextensions' directory while generating war in testing environment and exclude whole directory while generating war for development environment.
How to achieve this?

A: Add exclude to maven-jar-plugin in your pom.xml:
<plugin>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.3.1</version>
    <executions>
      <execution>
        <id>default-jar</id>
        <phase>package</phase>
        <goals>
          <goal>jar</goal>
        </goals>
        <configuration>
          <excludes>
            <exclude>**/ebextensions/*</exclude>
          </excludes>
        </configuration>
      </execution>
    </executions>
</plugin>

if you need for specific environment and maven doesn't support if statements,
you could use Ant-contrib's if task
<configuration>
          <tasks>
            <taskdef resource="net/sf/antcontrib/antcontrib.properties"
              classpathref="maven.plugin.classpath" />
            <if>
              <equals arg1="${env}" arg2="development" />
              <then>
          <excludes>
            <exclude>**/ebextensions/*</exclude>
          </excludes>

              </then>
              <else>
                <echo message="Do not exclude" />
              </else>
            </if>
          </tasks>
        </configuration>

and send to maven env parameter as: mvn install -Denv=development


text:
Q: DSB-SC modulation circuit I have the following circuit which is used for DSB-SC modulation but, I can't understand

*

*Why we use High Pass Filter(I expect to be High pass filter , I'm not sure with that ) at the carrier ?

*Why we used Dc Biasing at Both input and carrier input ?

A: MC1496 is an imperfect design and when used as a regular AM type broadcast modulator then there is no need for the fine-tuning of the DC offsets at the audio input. This is because regular AM broadcasts modulate less than 100%. This can be achieved by using a 4 quadrant modulator (like the 1496) and adding a dc offset to the audio input so in fact, any small error in dc offset introduced by the chip doesn't amount to a big deal performance wise. This turns it from 4-quadrant multiplication to 2-quadrant multiplication: -

However, when it comes to double-sideband-suppressed-carrier (aka modulating greater than 100%) to truly suppress the carrier, the audio input needs to have its dc component removed and, the dc imperfections in the 1496 need balancing-out. Below is what happen when you over-modulate a little bit, leaving some carrier behind but going beyond the AM broadcast levels of modulation: -

A regular AM receiver will produce distortion (as per the top-right diagram) due to the modulation being greater than 100%. Full-fat DSBSC looks like this and a regular AM detector would produce Dalek type sounds instead of pleasant normal audio: -

And to truly 99.9% suppress the carrier (i.e. not have hardly any spectral content whatsoever) you have to fine tune the dc offsets so that they virtually disappear.
Removal of DC on the carrier input as well as the audio input is equally needed because, for the simple fact being that the output = \$ Audio\times Carrier\$ i.e. just straightforward multiplication in the time domain.
EDIT
The op's circuit indicates that the audio is fed thru a 0.1uF capacitor which then feeds a 300 ohm resistor to ground. This cannot be correct if we are to believe the label "audio signal input" because the high-pass cut-off frequency would be \$\frac{1}{2\pi RC}\$ = 5305 Hz and this excludes most of the relevant part of the audio range. Here is another similar 1496 diagram for reference: -

Note that this uses a 10uF capacitor and a 100 ohm resistor giving a cut-off of 159 Hz - not hi-fi but good enough for speach.


text:
Q: Fluent-nHibernate using results To receive entities from database I created the class with virtual members.
When I received an entity from database I cant serialize it and I can't send it by web service.
Is there any any ways to solve this problem?

A: Do your typical setup...
public class MyTable
{
    public virtual int ID {get;set;}
    public virtual string Name {get;set;}
}

I have a special response class I wrap my data in when responding to a web service call
using System.Xml.Serialization;
...

[XmlInclude(typeof(Response))]
[XmlInclude(typeof(MyTable))]
public class Response
{
    public virtual bool Success {get;set;}
    public virtual MyTable MyTable {get;set;}
}

The "[XmlInclude(typeof(Response))]" and "[XmlInclude(typeof(MyTable))]" causes the table "MyTable" to serialize as XML within "Response".  If you reference "MyTable" as a list you will need "[XmlInclude(typeof(List))]".
I hope this helps put you on the right track.  I had a hard time with the same thing until I found something similar to this.


text:
Q: Python Pandas 2 Column Relation 1st colunn : Weapon
2nd column : Pepetrator_Age
What i am trying to find is which weapon is popular in which age.

For example i am trying to draw a similar graph like this:

For example y axis should be number of cases
x axis age of Perpetrator
and lines are weapon type that Perpetrator used
You can copy paste this to jupyter to initialize dataset
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
data = pd.read_csv("hdb.csv", low_memory=False)
cols = data.columns
cols = cols.map(lambda x: x.replace(' ', '_'))
data.columns = cols
#clear the unnecessary data here
data = data.drop(['Agency_Code', 'Victim_Ethnicity', 'Agency_Name','Agency_Type', 'Perpetrator_Ethnicity', 'Victim_Count', 'Perpetrator_Count'], axis=1)
data = data[data.Perpetrator_Age != "0"]
data = data[data.Perpetrator_Age != ""]
data = data[data.Perpetrator_Age != " "]
data = data[data.Victim_Sex != "Unknown"]
data = data[data.Victim_Race != "Unknown"]
data = data[data.Perpetrator_Sex != "Unknown"]
data = data[data.Perpetrator_Race != "Unknown"]
data = data[data.Relationship != "Unknown"]
data = data[data.Weapon != "Unknown"]
data

Data set here:
https://www.kaggle.com/jyzaguirre/us-homicide-reports

A: IIUC, this grouping of data is likely better shown as a grouped bar chart, such as in Seaborn's countplot, and not in a line plot because you want to color by a specific column (Weapon) but you want to show a different column on the x-axis (Perpetrator_Age). AFAIK, a line plot will not capture these aggregations simultaneously.
Here is an explicit pandas groupby to show the aggregations that you are referencing
df_grouped = df.groupby(['Perpetrator_Age', 'Weapon']).count()

print(df_grouped)
                               Perpetrator_Race  Relationship
Perpetrator_Age Weapon
15              Blunt Object                  1             1
27              Knife                         1             1
36              Rifle                         1             1
42              Strangulation                 2             2

Now, you want to show the first index level (Perpetrator_Age) on the x-axis and the second index level Weapon must be used to color the plotted data.
Here are a few approaches (that do not require groupby)
Seaborn

*

*use countplot which will generate a bar plot of counts (corresponding the number of cases or, in general, number of records in each grouping) and it allows you to specify the column to use to group the data

*since you want to color by the Weapon column, countplot allows the parameter hue where you can specify this

*additional links

*

*customize legend title

*add custom y-axis label
Imports
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.set(style="whitegrid")

Code
ax = sns.countplot(x="Perpetrator_Age", hue="Weapon", data=df)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles, labels=labels)
ax.set_ylabel("Number of cases")

Altair

*

*based on the multi-series line chart and grouped bar chart documentation examples

*

*additional links

*

*change bar width
Imports
import altair as alt
alt.renderers.enable('notebook')

Code
alt.Chart(df).mark_bar(size=15).encode(
    alt.Y('count(Weapon):Q', axis=alt.Axis(title='Number of cases')),
    alt.X('Perpetrator_Age:O', axis=alt.Axis(labelAngle=0)),
    color='Weapon:N'
).properties(
    width=250,
    height=250
)


text:
Q: Unable to download with wget wget https://pypi.python.org/packages/sources/s/setuptools/setuptools-1.1.6.tar.gz

I have used above link to download ,but I am getting the error as
Resolving pypi.python.org (pypi.python.org)... 185.31.18.223
Connecting to pypi.python.org (pypi.python.org)|185.31.18.223|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2016-05-02 14:54:20 ERROR 404: Not Found.

A: 404 mean that the server can't find the resource. Meaning that you have a wrong link.
In this link you can find the packages to download:
https://pypi.python.org/simple/setuptools/
Try this:
wget https://pypi.python.org/packages/cb/0f/14c41a82f571530a259d6961632a92327a6c84a7a802a03409e46325be99/setuptools-1.1.6.zip#md5=17838c189ea368fc58007f5ccd816f31


text:
Q: Center window in screen Is there any way to center a window in the center of the screen in OSX?
I am using the code below but it changes just the size but not the position on screen.
override func viewDidLoad() {
        super.viewDidLoad()

        let ScreenStart = NSSize(width: (NSScreen.mainScreen()?.frame.width)! / 1.5, height: (NSScreen.mainScreen()?.frame.height)! / 1.5)

        self.view.frame.size = ScreenStart
        self.view.frame.origin = NSPoint(x: (NSScreen.mainScreen()?.frame.origin.x)!/2, y: (NSScreen.mainScreen()?.frame.height)! / 2)
    }

A: For future references this is done inside NSWindowController class using self.window?.center()

A: I had the same question, when using a Modal presentation of a NSTabViewController.
I like this answer: How to constrain second NSViewController minimum size in OS X app?
I used NSWindowDelegate to access the NSWindow properties and functions.  This included self.view.window?.center() as @SNos said.
class YDtabvc: NSTabViewController, NSWindowDelegate {

    public let size = NSSize(width: 500, height: 800)

    override func viewWillAppear() {
        super.viewWillAppear()
        self.view.window?.delegate = self
        self.view.window?.minSize = size
        self.view.window?.center()

    }
    override func viewDidAppear() {
        super.viewDidAppear()
        var frame = self.view.window!.frame
        frame.size = size
        self.view.window?.setFrame(frame, display: true)
    }
}


text:
Q: Locus of a vertex defining a circle intrinsic to a triangle Given a triangle $\triangle ABC$, we draw the circles with centers in two vertices (say, $A,C$ in the picture below) and passing through the third one (say, $B$), determining the points $D$ and $E$ on the side $\overline{AC}$.

Then, we can draw the two circles with centers in the same two vertices and passing by the $D$ and $E$, determining other two points $F$ and $G$ on the other two sides.

The five points $B,D,E,F,G$, as shown here, always determine a circle (red).

My question is:

Given two vertices of $\triangle ABC$, what is the locus determined by the third point in such a way that the red circumference is well defined?

My suspect is that this locus is the inner part of an ellipse (orange, in the picture below) passing through the two initial vertices, and two points $H,I$ located at the far vertices of two equilateral triangles built on the side defined by the two initial points, as illustrated here:

But I have difficulties to determine a fifth point $J$ which would define such an ellipse without any ambiguity.
Thanks for your help, and sorry in case of trivialities!

A:
According to GeoGebra, if $A$ and $C$ are the fixed vertices, the equilateral triangles are significant, but the figure within which circle $BFDEG$ is defined is not an ellipse but rather the figure $HAIC$ (reminiscent of Euclid Elements I, 1), that is, the football-shaped overlap of two circles with centers $A$, $C$ and intersections $H$, $I$.
Circle $BFDEG$ persists wherever $B$ is moved within that figure, but shrinks to a point when $\triangle ABC$ degenerates to a line (when $B$ lies on $AC$), and disappears altogether when $B$ is moved outside the figure.
addendum: As noted in response(s) to OP's July posting, a necessary condition of the five-point circle $BFDEG$, where $A$, $C$ are fixed, is that $\angle BAC$ and $\angle BCA$ are both acute.  A further necessary condition seems to be that neither $BA$ nor $BC$ is greater than the given line $AC$. E.g. if $AB>AC$, then $E$ lies on $AC$ extended and $GBDE$ is no longer an isosceles trapezoid and/or inscribable in the same circle as isosceles trapezoid $FBED$ (cf. @dan fulea response to the July posting).
I note, however, that $G'BDE$ is an isosceles trapezoid concyclic with $FBED$, if $G'$ is diametrically opposite $G$ on the circle about $C$, i.e. on side $BC$ extended. But setting this aside as part of a more general problem, we seem to be left with the football.


text:
Q: Can't save the same record twice in the join table Entity Framework I have 2 tables, Invoice and Product, and I'm using EF to save data to my database
The two classes and my context class are as following:
public class Invoice
{
        public int Id { get; set; }
        public string InvoiceNumber { get; set; }
        public double TotalPrice { get; set; }
        public List<Product> Products { get; set; }
}
public class Product
{
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public List<Invoice> Invoices { get; set; }
}
public class DB : DbContext
{
    public DB() : base("MyConnectionstringName") { }

    public DbSet<Invoice> Invoices { get; set; }
    public DbSet<Product> Products { get; set; }
}

Finally, this is how I save data to the database:
public string Create(Invoice invoice, List<Product> products)
{
        foreach (var item in products)
        {
            invoice.Products.Add
                (db.Products.Find(item.id));
        }
        db.Invoices.Add(invoice);
        db.SaveChanges();
        ...
        return "Invoice was successfully saved";
}

The problem is, if I have the same Product twice in the products, I gets added to the join table in the database, only once.
For example, if a customer buys two Pepperoni pizza which has the Id of 5, after saving, there will be only of row of data in InvoiceProduct pointing to this particular invoice, and ProductId of 5.
Everything is fine up until db.Invoices.Add(invoice);, cause when I check invoice in debug mode I can see several of the same item were added to its Products property, but when it gets saved to the database, it only get saved once.
And it works just fine with several of different products for the same invoice.
What am I not seeing here?

A: In sql relational world you have the Products table, the Invoice table and the ProductsInvoices table that represents a many-to-many relationship. In that table you have the reference for an id of a product and an id of an invoice. When you add it twice EF understand that you already have the relation you want and does nothing.
In order to solve this I would create other class named InvoiceItem having a Product, an Invoice and a Quantity:
public class Invoice
{
        public int Id { get; set; }
        public string InvoiceNumber { get; set; }
        public double TotalPrice { get; set; }
        public List<InvoiceItem> Items { get; set; }
}

public class InvoiceItem
{
        public int Id { get; set; }
        public int Quantity { get; set; }
        public Product Product { get; set; }
}

public class Product
{
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public List<InvoiceItem> Invoices { get; set; }
}

public class DB : DbContext
{
    public DB() : base("MyConnectionstringName") { }

    public DbSet<Invoice> Invoices { get; set; }
    public DbSet<InvoiceItem> InvoiceItems { get; set; }
    public DbSet<Product> Products { get; set; }
}

It is recommended that you also add the copy of the item description and price of the Product in the InvoiceItem object, because if in the future the user changes the price or name of the product it doesn't alter the Invoice that were generated in the past.


text:
Q: Where to start? Building a website that uses a database I haven't started working seriously with web development just at the moment, as I have never had the need for a website. However I am quite competent when it comes to building software using languages like C#, I have also frequently work with Python, so I am not totally in the dark.
When it comes to the web I only know the different languages out there for web development, and have a vague idea of what each one does.
I realize this question could have thousand different answers so I will be a specific as I can.
Here is a description of the kind of website I am trying to build:
Basically a website where users can check out forums, and if they would like to, they can register an account with my website, which would allow them to start posting comments on certain pages.
Basically what I am asking is: In order to start a website, (like the one described above), where do I need to start? What languages/web technologies are going to be needed?, where would the first place be to start? ie. start learning html... Also, is there perhaps any free ebooks online that could get me started.
I hope this is enough information, keep in mind I am not looking for a an incredibly dense and detailed answer, just a simple explanation as to where to start, what language would be simple and easy to start with... I realize to create this kind of website takes a lot of hard work and complicated tasks, so just keep in mind I am only wanting an idea as to how to climb the first 2 or three stairs, not the whole staircase just right now. Thanks heaps!

A: Assuming you want forum website, there are lots of ready to use php "platforms" for sites like  this. I personally like "Simple Machines Forum". Other possible solution is "Phorum" and "PHPBB". Google them.
Because you mentioned C#, I am assuming you are working on windows. In order to get this forum up and running you will need PHP and MySQL on your server.

A: I am developing websites on both windows and os x, but as Nick said you will need a PHP + MySQL server which you can get from here:
http://prdownloads.sourceforge.net/appserv/appserv-win32-2.5.10.exe?download
Configuration is fairly easy, however after installing the appserv, I would advise you to download the latest version of PHP from here:
http://windows.php.net/downloads/releases/php-5.4.15-Win32-VC9-x86.zip
and copy all of those files to C:\AppServ\php5. Make sure that apache is not running, you can stop it by going to: Start->All Programs->Appserv->Control Server by Service->Apache Stop.
As nick said it is faster and easier to use forum systems that are already written: PHPBB, vBulletin etc.
Good luck.

A: What you seek to do is quite complex in PHP but a lot of fun.
Ask yourself, do you really want to do this in PHP or do you want sommething customisable that will produce the end result you desire?
You will get up and running very quickly if you go for something like Drupal which is a fully featured CMS system.  There is a very steep learning curve with any CMS system but you will be able to get what you want going pretty fast.
That having been said, there is a lot to say for developing your site with php as you will learn a lot on the way and you don't have all the overhead of a system that tries to be all things to all people.
I recommend w3schools.com which has excellent tutorials on PHP, Mysql, SQL, HTML and Javascript, all of which will be required to achieve what you need.
The best piece of advice I have ever received on this adventure was 'Design the Project First!' - THINK long and hard about what you plan to do.  Make sure you know what you are trying to achieve for each page and then do them one at a time.
Best of luck!


text:
Q: How do I solve this question using vectors? Given trigonometric equation
$$5\cos \theta -12\sin \theta = 13$$
I'll be trying to determine a general solution using vectors. I've recently asked this question two times. However, the answers weren't genuinely understandable in particular. This way would also collide with other ways being used to solve this problem.
Regards!

A: $$\langle 5,-12 \rangle \cdot \langle \cos\theta,\sin\theta \rangle = 13$$
$$\left(\sqrt{5^2+12^2}\sqrt{\cos^2\theta+\sin^2\theta}\right)\cos(\theta-\tan^{-1}(-12/5)) = 13$$
$$\cos(\theta+\tan^{-1}(12/5)) = 1$$
$$\theta = 2\pi k - \tan^{-1}(12/5), k\in\mathbb{Z}$$

A: We know that given two vectors $u$ and $v$
$$u\cdot v=|u||v| \iff v=ku$$
therefore let

*

*$u=(5,-12)\implies |u|=13$

*$v=(\cos \theta, \sin \theta)\implies |v|=1$
therefore since $u\cdot v=|u||v|$ we have that
$$v=(\cos \theta, \sin \theta)=k(5,-12)=\left(\frac5{13},-\frac{12}{13}\right)$$
that is

*

*$\cos \theta=\frac5{13}$

*$\sin \theta=-\frac{12}{13}$

and

*

*$\tan \theta =\frac{\sin \theta}{\cos \theta}=-\frac{12}5$

from which we obtain
$$\theta = \arctan(-12/5) \color{red}{+2k\pi}$$
Note that we take $+2k\pi$ since $\cos \theta>0$ and $\sin \theta<0$.

A: The equation $5\cos\theta - 12\sin\theta = 13$ is equivalent to the vector equation
$$\left< 5, -12 \right> \cdot \left<\cos\theta, \sin\theta\right> = 13$$
Now in general, for any two vectors $\textbf{u}, \textbf{v}$ the dot product obeys
$$\textbf{u} \cdot \textbf{v} = |\textbf{u}| |\textbf{v}| \cos\phi$$
where $\phi$ is the angle between the two vectors $\textbf{u}$ and $\textbf{v}$.  In this case, we have $\textbf{u}= \left< 5, -12 \right>$ with $|\textbf{u}| = 13$, and $\textbf{v} = \left<\cos\theta, \sin\theta \right>$ with $| \textbf{v} | = 1$, so
$$(13)(1)\cos\phi = 13$$
which means that $\phi = 0$.  In other words, $\left<\cos\theta, \sin\theta\right>$ is a unit vector that points in the same direction as $\left< 5, -12 \right>$, so $\theta = \arctan \left( - \frac{12}{5} \right) $.

A: Here is a geometric solution to the similar equation
$$5\cos\theta+12\sin\theta=13$$
From the Pythagorean triple $5$-$12$-$13$ construct the right triangle $\triangle ABD$ with sidelenghts $AB=5$, $AD=12$, and $BD=13$. Pick a point $C$ lying on $\overline{BD}$ such that $\overline{AC}$ is perpendicular to $\overline{BD}$. By the Inscribed Similar Triangles Theorem, $\triangle ABD$ is similar to $\triangle CAD$, therefore $\angle ABD=\angle CAD$.

Now for some trigonometry: Let $\theta=\angle ABD=\angle CAD$. Then $BC=5\cos\theta$ and $CD=12\sin\theta$. By construction, $BD=13$. Therefore,
$$BC+CD=BD\iff 5\cos\theta+12\sin\theta=13$$
By the Inscribed Similar Triangles Theorem, $\triangle CBA$ is similar to $\triangle ABD$, yielding the proportion
$$\frac{BC}{AB}=\frac{AB}{BD} \iff \frac{5\cos\theta}{5}=\frac{5}{13}$$
$$\implies \theta=\cos^{-1}(\frac{5}{13})$$
Maybe you can rearrange this setup to match your equation $5\cos\theta-12\sin\theta=13$.


text:
Q: Composer is not getting my new PHP version I'm trying to install a package that requires PHP ^7.0. So I changed my host PHP version from 5.6 to 7.0.25. Running php -v return:

PHP 7.0.25 (cli) (built: Oct 30 2017 17:10:45) ( NTS )

But composer still relating version problem:

*

*spatie/laravel-backup 4.19.2 requires php ^7.0 -> your PHP version (5.6.30) does not satisfy that requirement.

A: You probably still have php5.6-cli installed on your server (which php)
It should work if you call
/path/to/php7 composer.phar update

Or
Considering php7 executable is /usr/bin/php7.0, create an alias in your ~/.bash_profile
alias composer='/usr/bin/php7.0 /usr/local/bin/composer'

Or
By default, composer (composer.phar generally located in /usr/local/bin/composer) uses the executable specified by env :
#!/usr/bin/env php

You can also specify a targeted version of php to use :
#!/usr/bin/php7.0

Or
completely remove php5.6-cli :)


text: Q: problem with packpath when install neosolarized i'm trying to set up neosolarized theme like the instruction below. I've install colorbuddy and neosolarized.vim but when i paste the code into 'init.vim', the error happens. What should i do now?


text:
Q: Array key as string and number How to make arrays in which the key is number and string.
<?php
$array = array
(
    'test' => 'thing',
    'blah' => 'things'
);

echo $array[0]; // thing
echo $array[1]; // things

echo $array['test']; // thing
echo $array['blah']; // things
?>

A: $array = array_values($array);

but why would you need that? can you extend your example?

A: You could use array_keys to generate a lookup array:
<?php
$array = array
(
    'test' => 'thing',
    'blah' => 'things'
);
$lookup = array_keys ($array);
// $lookup holds (0=>'test',1=>'blah)

echo $array[$lookup[0]]; // thing
echo $array[$lookup[1]]; // things

echo $array['test']; // thing
echo $array['blah']; // things
?>

A: You could implement your own class that "implements  ArrayAccess"
For such class you can manually handle such behaviour
UPD: implemented just for fun
class MyArray implements ArrayAccess
{
    private $data;
    private $keys;

    public function __construct(array $data)
    {
        $this->data = $data;
        $this->keys = array_keys($data);
    }

    public function offsetGet($key)
    {
        if (is_int($key))
        {
            return $this->data[$this->keys[$key]];
        }

        return $this->data[$key];
    }

    public function offsetSet($key, $value)
    {
        throw new Exception('Not implemented');
    }

    public function offsetExists($key)
    {
        throw new Exception('Not implemented');
    }

    public function offsetUnset($key)
    {
        throw new Exception('Not implemented');
    }
}

$array = new MyArray(array(
    'test' => 'thing',
    'blah' => 'things'
));

var_dump($array[0]);
var_dump($array[1]);
var_dump($array['test']);
var_dump($array['blah']);


text:
Q: Search more then one MySql table in Mysql Database PHP I have a database have 20 tables I want to search all of these I got stuck that how can I search this and solve this query help is very appreciated. Like:

*

*table1

*table2

*table3

*table4

and so one. This is my script.
<?php
                 if(isset($_GET["search"]))
                 {
                      $condition = '';
                      //$query = explode(" ", $_GET["search"]);
                      $query = explode(" ", $_GET["search"]);

                      foreach($query as $text)
                      {
                           $condition .= "`title`  LIKE +'%".mysqli_real_escape_string($connect, $text)."%' OR ";
                      }
                      $condition = substr($condition, 0, -4);
                      $sql_query = "SELECT * FROM countries2 WHERE " . $condition;
                      $result = mysqli_query($connect, $sql_query);
                      if(mysqli_num_rows($result) > 0)
                      {
                           while($row = mysqli_fetch_array($result))
                           {
                                echo '
'.$row["title"].'
';
                           }
                      }
                      else
                      {
                           echo 'Data not Found';
                      }
                 }
                 ?>

A: Try with this
sql_query = "SELECT * FROM `countries`,`countries2`   WHERE " . $condition;

i have noticed that you are making a search directory or something like this.
you may use FULLTEXT SEARCH with operators and Stemming
after this your query will look like this.
implement as per your requirement ;).
(SELECT * FROM table1 WHERE(col1,col2,clo3) AGAINST(."$search".) IN NATURAL LANGUAGE MODE)


text:
Q: MySQL finding subtotals EDIT:
I'm told that making you guys read means I get less attention. My apologies. Here's a simpler version:
Bill got $100 dollars worth of items from a store.
He wants to return enough of the items to get exactly $30 dollars back.
The store has a Point of Return system that will help him do this.
Here is the data after he scans his items:
       item ¦   price ¦

socks             4.00
cheap tv         22.00
book on tape      9.00
book on paper     7.00
party hats        3.00
picture frame    10.00
hammer            5.00
juicer           16.00
mysql guide      24.00

total items  ¦ total price ¦
            9   100.00

Option 1
===============
item ¦          price ¦
cheap tv        22.00
party hats       3.00
hammer           5.00
===============

Option 2
===============
item ¦          price ¦

socks            4.00
picture frame   10.00
juicer          16.00
===============

Option 3
===============
item ¦          price ¦

book on tape    9.00
hammer          5.00
juicer         16.00

I probably missed a few options, since I made all of this up.
So, the big question is:
Is there a way (with GROUP BY, probably) to have one query that would return ever possible combination of items?
Thanks!
a

A: You're asking for all subsets which sum up to exactly $30.
This sounds a lot like the subset sum problem, and knapsack problem, so I strongly doubt you can do this with a simple query.  You'd probably have to turn to T-SQL, but even that would probably look ugly.
I think programming is the way to go here.

A: If the number of items are small enough you can brute force this with SQL.  This might be a quick to write solution, but you probably want to do something smarter.  Sounds like the "knapsack problem" which is NP complete.
If the number of items is large, you will need to delve into dynamic programming algorithms.  You have to ask yourself how important this is to your application.
If the number of items is relatively small, you may be able to brute-force this.  A brute-force SQL statement (which is what you asked for) that finds combinations of 1,2 or 3 items that match is as follows.  If this is not satisfactory, then maybe SQL is not the right tool for this job.
SELECT
   i1.id AS id1,
   NULL AS id2,
   NULL AS id3,
   i1.amount
FROM
   items i1
UNION ALL
SELECT
   i1.id AS id1,
   i2.id AS id2,
   i3.id AS id3,
   i1.amount + i2.amount AS total
FROM
   items i1,
   items i2
WHERE
   i1.amount + i2.amount = 30 AND
   i1.id <> i2.id AND
   i1.id <> i3.id
UNION ALL
SELECT
   i1.id AS id1,
   i2.id AS id2,
   i3.id AS id3,
   i1.amount + i2.amount + i3.amount AS total
FROM
   items i1,
   items i2,
   items i3
WHERE
   i1.amount + i2.amount + i3.amount = 30 AND
   i1.id <> i2.id AND
   i1.id <> i3.id AND
   i2.id <> i3.id

In Oracle, you would use the CUBE function to turn this into a generic version, not sure about a MySQL equivalent.

A: i don't think group by can do it.
i can't think of a better way than finding/trying all of the permutations, either in your programming language of choice or with a stored procedure.
if you had items over 30$ you could omit them.
there would be some improvements if you wanted a "best" option by some criteria.

A: This problem is in fact P/NP. eg you probably can't find THE BEST fitting article prices, without brute force search, and if your clients store is big - you can find that search very long lasting.
You can use some of the existing algorithms that can give you pretty good guess, but I'm afraid that they are all non-SQL ones.
I would suggest to do approximation of your problem:
Create procedure/query that finds ONE article that best fits wanted price, and than call it again for new change you have. Not perfect, but will do the job.


text:
Q: Regex Find Missing Double Bracket tags and remove them i have string like this
{wrongTag}} RegExr was {{created}aaaa{{fffffff}} shks {{sdfsdfsd}  and    {{created}aaaa{{fffffff}
i want to remove all wrong tags either single bracket is missing from the start or end of tag. in example about only {{fffffff}} is correct tag all other tags are worng should be removed , my code is this for removing all wrong tags
const cleanString = message.replace(/(?!{{[^{{}}]+\}\})\{{[^{{}}]+\}/g, "")

but my regex is only detecting last missing baraket .
So following wrong tag also be matched
https://regexr.com/69vlq
{wrongTag}}
{missingtag}
Below is my Regex , you can see its working partially but not fully any help would be appricated
https://regexr.com/69vlq

A: You can use
const cleanString = message.replace(/(?<!{)({{[^{}]+}})(?!})|{+[^{}]*}+/g, '$1');

Or,
const cleanString = message.replace(/((?:[^{]|^){{[^{}]+}}(?:{{[^{}]+}})*)(?!})|{+[^{}]*}+/g, '$1');

See the regex demo #1 / regex demo #2. The point is to match and capture into Group 1 any valid tag, and then match and remove the tags with any one or more curly braces around them.
Details:

*

*(?<!{) - a negative lookbehind that fails the match if there is a { char immediately to the left of the current location

*({{[^{}]+}}) - Group 1: {{, one or more chars other than { and }, and then }}

*(?!}) - a negative lookahead that fails the match if there is a } char immediately to the right of the current location

*| - or

*{+ - one or more { chars

*[^{}]* - zero or more chars other than { and }

*}+ - one or more } chars.

In the no-lookbehind solution, (?<!{) is replaced with (?:[^{]|^) that matches either a char other than { (with [^{]) or start of string (with ^).

A: If you're looking for mismatched brackets, you could use the following test for missing leading brackets
[^{]{([^{}]+)\}\}

and this for missing trailing brackets
{{([^{}]+)\}[^}]

and this for missing leading and trailing brackets
[^{]{([^{}]+)\}[^}]

It can by done with a single regex; but you're well on your way to write only code when you try to make a regular expression do more than a single operation at a time.
In plain english; the first expression would read:
Find the first '{' that is not preceded by a '{'.  Match a group of characters that do not contain '{' or '}' until you reach a '}' followed by another '}'
The second is basically the same statement, but it reads:
Find the first "{{". Match a group of characters that do not contain '{' or '}' and consider it a match if the next '}' is not followed by '}'.
The third is just a combination of the first two, to match items that are wrapped in "{}" but not in "{{}}"


text:
Q: T/F: If the sequence $(a_{n})_{n=1}^{\infty}$ converges and the sequence $(b_{n})_{n=1}^{\infty}$ does not converge, then ... T/F: If the sequence $(a_{n})_{n=1}^{\infty}$ converges and the sequence $(b_{n})_{n=1}^{\infty}$ does not converge, then the sequence $(a_{n} + b_{n})_{n=1}^{\infty}$ does not converge.
I thought about finding some $f(x)$ and $g(x)$ that contradict this but I can't think of any (because it's a sum and not multiply).

A: Suppose $(a_n)$ converges and $(b_n)$ does not. Note that if $(a_n)$ and $(c_n)$ converges, then so does $(a_n)+(c_n)$. Thus, if $(a_n)+(b_n)$ would converge, then so would $(a_n+b_n)-(a_n)=(b_n)$.


text:
Q: Prove that a function $f: T^{2} \to T^{2}$ is topological transistive. The question I`m not getting is the following:
$\alpha$ is irrational and  $f: T^{2} \to T^{2}$ is the homeomorphic function from to 2-torus unto itself given by $f(x,y)=(x+\alpha,x+y)$.
$a )$ Prove that every non-empty, open, $f$-invariant set is dense.
My attempt:
I know I have to show that every orbit of this function is dense, but I don`t know how. Could you please help me?
Yours,
Pim


text:
Q: System.IO.IOException:Sharing violation on path - multiple clients I have two applications. The server send files to my clients. The clients are implemented in Unity3d with C#. Each client has one thread to receive files from server. If I send the files over the network, I write the bytes to the file with this code:
private Thread clientThread;
private object writeLock = new object();

public void StartConnection()
{
   // Start connection to server.
   clientThread = new Thread(GetFiles);
}
public void GetFiles()
{
    string fullPath;
    // Receive bytes from server

    fullPath = Path.Combine(clientDirPath, fileNameFromServer);
    lock(writeLock)
    {
      using (BinaryWriter bWrite = new BinaryWriter(File.Open(fullPath, FileMode.Create)))
      {
          bWrite.Write(binaryFileContent);
          bWrite.Flush();
      }
}

Now, if I start multple clients and send files to receive them synchronously on the client-side, I get this error message: System.IO.IOException:Sharing violation on path. Whether I use the lock-statement it is not working. Do anyone know the way to get it working?
EDIT: I added more code.