text:
Q: Yii 1.1 model relation can't use joined table column on select This is my class
Class System extends CActiveRecord
{
    public function relations() {
        return array(
            'SystemInverterModuleMountGrouped' => array(self::HAS_MANY, 'SystemInverterModule', array('id' => 'system_inverter_id'),
                'through' => 'SystemInverter',
                'group' => 'system_id, SystemInverterModuleMountGrouped.mount_id',
                'condition' => 'SystemInverterModuleMountGrouped.mount_id is not null AND SystemInverterModuleMountGrouped.mount_id != "" AND number_of_mounts > 0 AND
                    CASE WHEN Mount.unit_of_measure = 1 THEN
                        SystemInverterModuleMountGrouped.existing_array != 1
                    ELSE true
                    END',
                'select' => '*, '
                    . 'SUM(SystemInverterModuleMountGrouped.number_of_mounts) AS number_of_mounts_grouped, ',
                'with' => 'Mount'
            )
        );
    }
}

This is working fine, but now I want to sum number_of_mounts in a certain condition
array(
    'select' => '*, '
        . 'IF(Mount.unit_of_measure IN (1,2,3), 0, SUM(SystemInverterModuleMountGrouped.number_of_mounts)) AS number_of_mounts_grouped, ',
)

It doesn't work and yii throws an error

Active record "SystemInverterModule" is trying to select an invalid column "IF(Mount.unit_of_measure IN (1". Note, the column must exist in the table or be an expression with alias.

Notice that I'm able to use Mount.unit_of_measure on the condition

'condition' => 'CASE WHEN Mount.unit_of_measure = 1 THEN '

It works with raw sql query
SELECT IF(Mount.unit_of_measure IN (1,2,3), 0, SUM(SystemInverterModuleMountGrouped.number_of_mounts)) AS number_of_mounts_grouped
FROM `SystemInverterModules` `SystemInverterModuleMountGrouped`
LEFT OUTER JOIN `SystemInverter` `SystemInverter`
       ON (`SystemInverter`.`id` = `SystemInverterModuleMountGrouped`.`system_inverter_id`)
LEFT OUTER JOIN `Inventory` `Mount`
       ON (`SystemInverterModuleMountGrouped`.`mount_id` = `Mount`.`id`)
WHERE (SystemInverterModuleMountGrouped.mount_id is not null AND SystemInverterModuleMountGrouped.mount_id != "" AND
       number_of_mounts > 0 AND
       CASE WHEN Mount.unit_of_measure = 1 THEN
              SystemInverterModuleMountGrouped.existing_array != 1
       ELSE true END
    )
    AND (`SystemInverter`.`system_id` = '42146')
GROUP BY system_id, SystemInverterModuleMountGrouped.mount_id
ORDER BY sort_mounting ASC

A: You should use array for declaring select in this case - string format does not work well for complicated expressions:
'select' => [
    '*',
    'IF(Mount.unit_of_measure IN (1,2,3), 0, SUM(SystemInverterModuleMountGrouped.number_of_mounts)) AS number_of_mounts_grouped',
],


text:
Q: Embedding assemblies inside another assembly If you create a class library that uses things from other assemblies, is it possible to embed those other assemblies inside the class library as some kind of resource?
I.e. instead of having MyAssembly.dll, SomeAssembly1.dll and SomeAssembly2.dll sitting on the file system, those other two files get bundled in to MyAssembly.dll and are usable in its code.

I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET? Are all .NET assemblies DLLs, but not all DLLs are .NET assemblies? Why do they use the same file format and/or file extension?

A: You can embed an assembly (or any file, actually) as a resource (and then use the ResourceManager class to access them), but if you just want to combine assemblies, you're better off using a tool like ILMerge.
EXE and DLL files are Windows portable executables, which are generic enough to accomodate future types of code, including any .NET code (they can also run in DOS but only display a message saying that they're not supposed to run in DOS). They include instructions to fire up the .NET runtime if it isn't already running. It's also possible for a single assembly to span across multiple files, though this is hardly ever the case.

A: ILMerge does merge assemblies, which is nice, but sometimes not quite what you want. For example, when the assembly in question is a strongly-named assembly, and you don't have the key for it, then you cannot do ILMerge without breaking that signature. Which means you have to deploy multiple assemblies.
As an alternative to ilmerge, you can embed one or more assemblies as resources into your exe or DLL.  Then, at runtime, when the assemblies are being loaded, you can extract the embedded assembly programmatically, and load and run it.  It sounds tricky but there's just a little bit of boilerplate code.
To do it, embed an assembly, just as you would embed any other resource (image, translation file, data, etc).  Then, set up an AssemblyResolver that gets called at runtime.  It should be set up in the static constructor of the startup class. The code is very simple.
    static NameOfStartupClassHere()
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolver);
    }

    static System.Reflection.Assembly Resolver(object sender, ResolveEventArgs args)
    {
        Assembly a1 = Assembly.GetExecutingAssembly();
        Stream s = a1.GetManifestResourceStream(args.Name);
        byte[] block = new byte[s.Length];
        s.Read(block, 0, block.Length);
        Assembly a2 = Assembly.Load(block);
        return a2;
    }

The Name property on the ResolveEventArgs parameter is the name of the assembly to be resolved. This name refers to the resource, not to the filename.  If you embed the file named "MyAssembly.dll", and call the embedded resource "Foo", then the name you want here is "Foo".  But that would be confusing, so I suggest using the filename of the assembly for the name of the resource.  If you have embedded and named your assembly properly, you can just call GetManifestResourceStream() with the assembly name and load the assembly that way.  Very simple.
This works with multiple assemblies, just as nicely as with a single embedded assembly.
In a real app you're gonna want better error handling in that routine - like what if there is no stream by the given name?  What happens if the Read fails?  etc.  But that's left for you to do.
In the rest of the application code, you use types from the assembly as normal.
When you build the app, you need to add a reference to the assembly in question, as you would normally. If you use the command-line tools, use the /r option in csc.exe; if you use Visual Studio, you'll need to "Add Reference..." in the popup menu on the project.
At runtime, assembly version-checking and verification works as usual.
The only difference is in distribution.  When you deploy or distribute your app, you need not distribute the DLL for the embedded (and referenced) assembly.  Just deploy the main assembly; there's no need to distribute the other assemblies because they're embedded into the main DLL or EXE.

A: Note ILMerge doesn't work with embedded resources like XAML, so WPF apps etc will need to use Cheeso's method.

A: There's also the mkbundle utility offered by the Mono project

A: Take a look at ILMerge for merging assemblies.

I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET?

Yes.

Are all .NET assemblies DLLs,

Either DLLs or EXE normally - but can also be netmodule.

but not all DLLs are .NET assemblies?

Correct.

Why do they use the same file format and/or file extension?

Why should it be any different - it serves the same purpose!

A: Why do they use the same file format and/or file extension?

Why should it be any different - it serves the same purpose!

My 2¢ bit of clarification here:  DLL is Dynamic Link Library.  Both the old style .dll (C-code) and .net style .dll are by definition "dynamic link" libraries.  So .dll is a proper description for both.

A: With respect to Cheeso's answer of embedding the assemblies as resources and loading them dynamically using the Load(byte[]) overload using an AssemblyResolve event handler, you need to modify the resolver to check the AppDomain for an existing instance of the Assembly to load and return the existing assembly instance if it's already loaded.
Assemblies loaded using that overload do not have a context, which can cause the framework to try and reload the assembly multiple times. Without returning an already loaded instance, you can end up with multiple instances of the same assembly code and types that should be equal but won't be, because the framework considers them to be from two different assemblies.
At least one way that multiple AssemblyResolve events will be made for the same assembly loaded into the "No context" is when you have references to types it exposes from multiple assemblies loaded into your AppDomain, as code executes that needs those types resolved.
https://msdn.microsoft.com/en-us/library/dd153782%28v=vs.110%29.aspx
A couple of salient points from the link:
"Other assemblies cannot bind to assemblies that are loaded without context, unless you handle the AppDomain.AssemblyResolve event"
"Loading multiple assemblies with the same identity without context can cause type identity problems similar to those caused by loading assemblies with the same identity into multiple contexts. See Avoid Loading an Assembly into Multiple Contexts."

A: I would suggest you to try Costura.Fody. Just don't forget to Install-Package Fody before Costura.Fody (in order to get the newest Fody!)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Camel: Claim Check + streaming splitter. Possible? I have a requirement where I will be receiving messages on rabbitmq. These messages will contain a document Id and an attachment name. Now I am using camel to consume from this endpoint. Now whenever I consume a message I want to download the attachment from a HTTP service and then split it. I want to use camel splitter for doing this. These files can potentially be over 1 GB in size so I want to split it while streaming them over HTTP.
   So my requirement is sort of a streaming claim check. Is this possible in camel?

A: Got it working now. RecipientList to the rescue.


text: Q: I am using an angular mat-stepper, however all of my components inside the stepper are non-responsive I am using an angular mat-stepper, however, all of my components inside the stepper are non-responsive when the screen size changes. to my understanding, angular components are responsive by design. any help on this question or how to resolve will be appreciated


text:
Q: Delete website in Magento can't delete store and store view I have a controller extended from Mage_Adminhtml_System_StoreController, below is the action I overwrite:
public function deleteWebsitePostAction()
    {
        $multiWebEnable = Mage::getStoreConfig('web/multi_web_general/multi_web');
        $itemId = $this->getRequest()->getParam('item_id');

        if (!$model = Mage::getModel('core/website')->load($itemId)) {
            $this->_getSession()->addError(Mage::helper('core')->__('Unable to proceed. Please, try again'));
            $this->_redirect('*/*/');
            return;
        }
        if (!$model->isCanDelete()) {
            $this->_getSession()->addError(Mage::helper('core')->__('This website cannot be deleted.'));
            $this->_redirect('*/*/editWebsite', array('website_id' => $model->getId()));
            return;
        }

        $this->_backupDatabase('*/*/editWebsite', array('website_id' => $itemId));

        try {
            $model->delete();

            if ($multiWebEnable) {
                $websiteCode = $model->getCode();
                $websiteDir = BP . DS . 'mpshop' . DS . $websiteCode;
                if (is_dir($websiteDir)) {
                    $objects = scandir($websiteDir);
                    foreach ($objects as $object) {
                        if ($object != "." && $object != "..") {
                            if (filetype($websiteDir . DS . $object) == "dir") {
                                rmdir($websiteDir . DS . $object);
                            } else {
                                unlink($websiteDir . DS . $object);
                            }
                        }
                    }
                    reset($objects);
                    rmdir($websiteDir);
                }
            }

            $this->_getSession()->addSuccess(Mage::helper('core')->__('The website has been deleted.'));
            $this->_redirect('*/*/');
            return;
        } catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        } catch (Exception $e) {
            $this->_getSession()->addException($e, Mage::helper('core')->__('Unable to delete website. Please, try again later.'));
        }
        $this->_redirect('*/*/editWebsite', array('website_id' => $itemId));
    }

I tried to comment out this function in my controller but the issue still there.
I'm confused with this. I need to know why this can happens, give me some suggestion... THanks
Any help will be appreciated.

A: Well,
After research deep inside, I realise one foreign key was missing between core_website table and core_store, core_store_group.
The solution here is download Magento Database Repair Tool which available to download at Magento homepage.
Hope this help.

A: Note that deleting websites can only be done from admin panel which is why the standalone script has that.
( Placed in root/var folder )
This will delete your website from a standalone file:
require_once( 'app/Mage.php' );

umask(0);
Mage::app( 'admin' );
function deleteWebsitePostAction()
{
    try
    {
        $sWebsiteId = 'a';
        $oWebsite = Mage::getModel( 'core/website' )->load( $sWebsiteId );
        if( !empty( $oWebsite->getId() ) )
        {
            $oWebsite->delete();
        }
    }
    catch( Exception $oException )
    {
        Mage::logException( $oException );
    }
}
deleteWebsitePostAction();

To implement this in the admin panel ensure that you are submitting the correct variable to the controller, in this case I chose the name website_id so your form should have an  somewhere.
public function deleteWebsitePostAction()
{
    try
    {
        $sWebsiteId = $this->getRequest()->getParam( 'website_id' );
        $sWebsiteId = 'a';
        $oWebsite = Mage::getModel( 'core/website' )->load( $sWebsiteId );
        if( !empty( $oWebsite->getId() ) )
        {
            $oWebsite->delete();
        }
        else
        {
            $this->_getSession()->addError( 'Unable to proceed. Please, try again' );
            $this->_redirect( '*/*/' );
            return;
        }
    }
    catch( Exception $oException )
    {
        Mage::logException( $oException );
        $this->_getSession()->addError( 'Unable to delete website. Please, try again' );
    }
}

A: Disable your cache from Admin> System> Cache management
Refresh your cache and check again.
You can also delete your cache from cache management or [root]/var/cache


text:
Q: How to test a gem with RSpec that extends ActiveRecord models? I am moving some code we use into a gem.  The code allows you to create breadcrumbs on ActiveRecord models like so:
Parent < ActiveRecord::Base
  has_breadcrumbs
end

My question is - how do I use Rspec in my gem to mock/stub these abstract AR objects?  So essentially, I need to create 'fake' active record objets, add my has_breadcrumbs to them, then use these mocked records in my specs.
In my spec_helper.rb I'm including:
require 'rubygems'
require 'rails/all'
require 'rspec/rails'

I need to test that the gem is working correctly by ensuring my has_breadcrumbs is responding correctly and allowing me to apply settings against AR models.  However, I'm finding this tricky since I don't have a DB instead I need to mock these objects somehow.
Some code examples would be great to give me an idea on what's the best practice for this sort of thing.


text:
Q: cannot drag window created with divs hey there i am trying to drag the following window

with the following codes:
var zindex = 0;
var dragobject = {
    z: 0,
    x: 0,
    y: 0,
    offsetx: null,
    offsety: null,
    targetobj: null,
    dragapproved: 0,
    initialize:function(){
        document.onmousedown=this.drag
        document.onmouseup=function(){this.dragapproved=0}
    },
    drag:function(e){
        var evtobj=window.event? window.event : e
        this.targetobj=window.event? event.srcElement : e.target

        if (this.targetobj.className=="drag"){
            this.dragapproved=1
            zindex = zindex + 1;
            $("#" + this.targetobj.id).css('z-index', zindex);
            //document.getElementById(this.targetobj.id).style.zIndex='1'

            if (isNaN(parseInt(this.targetobj.style.left))) {
                this.targetobj.style.left=0
            }

            if (isNaN(parseInt(this.targetobj.style.top))) {
                this.targetobj.style.top=0
            }

            this.offsetx=parseInt(this.targetobj.style.left)
            this.offsety=parseInt(this.targetobj.style.top)
            this.x=evtobj.clientX
            this.y=evtobj.clientY

            if (evtobj.preventDefault)
                evtobj.preventDefault()
                document.onmousemove=dragobject.moveit
            }
        },
        moveit:function(e){
            var evtobj=window.event? window.event : e

            if (this.dragapproved==1){
                this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px"
                this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px"
                return false
            }
        }
    }

dragobject.initialize()

the css:
.heading{
    background: rgb(69,72,77); /* Old browsers */
    background: -moz-linear-gradient(top,  rgba(69,72,77,1) 0%, rgba(0,0,0,1) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(69,72,77,1)), color-stop(100%,rgba(0,0,0,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%); /* IE10+ */
    background: linear-gradient(to bottom,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#45484d', endColorstr='#000000',GradientType=0 ); /* IE6-9 */
}

.drag{
position:relative;
cursor:hand;
}

and the html:

Window

but it doesn't seem to work, i mean i can drag the window when the drag css is in the div with id="window1" but i cannot drag it with the black header, i have to drag it with the white space in the window, hope i made myself clear. when the drag css is in the div with id="window1x" i cannot drag the window at all as shown in the html code above, as a matter of fact i cannot drag anything. can anyone please tell me how to get around this. thanks!
P.S i found the dragging code by viewing the example source code from here

A: Try Adding pointer-events: none; to the CSS of your header bar.
So:
.heading {
    pointer-events: none;
}

This will allow click events to pass through to the actual container div that does the dragging.
See jsfiddle.
Warning: This will not work in IE10 or below.


text:
Q: Fourier transform that gives Heaviside step function Given,
$$
f(x) = \frac{1}{1+ix}
$$
in a textbook I am told that its Fourier transform is:
$$
\hat{\omega} = 2\pi~\Theta(-\omega)~e^\omega
$$
I am aware of the relation between the Heaviside step function and the Dirac delta function, however by applying the definition of a Fourier transform I am not able to derive the above result.

A: Correction: It must be $\dfrac{1}{1+i\omega}$ not $\dfrac{1}{1-i\omega}$.
First we try to find the Fourier transform of $g(x)=e^{-x}\Theta(x)$$$G(\omega)=\int_{-\infty}^{\infty}e^{-x}\Theta(x)e^{-i\omega x}dx=\int_{0}^{\infty}e^{-x}e^{-i\omega x}dx=\dfrac{e^{-x(1+i\omega)}}{1+i\omega}|_{\infty}^{0}=\dfrac{1}{1+i\omega}$$so$$g(x)\Leftarrow\Rightarrow \dfrac{1}{1+i\omega}$$by using duality:$$\dfrac{1}{1+it}\Leftarrow\Rightarrow2\pi g(-\omega)$$and$$\dfrac{1}{1+it}\Leftarrow\Rightarrow2\pi e^{\omega}\Theta(-\omega)$$


text:
Q: CSS header & footer, scrollable content I'm struggling with CSS to create scrollable "windows" with fixed header & footer and scrollable content. The accepted answer here is the nearest I have come to solving this, but this requires that one sets the height of the "content" class div.
<!DOCTYPE html>

Header

    Content

Footer

My aims are:
1. If content less than body height, no scroll
2. If content is longer than body height minus header & footer, then scroll.
How to achieve this?

A: You can use flex or grid :
flex example

body{

margin:0;
}
 .wrapper {
height:100vh;
display:flex;
flex-direction:column;
}
.content {
flex:1;
overflow:auto;
}

/* demo purpose */
.content:hover:before {
content:'';
display:block;
padding-top:150vh;
}

Header of any size

    Content

Footer of any size

and grid

body {
margin:0;
}
.wrapper {
height:100vh;
display:grid;
grid-template-rows:auto 1fr auto ;
}
.content {
overflow:auto;
}

/* demo purpose */
.content:hover:before {
content:'';
display:block;
padding-top:150vh;
}

Header of any size

    Content

Footer of any size

tutorials/reminders :

*

*https://css-tricks.com/snippets/css/a-guide-to-flexbox/

*https://css-tricks.com/snippets/css/complete-guide-grid/


text:
Q: Matching vertical layout in different ItemsControls I have ListView that uses a GridView to display several columns of data.
Two of the columns have cell templates containing ItemControl's to show a small collection in each cell.
The problem I have is that the vertical size of the ItemControls is not connected in any way since they are in different cells, and therefore they don't line up.
eg:(note this is ONE ROW in the parent listview)

XAML so far:
<ListView Margin="6,6,6,0" ItemsSource="{Binding Controllers}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem" >
            <Setter Property="VerticalContentAlignment" Value="Top" />
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>

         <!-- snip other columns -->

        <GridViewColumn Header="Mode">
             <GridViewColumn.CellTemplate>
                 <DataTemplate>
                    <ItemsControl ItemsSource="{Binding Modes}" DisplayMemberPath="Name"/>
                 </DataTemplate>
             </GridViewColumn.CellTemplate>
        </GridViewColumn>

        <GridViewColumn Header="Parameters">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding Modes}">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock  Text="Blah:" Margin="5,0"/>
                                    <ComboBox>
                                        <ComboBoxItem>Hello</ComboBoxItem>
                                    </ComboBox>
                                 </StackPanel>
                             </DataTemplate>
                         </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
    </GridView>
    </ListView.View>
</ListView>

My first thought was to use a grid as the ItemsPanel of the ItemsControls, so I could use SharedSizeScope on the rows to line them up. However, I can see no way of assigning items dynamically created by the ItemsControl to specific Grid rows.
Can anyone suggest a better solution?

A: Managed to fix this by setting ListView.ItemContainerStyle.VerticalContentAlignment to Stretch, and then using UniformGrid's for the ItemsControl panels:
Each cell now stretches vertically to match the largest cell, and using UniformGrid splits that vertical size evenly for each item.
eg
<GridViewColumn Header="Mode">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding Modes}" DisplayMemberPath="Name">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <UniformGrid Columns="1"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>


text:
Q: Pygame - Looping shooting bullets for space invaders Right now my code has 2 random aliens shoot 1 bullet, but I want this to loop so that when the bullets leave the screen, it loops for 2 more random aliens shooting bullets and so on.
http://pastebin.com/RhXp2zss
the class for the alien bullets is called Alien_Bullets
within class Space_invaders there should be the sprite group for the alien bullets and I need to include the looping bullet effect within the function update under Space_invaders

A: You should keep a reference to the Alien in your Alien_Bullets, then when de bullet gets destoyed you trigger a new shot. You can keep a counter in your Alien to know how many bullets it shot. When the counter reches 3 or the bullet hits the target you reset the counter and stop shooting.


text:
Q: Change Tkinter Frame Title I am trying to figure out how to change the title of a Tkinter Frame. Below is simplified code that mimics the portion of my program where I am trying to change the title:
from Tkinter import *

class start_window(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        Frame.pack(self)
        Label(self, text = 'Test', width=30).pack()

if __name__ == '__main__':
    start_window().mainloop()

With this sample code the Frame has the standard "tk" title but I would like to change it to something like "My Database". I've tried everything I can think of with no success. Any help would be appreciated.

A: Try this:
if __name__ == '__main__':
    root = Tk()
    root.title("My Database")
    root.geometry("500x400")
    app = start_window(root)
    root.mainloop()

A: First, you should be explicitly creating the main window by creating an instance of Tk. When you do, you can use the reference to this window to change the title.
I also recommend not using a global import. Instead, import tkinter by name,and prefix your tkinter commands with the module name. I use the name tk to cut down on typing:
import Tkinter as tk

class start_window(tk.Frame):
    def __init__(self, parent=None):
        tk.Frame.__init__(self, parent)
        tk.Frame.pack(self)
        tk.Label(self, text = 'Test', width=30).pack()

if __name__ == '__main__':
    root = tk.Tk()
    root.wm_title("This is my title")
    start_window(root)
    root.mainloop()

Finally, to make your code easier to read I suggest giving your class name an uppercase first letter to be consistent with almost all python programmers everywhere:
class StartWindow(...):

By using the same conventions as everyone else, it makes it easier for us to understand your code.
For more information about naming conventions used by the tkinter community, see PEP8

A: I generally start my tkinter apps with
#!/usr/local/bin/python3

import Tkinter as tk

root = Tk()

root.title('The name of my app')

root.minsize(300,300)
root.geometry("800x800")

root.mainloop()


text:
Q: Are there any (valid) C implementations where float cannot represent the value 0? If all floats are represented as x = (-1)^s * 2^e * 1.m , there is no way to store zero without support for special cases.

A: No, all conforming C implementations must support a floating-point value of 0.0.
The floating-point model is described in section 5.2.4.2.2 of the C standard (the link is to a recent draft). That model does not make the leading 1 in the significand (sometimes called the mantissa) implicit, so it has no problem representing 0.0.
Most implementations of binary floating-point don't store the leading 1, and in fact the formula you cited in the question:
x = (-1)^s * 2^e * 1.m

is typically correct (though the way e is stored can vary).
In such implementations, including IEEE, a special-case bit pattern, typically all-bits-zero, is used to represent 0.0.
Following up on the discussion in the comments, tmyklebu argues that not all numbers defined by the floating-point model in 5.2.4.2.2 are required to be representable. I disagree; if not all such numbers are required to be representable, then the model is nearly useless. But even leaving that argument aside, there is an explicit requirement that 0.0 must be representable. N1570 6.7.9 paragraph 10:

If an object that has static or thread storage duration is not
  initialized explicitly, then:

*

*...

*if it has arithmetic type, it is initialized to (positive or unsigned) zero;

*...

This is a very long-standing requirement. A C reference from 1975 (3 years before the publication of K&R1) says:

The initial value of any externally-defined object not explicitly initialized is guaranteed to be 0.

which implies that there must be a representable 0 value. K&R1 (published in 1978) says, on page 198:

Static and external variables which are not initialized are guaranteed
  to start off as 0; automatic and register variables which are not
  initialized are guaranteed to start off as garbage.

Interestingly, the 1990 ISO C standard (equivalent to the 1989 ANSI C standard) is slightly less explicit than its predecessors and successors. In 6.5.7, it says:

If an object that has static storage duration is not initialized
  explicitly, it is initialized implicitly as if every member that has
  arithmetic type were assigned 0 and every member that has pointer type
  were assigned a null pointer constant.

If a floating-point type were not required to have an exact representation for 0.0, then the "assigned 0" phrase would imply a conversion from the int value 0 to the floating-point type, yielding a small value close to 0.0. Still, C90 has the same floating-point model as C99 and C11 (but with no mention of subnormal or unnormalized values), and my argument above about model numbers still applies. Furthermore, the C90 standard was officially superseded by C99, which in turn was superseded by C11.

A: After o search a while a found this.
ISO/IEC 9899:201x section 6.2.5, Paragraph 13

Each complex type has the same representation and alignment requirements as an array
  type containing exactly two elements of the corresponding real type; the first element is
  equal to the real part, and the second element to the imaginary part, of the complex number.

section 6.3.1.7, Paragraph 1

When a value of real type is converted to a complex type, the real part of the complex
  result value is determined by the rules of conversion to the corresponding real type and
  the imaginary part of the complex result value is a positive zero or an unsigned zero.

So, if i understand this right, any implementations where supports C99 (first C standard with _Complex types), must support a floating-point value of 0.0.
EDIT
Keith Thompson pointed out that complex types are optional in C99, so this argument is pointless.

A: I believe the following floating-point system is an example of a conforming floating-point arithmetic without a representation for zero:
A float is a 48-bit number with one sign bit, 15 exponent bits, and 32 significand bits.  Every choice of sign bit, exponent bits, and significant bits corresponds to a normal floating-point number with an implied leading 1 bit.
Going through the constraints in section 5.2.4.2.2 of the draft C standard Keith Thompson linked:

*

*This floating-point system plainly conforms to paragraphs 1 and 2 of 5.2.4.2.2 in the draft standard.

*We only represent normalised numbers; paragraph 3 merely permits us to go farther.

*Paragraph 4 is tricky; it says that zero and "values that are not floating-point numbers" may be signed or unsigned.  But paragraph 3 didn't force us to have any values that aren't floating-point numbers, so I can't imagine interpreting paragraph 4 as requiring there to be a zero.

*The range of representable values in paragraph 5 is apparently -0x1.ffffffffp+16383 to 0x1.ffffffffp+16383.

*Paragraph 6 states that +, -, *, / and the math library have implementation-defined accuracy.  Still OK.

*Paragraph 7 doesn't really constrain this implementation as long as we can find appropriate values for all the constants.

*We can set FLT_ROUNDS to 0; this way, I don't even have to specify what happens when addition or subtraction overflows.

*FLT_EVAL_METHOD shall be 0.

*We don't have subnormals, so FLT_HAS_SUBNORM shall be zero.

*FLT_RADIX shall be 2, FLT_MANT_DIG shall be 32, FLT_DECIMAL_DIG shall be 10, FLT_DIG shall be 9, FLT_MIN_EXP shall be -16383, FLT_MIN_10_EXP shall be -4933, FLT_MAX_EXP shall be 16384, and FLT_MAX_10_EXP shall be 4933.

*You can work out FLT_MAX, FLT_EPSILON, FLT_MIN, and FLT_TRUE_MIN.


text:
Q: Grouping/aggregating SQL results into 1-hour buckets Similar to this question, I need to group a large number of records into 1-hour "buckets". For example, let's say I've got a typical ORDER table with a datetime attached to each order. And I want to see the total number of orders per hour. So I'm using SQL roughly like this:
SELECT datepart(hh, order_date), SUM(order_id)
FROM ORDERS
GROUP BY datepart(hh, order_date)

The problem is that if there are no orders in a given 1-hour "bucket", no row is emitted into the result set. I'd like the resultset to have a row for each of the 24 hour, but if no orders were made during a particular hour, just record the number of orders as O.
Is there any way to do this in a single query?
See also Getting Hourly Statistics Using SQL.

A: You need to have a pre-populated table (or a function returning a table result set) to join with, that contains all the 1-hour slots you want in your result.
Then you do a OUTER JOIN with that, and you should get them all.
Something like this:
SELECT SLOT_HOUR, SUM(order_id)
FROM
    ONEHOURSLOTS
    LEFT JOIN ORDERS ON DATEPART(hh, order_date) = SLOT_HOUR
GROUP BY SLOT_HOUR

A: Create a table of hours, either persisted or even synthesized 'on the fly':
SELECT h.hour, s.sum
FROM (
   SELECT 1 as hour
   UNION ALL SELECT 2
   UNION ALL SELECT 3
   ...
   UNION ALL SELECT 24) as h
LEFT OUTER JOIN  (
   SELECT datepart(hh, order_date) as hour, SUM(order_id) as sum
      FROM ORDERS
      GROUP BY datepart(hh, order_date) ) as s
  ON h.hour = s.hour;

A: Some of the previous answers recommend using a table of hours and populating it using a UNION query; this can be better done with a Common Table Expression:
; WITH [Hours] ([Hour]) AS
(
SELECT TOP 24 ROW_NUMBER() OVER (ORDER BY [object_id]) AS [Hour]
FROM sys.objects
ORDER BY [object_id]
)
SELECT h.[Hour], o.[Sum]
FROM [Hours] h
LEFT OUTER JOIN (
   SELECT datepart(hh, order_date) as [Hour], SUM(order_id) as [Sum]
      FROM Orders
      GROUP BY datepart(hh, order_date)
) o
ON h.[Hour] = o.[Hour]


text:
Q: SPF Records for subdomain sharing mail server I have two websites hosted on the same server.  I set up the second site after I had already set up the first site and its corresponding email server.  This is more of a DNS question.  The first server has been working trouble free for a long time, and its SPF record checks out just fine and I send mail with no issues.  I set up a second web server using an apache vhost, and I used iRedAdmin to set up a second email domain.  The problem appears to lie with my SPF record, and whenever I send mail form the second domain, it gets flagged as spam.  I've set it up using the original mail server as its MX, but I've never done two e-mail server on the same IP address and I'm not sure if I'm mucking it up.
Here are the two SPF records for reference (hostnames obfuscated):
This works fine:
v=spf1 a mx a:server1.com mx:mail.server1.com ip4:x.x.x.x ~all

This does not work:
v=spf1 a mx a:server2.com mx:mail.server1.com ip4:x.x.x.x ~all

And ideas?  Server 2 insofar as mail is concerned is simply a front for server1.  You can send mail to test@server2.com, but it gets routed through the iredmail server at server1.com.
Any insight would be appreciated as I need my messages to stop being flagged as spam.
Received-SPF: neutral (google.com: x.x.x.x is neither permitted nor denied by best guess record for domain of mymail@server2.com) client-ip=x.x.x.x;

Ok.  I don't care if you guys know my ip addresses, I just need to know why gmail sends this to the spam folder.  According to the headers in the message, it passes the SPF tests and etc.
Delivered-To: spuy767@gmail.com
Received: by 10.58.206.18 with SMTP id lk18csp38915vec;
        Fri, 22 Feb 2013 11:17:09 -0800 (PST)
X-Received: by 10.68.203.100 with SMTP id kp4mr4779507pbc.186.1361560628737;
        Fri, 22 Feb 2013 11:17:08 -0800 (PST)
Return-Path: <clay@claygarland.com>
Received: from signtelligence.com ([198.71.84.238])
        by mx.google.com with ESMTP id d10si3813292paz.55.2013.02.22.11.17.08;
        Fri, 22 Feb 2013 11:17:08 -0800 (PST)
Received-SPF: pass (google.com: domain of clay@claygarland.com designates 198.71.84.238 as permitted sender) client-ip=198.71.84.238;
Authentication-Results: mx.google.com;
       spf=pass (google.com: domain of clay@claygarland.com designates 198.71.84.238 as permitted sender) smtp.mail=clay@claygarland.com
Received: from localhost (localhost.localdomain [127.0.0.1])
    by signtelligence.com (Postfix) with ESMTP id DD33E5362890
    for <spuy767@gmail.com>; Fri, 22 Feb 2013 23:17:07 +0400 (MSK)
X-Virus-Scanned: Debian amavisd-new at signtelligence.com
Received: from signtelligence.com ([127.0.0.1])
    by localhost (signtelligence.com [127.0.0.1]) (amavisd-new, port 10024)
    with ESMTP id NhgKkX5jwSBC for <spuy767@gmail.com>;
    Fri, 22 Feb 2013 23:17:07 +0400 (MSK)
Received: from claygarland.com (localhost.localdomain [127.0.0.1])
    by signtelligence.com (Postfix) with ESMTPA id 76033536288F
    for <spuy767@gmail.com>; Fri, 22 Feb 2013 23:17:06 +0400 (MSK)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8;
 format=flowed
Content-Transfer-Encoding: 7bit
Date: Fri, 22 Feb 2013 14:17:06 -0500
From: clay@claygarland.com
To: <spuy767@gmail.com>
Subject: It's been a long time.
Message-ID: <59b5ce9cc073e86a1bc8bd15475a9a8c@claygarland.com>
X-Sender: clay@claygarland.com
User-Agent: RoundCube WebMail

Hey.  I just wanted to say hello.  It's been a long time since we've
talked.  My new phone number is (xxx) xxx-xxxx.  Give me a ring!

Peace,
Clay

A: First of all, you seem to have redundant syntax in your records.
I'm taking a guess because we would really need the right domains and IP to conclude anything for sure.
v=spf1 a mx a:server1.com mx:mail.server1.com ip4:192.168.1.254 ~all

If the SPF above is the SPF of server1.com then;
v=spf1 a ~all

is synonymous to
v=spf1 a:server1.com ~all

Also, if 192.168.1.254 is the IP of an A record of an MX record, then it too is redundant.
On a side note, I hope 192.168.1.254 is an obfuscated IP...your SPF should NOT have non-routable IP listed in them.
So lets assume that you are sending emails using the MX records on server1.com from both domains, your SPF records would look like this;
On server1.com;
v=spf1 +mx ~all

On server2.com;
v=spf1 +mx:server1.com ~all

On top of that, if both domains are having the same MX records, then you could use the same SPF on both domains.
On server1.com and server2.com
v=spf1 +mx ~all

The + in front of the mx makes sure the result would be a Pass as opposed to a Neutral result. Especially since you are using a soft fail (~all)
Finally, I would suggest you read the OpenSPF Syntax documentation.

A: I think you're misunderstanding how SPF records work.  Here's a breakdown of what you have.
a:server1.com : If the IP of the sending server resolves to server1.com, allow that machine to send mail.
mx:mail.server1.com : Get the MX records for the domain mail.server1.com. If any of these (there can be multiple) resolve to the IP of the sending server, then allow that machine to send mail.
ip4:192.168.1.254 : allow this IP to send mail for this domain.
So, assuming you only have one machine here, it should work if the SPF record for the second domain is the same as the first.  I.e.
v=spf1 a mx a:server1.com mx:mail.server1.com ip4:192.168.1.254 ~all

Although, you may be able to simplify this down depending on how the IPs resolve to:
v=spf1 a a:server1.com ip4:192.168.1.254 ~all

The other thing to check is that you have a PTR record set up correctly.  Whatever IP the server sends from should have a reverse lookup record to whatever the server HELO's itself as.
Good luck!


text:
Q: ASP.NET Threading: should I use the pool for DB and Emails actions? I'm looking for the best way of using threads considering scalability and performance.
In my site I have two scenarios that need threading:

*

*UI trigger: for example the user clicks a button, the server should read data from the DB and send some emails. Those actions take time and I don't want the user request getting delayed. This scenario happens very frequently.

*Background service: when the app starts it trigger a thread that run every 10 min, read from the DB and send emails.
The solutions I found:
A.  Use thread pool - BeginInvoke:
This is what I use today for both scenarios.
It works fine, but it uses the same threads that serve the pages, so I think I may run into scalability issues, can this become a problem?
B.  No use of the pool – ThreadStart:
I know starting a new thread takes more resources then using a thread pool.
Can this approach work better for my scenarios?
What is the best way to reuse the opened threads?
C.  Custom thread pool:
Because my scenarios occurs frequently maybe the best way is to start a new thread pool?
Thanks.

A: I would personally put this into a different service. Make your UI action write to the database, and have a separate service which either polls the database or reacts to a trigger, and sends the emails at that point.
By separating it into a different service, you don't need to worry about AppDomain recycling etc - and you can put it on an entire different server if and when you want to. I think it'll give you a more flexible solution.

A: I do this kind of thing by calling a webservice, which then calls a method using a delegate asynchronously.  The original webservice call returns a Guid to allow tracking of the processing.

A: For the first scenario use ASP.NET Asynchronous Pages. Async Pages are very good choice when it comes to scalability, because during async execution HTTP request thread is released and can be re-used.
I agree with Jon Skeet, that for second scenario you should use separate service - windows service is a good choice here.

A: Out of your three solutions, don't use BeginInvoke. As you said, it will have a negative impact on scalability.
Between the other two, if the tasks are truly background and the user isn't waiting for a response, then a single, permanent thread should do the job. A thread pool makes more sense when you have multiple tasks that should be executing in parallel.
However, keep in mind that web servers sometimes crash, AppPools recycle, etc. So if any of the queued work needs to be reliably executed, then moving it out of process is a probably a better idea (such as into a Windows Service). One way of doing that, which preserves the order of requests and maintains persistence, is to use Service Broker. You write the request to a Service Broker queue from your web tier (with an async request), and then read those messages from a service running on the same machine or a different one. You can also scale nicely that way by simply adding more instances of the service (or more threads in it).
In case it helps, I walk through using both a background thread and Service Broker in detail in my book, including code examples: Ultra-Fast ASP.NET.


text:
Q: Laravel where_column1_and_column2 error? I use laravel 4 PHP Framework when I write this method:

where_email_and_password($email, $password)

show this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column
  '_email_and_password' in 'where clause' (SQL: select * from users
  where _email_and_password = ? limit 1) (Bindings: array ( 0 =>
  'email@example.com', ))

See code and error: http://i.stack.imgur.com/dn85M.png

A: Looks like you are migrating from Laravel 3 where this is a valid method call. In Laravel 4, everything follows the camel case convention. I have not tested this but looking at the source code for the method that handles dynamic wheres, try whereEmailAndPassword($email, $password)
See the method here: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Query/Builder.php#L747
Hope this helps.


text:
Q: thrift.transport.TTransport.TTransportException: Could not start SASL: b'Error in sasl_client_start (-12) SASL library is not initialized' I have OS windows Server 2008 R2 and python
C:\Windows\system32>C:\Software\Python36\python --version
Python 3.6.4

installed libs
future (0.16.0)
pip (9.0.1)
pure-sasl (0.4.0)
PyHive (0.5.0)
sasl (0.2.1)
setuptools (28.8.0)
six (1.11.0)
thrift (0.11.0)
thrift-sasl (0.3.0)

Tried write client to Hive DB
import pyhs2 as hive
import getpass
DEFAULT_DB = 'default'
DEFAULT_SERVER = 'hive_server'
DEFAULT_PORT = 10010
DEFAULT_DOMAIN = 'mydomain'

# u = raw_input('Enter PAM username: ')
# s = getpass.getpass()
u="tech_user"
s="tech_passwd"
connection = hive.connect(host=DEFAULT_SERVER, port= DEFAULT_PORT, authMechanism='LDAP', user=u + '@' + DEFAULT_DOMAIN, password=s)

After executed return error
  File "C:\Software\Python36\lib\site-packages\pyhive\hive.py", line 159, in __init__
    self._transport.open()
  File "C:\Software\Python36\lib\site-packages\thrift_sasl\__init__.py", line 79, in open
    message=("Could not start SASL: %s" % self.sasl.getError()))
thrift.transport.TTransport.TTransportException: Could not start SASL: b'Error in sasl_client_start (-12) SASL library is not initialized'

How solve this problem?


text:
Q: Доступ к сайту через прокси ASP.NET public IActionResult Page()
{
  var url = "https://docs.microsoft.com";
  var proxy = new WebProxy("http://proxy address:port/", false);
  proxy.Credentials = new NetworkCredential("username", "password");
  var httpClientHandler = new HttpClientHandler();
  httpClientHandler.Proxy = proxy;
  var client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
  client.BaseAddress = new Uri(url);
  return Redirect(client.BaseAddress.ToString());

Переходит на сайт, но без прокси (хотя когда задаю настройки прокси явно через windows настройки на этот же сайт доступа нет)
Как можно проверить используется ли при этом сам прокси? А то может все работает, а я поднял шумиху


text:
Q: How do I stop my python code from printing none after it prints the string? str = input("Please enter y to start the program: ")
while str == 'y':
    def printNTimes(s, n):
        for i in range(n):
            print(s)

    phrase = input("Enter a string: ")
    number = int(input("Enter a positive number: "))

    allTogether = printNTimes(phrase, number)

    print(allTogether)
    print()
    str = input("Please enter y if you want to continue: ")
print("DONE")

Output:
Please enter y to start the program: y
Enter a string: Hi
Enter a positive number: 3
Hi
Hi
Hi
None

Please enter y if you want to continue:

A: You don't need print(allTogether), or the variable itself, because when you print it, you get an extra None (because the function returns None i.e, it does not return anything).
Also, put the function outside the while loop so that it is easier to read.
def printNTimes(s, n):
    for i in range(n):
        print(s)

str = input("Please enter y to start the program: ")
while str == 'y':
    phrase = input("Enter a string: ")
    number = int(input("Enter a positive number: "))

    printNTimes(phrase, number)
    print()
    str = input("Please enter y if you want to continue: ")
print("DONE")

Just call the function. You could use return and then print the function, but this might be easier.

A: The problem is the function printNtime is actually being used as a subroutine, meaning it doesn't RETURN any values.
I am not sure what you want as a final output so here's two solution.
IF USED AS SUBROUTINE: just remove the print(allTogether)
IF USED AS A FUNCTION: you need to create a string variable in the function and return it.
def printNTimes(s, n):
  mystring = ""
  for i in range(n):
    mystring = mystring + s + "\n"
  return mystring

A: The issue you're seeing is because your routine, printNTimes(), returns a None value. You say:
allTogether = printNTimes(phrase, number)

print(allTogether)

allTogether is set to None because printNTimes does not return a value. When you call print(allTogether), that's what is printing the None.
It sounds like you intended your printNTimes() routine to assemble one big string of all the output and return it, which you would then print out via the print(allTogether) call. But your printNTimes() routine is calling the print() method and outputing the text then. So, you need to rewrite your printNTimes() method.  Also, note that defining that function inside the loop is not necessary. Once is sufficient. So something like this should suffice:
def printNTimes(s, n):
    s_out = ""
    for i in range(n):
        s_out += s + '\n'
    return s_out
str_ = input("Please enter y to start the program: ")
while str_ == 'y':

    phrase = input("Enter a string: ")
    number = int(input("Enter a positive number: "))

    allTogether = printNTimes(phrase, number)

    print(allTogether)
    print()
    str_ = input("Please enter y if you want to continue: ")
print("DONE")

Also note that I renamed your str variable to str_. str is a Python type, a reserved word that should not be reused.


text:
Q: Flutter merge array which have same name I have array like this
[{
"providerName": "ABC",
"data1": "asd"
"data2: "asd"
},
{
"providerName": "ABC",
"data1": "asd"
"data2: "asd"
},
{
"providerName": "DEF",
"data1": "dsa"
"data2: "dosa"
},
{
"providerName": "GHI",
"data1": "ghg"
"data2: "hg"
}]

I want to merge the array in which the provider name is the same and save other data in one array.
So I am expecting output like this
[{
"providerName": "ABC", "dataMerge": [{"data1": "asd","data2: "asd"}, {"data1": "asd", "data2: "asd"}},
{
"providerName": "DEF", "dataMerge": [{"data1": "dsa", "data2: "dosa"}
},
{
"providerName": "GHI", "dataMerge": [{"data1": "ghg", "data2: "hg"},
}]


text:
Q: Why does typing variable length Tuple require ellipses but List does not? According to the docs:

To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

So therefore, the annotation Tuple[int] specifies a tuple containing a single integer; yet List[int] implies variable length.
Why must ... be used with Tuple[int, ...] and not with List[int] if both can be homeo/hetero-geneous?

A: A tuple is typically used for a small heterogenous set of values of fixed size. Therefore the type hint takes individual arguments denoting the type of each value, e.g. Tuple[str, int, list]. A homogeneous tuple is really a special case, and the ... notation is a shorthand for it.
A list is typically a homogenous sequence of undefined length. Hence its type hint only takes one argument.


text:
Q: !function($) means what? I have some questions about jquery plugin - bootstrap-popover.js.

*

*!function ($){ // meaning?

*some lines have no semicolon and comma, why?

*}(window.jQuery); // meaning?

!function ($) { //<--- 1. what does this line mean?

      "use strict"; // jshint ;_;

      var Popover = function (element, options) {

        this.init('popover', element, options) //<-- 2. this line has no semicolon, why...?

      }

      Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
        ..................................
      })

      var old = $.fn.popover

      $.fn.popover = function (option) {
        return this.each(function () {

          var $this = $(this)
            , data = $this.data('popover')
            , options = typeof option == 'object' && option

          if (!data) $this.data('popover', (data = new Popover(this, options)))

          if (typeof option == 'string') data[option]() // <-- 3. this line has no semicolon no comma, why...?

        })

      }
    .......................................

    }(window.jQuery); // <-- 4. what does this line mean?

A: !function ($) {...}(window.jQuery); is equivalent to
(function ($) {...})(window.jQuery); or
(function ($) {...})(window.jQuery); which has the same behaviour.
It is a IIFE, self invoked function: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression
(window.jQuery) is the param passed to the anonymous function, this is to put $ inside function refers to jQuery version passed as parameter.
Forget to tell about semi-colon. Following ECMAScript, semi-colons are optionnal, javascript engine are enough clever to find when add them when missing. But, as a side note, there is a particular behaviour:
Following code will always return 'undefined':
return
        1;

In this case, as a new line is detected and engine doesn't know what to return, a semi-colon will be added between return statement and value, giving:
return ;1;

So use: return 1; without new line between it. return 1 will works too, of course.

A: In Javascript / EMCA script, functions are values that can be passed around, called anonymously, or just plain used.
So, for example, the following is perfectly fine.
var square_something = function(x) { return x * x; };
alert(square_something(5));

Taking this concept a step further, we can do things like
alert(function(x) { return x * x; }(5));

That is to say, invoke (or call) the (anonymous) function with the value 5
Another wonderful feature of Javascript / ECMA script is that the character "$" is a perfectly valid variable name. So I can do
var $ = 5;
alert ($);

And I will see the value 5 perfectly fine. The jQuery library makes extensive use of this, as do other Javascript libraries. Or...
var myFunc = function($) { alert($ + 10); }
myFunc(32); // should alert the number 42

In jQuery extensions, you will often see this pattern...
function($) {
  // all the extension code...
}(window.jQuery);

Which is to say, invoke the anonymous function with the value window.jQuery. They do this because other Javascript libraries use the variable $ but not the variable window.jQuery. This is a very subtle way to use the very short and convienent $ instead of window.jQuery everywhere, only within the scope of the defined function.
To answer your "no semi-colon question"... There is no semi-colon on the line you mention because it is not required there. It would, however, be required if you had another line :)


text:
Q: Better way of mixing up own framework with PHP zend framework Recently I've started to use Zend framework next to my own framework. The solution at this moment for instance for the module "partner" having a rewrite condition in htaccess like
RewriteCond %{REQUEST_URI} ^./partner/?(.)
//redirect to build ZF
RewriteRule ^.*$ public/partner/index.php
// and the bootstrap files are
//index.php for Zend
set_include_path(APPLICATION_PATH . '../../../library/php/');
include_once 'Zend/Loader/Autoloader.php';
//index.php for own framework
set_include_path(get_include_path() . PATH_SEPARATOR . 'library/php/');
Is it possible to use Zend components just like it would with PEAR components?
Or the question with different perspective
Am I required to choose one of the two MVC patterns to go along with?
At the end I want to be able to use any library/framework for any module.

A: You can use ZF components similar to PEAR stuff. The only thing you will need to do is set the include path so, that ZF's requires will function:
set_include_path('path/to/library' . PATH_SEPARATOR . get_include_path())

where path/to/library contains the Zend directory.
At this point you can either initialize the ZF autoloader, or use require_once to load any classes you want to use.


text:
Q: Como criar um método assíncrono que seja cancelável? Como criar um método assíncrono que seja cancelável?
Nesse contexto, o método DoFoo() faz coisas que não podem ser simplesmente paradas, como leitura e gravação de arquivos, e ao cancelar, tenho que esperar que essas operações de I/O sejam concluídas para o método ser cancelado.
private async void Button_Click()
{
    await DoFoo();
}

private async void Cancelar_Click()
{
    // cancelamento do método DoFoo()
    // ...
}

private async Task DoFoo()
{
    // operações de I/O
    File.WriteAllText("path", "conteudo");

    // operações de longa execução

    // ...
}

A: Precisa criar um token de cancelamento no método. Só pode cancelar o que está preparado para o cancelamento. De forma geral a API assíncrona do .NET aceita.
CancellationTokenSource cts;

private async void Button_Click() {
    cts = new CancellationTokenSource();
    try {
        await DoFoo(cts.Token);
    } catch (OperationCanceledException ex) {
        //trata o cancelamento
    }
}

private async void Cancelar_Click() => cts.Cancel();

private async Task DoFoo(CancellationToken ct) {
    // operações de I/O
    File.WriteAllText("path", "conteudo");
    for (var item in lista) {
        //faz o que quiser aqui
        ct.ThrowIfCancellationRequested(); //isto pode ser muito lento
    }
}

Coloquei no GitHub para referência futura.
É comum não verificar se houve pedido de cancelamento em cada passo do loop já que a verificação tem um custo razoável, então pode filtrar quando aceitar uma requisição de cancelamento, talvez a cada 1000 itens processados, por exemplo.
Certamente tem outras formas de fazer dependendo do objetivo. Exceção não precisa ser o mecanismo de tratamento.
Documentação do CancellationTokenSource.
Documentação do CancellationToken.


text:
Q: Extending EF Poco Class I am learning EF 4 staff and really got stacked.  I am using Code First approach eg.
public class Machine{
 public int A{get;set;}
 ...
}

I am trying to implement business logic in additional property based on the A property (eg. B = A+5) and present it in WPF datagrid. This new property doesn't need to be stored in database at all. How would I do that (e.g. with partial class )? Any examples?

A: public class Machine
{
    public int A { get; set; }

    [NotMapped]
    public int B
    {
        get
        {
            return A + 5;
        }
    }
}

This should work.

A: If you are using EF 4.1 you can just use the not mapped attribute. If you are using the edmx designer, i beleive you can remove the column name it assigns to in the model viewer table mappings


text:
Q: Accessing source code for Spring Annotations Where can I see the source code behind the @Service or org.springframework.stereotype.Service in the Spring framework?

A: Annotations themselves do not carry implementation logic, just some simple attributes. The framework (Spring in our case) just checks for the existence of annotations (i.e instances of an annotation class like Service) on our classes and then acts accordingly. For example, if it sees a Service present, it will instantiate our class as a bean and manage that bean.

A: If you are using IDE, to check @Service implementation you can press Ctrl and click on this annotation. org.springframework.stereotype.Service interface will be opened in this case.


text:
Q: scipy.signal.spectrogram frequency resolution scipy.signal.spectrogram calculates the spectrogram for a signal, but I can't see an option to increase the frequency resolution of this spectrogram.
Given the code available from the documentation, how could that be achieved?
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt

fs = 10e3
N = 1e5
amp = 2 * np.sqrt(2)
noise_power = 0.01 * fs / 2
time = np.arange(N) / float(fs)
mod = 500*np.cos(2*np.pi*0.25*time)
carrier = amp * np.sin(2*np.pi*3e3*time + mod)
noise = np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
noise *= np.exp(-time/5)
x = carrier + noise

f, t, Sxx = signal.spectrogram(x, fs)
plt.pcolormesh(t, f[0:10], Sxx[0:10,])
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()

A: The spectral resolution is determined by the number of points used in the FFT, which is controlled by the nperseg parameter. To increase the resolution you would increase the number of input points per FFT computation. For example, increasing the number of points from the default 256 to double the resolution (i.e. 512 points) you would call scipy.signal.spectrogram like so:
f, t, Sxx = signal.spectrogram(x, fs, nperseg=512)

Note that you could also use:
f, t, Sxx = signal.spectrogram(x, fs, nfft=512)

to use more points in the FFT, but not more input point per segment (i.e. zero padding each segment). This would essentially produce a spectrogram where the additional frequency points are interpolated. It wouldn't increase the resolution (i.e. two tones with very similar frequencies wouldn't be any more distinguishable), but the additional points would make the result appear more smooth.


text:
Q: CMOS Inverter DC charecteristics steepness I was trying to solve the following multiple choice question(only one option is correct).

I simulated the inverter for varying W with L constant. What I found is the absolute value of dVout/dVin increases when W decreases.
Can anyone explain this?
I went through this question where I found the small signal gain increases with decreasing W.
But here we are looking at large signal behavior.
Also please mention the solution of the above question.

A: The question is not very well formulated and this is the main problem here. However, the most likely answer is (d).
Generally the transition slope can be described by the small signal gain \$A_V\$ of the circuit which is given by
$$
A_V = -\frac{g_{m,p} + g_{m,n}}{g_{ds,p} + g_{ds,n}}
$$
where \$g_{m,p}\$ and \$g_{m,n}\$ are the transconductances and \$g_{ds,p}\$ and \$g_{ds,n}\$ the output conductances of the PMOS and NMOS transistors, respectively.
So, the sum of transconductances needs to be maximized and the sum of the conductances minimized.
Using
$$
g_m = \frac {2 I_D}{V_{GS}-V_T}
$$
where \$I_D\$ is the drain current, \$V_{GS}\$ the gate-source voltage and \$V_T\$ the threshold voltage of the transistor. For the output conductane we can write
$$
g_{ds} = \lambda^\prime / L  \cdot I_D
$$
where \$\lambda^\prime\$ is a constant and L the transistor's channel length.
Now an important observation can be made. Using these two expressions in the equation for the gain \$A_V\$ the current ID drops out of the equation, since both gm and gds are proportional to the current and only their ratio determines the gain.
Making the assumption that the switching threshold of the inverter is at half the supply voltage it can be shown that (d) is the correct answer. Since the gate-source voltage of both transistors is half the supply voltage the expression for gm is
$$
g_m = \frac{2 I_D}{V_{GS}-V_T} = \frac{2 I_D}{V_{DD}/2-V_T}
$$
with \$V_{DD}\$ being the supply voltage. As shown above, the drain current drops out of the equation, so the contribution of transconductance is constant. Therefore the only way to increase the gain AV is by decreasing gds.
With \$g_{ds} = \lambda^\prime / L  \cdot I_D\$ and noting that \$I_D\$ gets cancelled when used in the expression for \$A_V\$, an increase of L will result in a decrease of gds and therefore will result in a higher gain.
However, if the switching threshold is not centered things are different. We can maximize the transconductance of either the PMOS or the NMOS transistor and get a steeper slope. To move the switching threshold the width of the PMOS or the NMOS could be increased. This would result in (a) or (b) as the correct answer.
This could also explain the results you got from simulation, if you didn't properly adjust the switching threshold of the inverter before and after changing the width.


text:
Q: Calling method from AppDelegate unrecognized selector sent to instance error I'm trying to call another class's method in AppDelegate.m. I've done the following:

*

*In MyClass.h, I have  -void testMethod

*In AppDelegate.m, I have
#import "MyClass.h"
MyClass * myClassInstance = [[MyClass alloc] init];
[myClassInstance testMethod]

*In AppDelegate.h, I have also imported
#import "MyClass.h"
I think I've done everything the answer to this question suggested: calling a method inside someClass from AppDelegate Objective-C IOS
But I'm still getting a "Unrecognized selector sent to instance" error?
What's missing?
Thanks in advance.

A: Try to put the method call in some appDelegate lifecycle method like:
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

     // Override point for customization after application launch.
     Test* testObject = [[Test alloc] init];
     [testObject testMethod];
     return YES;
 }

For the class that you are instantiating use something like:
Test.h file
 #import <Foundation/Foundation.h>

 @interface Test : NSObject

 -(void)testMethod;

 @end

and Test.m file
 #import "Test.h"

 @implementation Test

 -(void)testMethod{
     NSLog(@"test");
 }

 @end

In this case when the apps initialize the log message appears on console.


text:
Q: DBNETLIB ConnectionOpen (Connect()) error with Delphi 2010 application accessing SQL Server 2005 with OLEDB drivers on Windows 7 x64 I built a D2010 application, which uses a TADOConnection component to connect to SQL Server using OLEDB drivers and tcp/ip. The problem is that my application can't connect to the database when I execute it (inside the IDE or not) from a network drive. Each time I try i get this error through the IDE:
---------------------------
Debugger Exception Notification
---------------------------
Project TroisTiers.exe raised exception class EOleException with message '[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.'
---------------------------
Break   Continue   Help
---------------------------

and I get a "EOleException: Unspecified error" when I run the application outside the IDE.
The thing is, When I copy the .exe on a local drive (C:) it works instantly, no errors, no lag. When I compile the D2010 application on a WinXP computer and execute it from Win7, it also works flawlessly. When I take the .exe I builded and execute it on a x86 Windows 7, I get the same errors as above.
I noticed that when I start the application on the network drive, the following modules are loading:
Module Load: WSHTCPIP.dll. No Debug Info. Base Address: $74CD0000. Process TroisTiers.exe (848)
Module Load: WSHIP6.dll. No Debug Info. Base Address: $74010000. Process TroisTiers.exe (848)
Module Load: DBnmpntw.dll. No Debug Info. Base Address: $750C0000. Process TroisTiers.exe (848)

I have asserted that the app tries to connect using TCP/IP first, then for whatever reason resorts to named pipes. Just for tests, I activated the named pipes protocol on the server and it started to work but not every time and takes up to 10 seconds before the connection is made. I deactivated it since it's not the way we connect to the production databases. When the app is executed locally (and showing data correctly), the DBnmpntw.dll module is neved loaded.
When I build a connection string (through a .udl file) and test the connection, it works, though I am not certain if I'm testing through the 64bit or 32bit drivers.
Setting the .exe output directory to my local drive is an acceptable work-around for now but I would really like to know what's causing this problem, as it makes things complicated with working in an up-to-date environment (additionnal files beside the .exe).
Additionnal info, for what it's worth:
My connection string: 'Provider=SQLOLEDB.1;Persist Security Info=True;User ID=*;Password=hunter2;Initial Catalog=[database name];Data Source=[server ip address]'.
I tried to force using TCP/IP with "Network Library=DBMSSOCN;" but it doesn't help.
Firewalls disabled on my computer and on the server;
McAfee AV on my computer, managed through ePO;
SQL Server 2005 x64 running on Win2k3 x64;
Windows 7 without SP1 installed;
cliconfg.exe -> active protocol is tcp/ip only;
I can provide additionnal info if needed.

A: Is your .EXE too large for running on a network shared drive?  I have the same experience when the size of .EXE exceed 25MB or something closed to.
The solution is simple, just to move the .EXE back to local drive.


text:
Q: Problem uploading member image in Umbraco I am working with member API in Umbraco 8 and i am trying to upload the image when registering. After i register member and open member profile in backoffice i see this:

This is my Coontroller
    public class RegisterController : SurfaceController
{
    // GET: Register
    public ActionResult Register(Models.RegisterModel model)
    {
        if (!ModelState.IsValid)
            return CurrentUmbracoPage();

        var memberService = Services.MemberService;

        if (memberService.GetByEmail(model.Email) != null)
        {
            ModelState.AddModelError("", "A member with that email alredy exists");
            return CurrentUmbracoPage();
        }

        var member = memberService.CreateMemberWithIdentity(model.Email, model.Email, model.Name, "bMEMembers");

        member.SetValue("companyName", model.CompanyName );
        member.SetValue("avatar", model.Avatar);

        memberService.SavePassword(member, model.Password);
        Members.Login(model.Email, model.Password);

        memberService.Save(member);

        return Redirect("/");
    }
}

Model:
        public HttpPostedFileBase Avatar { get; set; }

View:
    @Html.LabelFor(model => model.Avatar)
    <input type="file" name="Avatar" />
    @Html.ValidationMessageFor(model => model.Avatar)

    <input class="btn" type="submit" value="Create" />

Anybody could help me with this?

A: It's normal to appear because Avatar is an object (exactly: HttpPostedFileBase), and LabelFor will display object namespace.
Take a look: https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.html.labelextensions.labelfor?view=aspnet-mvc-5.2
and see that there is an overload for that method:
public static System.Web.Mvc.MvcHtmlString LabelFor<TModel,TValue> (this System.Web.Mvc.HtmlHelper<TModel> html, System.Linq.Expressions.Expression<Func<TModel,TValue>> expression, string labelText, System.Collections.Generic.IDictionary<string,object> htmlAttributes);

you can use like:
@Html.LabelFor(model => model.Avatar, "Avatar", null);

or more beauty way:
[DisplayName("Avatar")]
public HttpPostedFileBase Avatar { get; set; }

and leave your CSHTML code:
@Html.LabelFor(model => model.Avatar)


text:
Q: How to Detect Empty Rows Programmatically Using Open XML and SAX? I am working on an application that parses rows from a sheet in a xlsx file using Open XML with SAX. However, I was testing my implementation with a spreadsheet that has empty rows here and there. I would like to skip all the empty rows that I may find while I am looping through the rows in a sheet.
For example, I have the following spreadsheet

I opened up the spreadsheet using the Open XML Productivity tool and I found out that rows with empty cells all over have only one cell in the markup. That cell has an attribute called "s" that the other cells with cell values do not seem to have.
I was wondering if there is a way in code to find out if a given row is empty.
So far what I am doing to go through the rows in the sheet is the following:
do{
if (reader.ElementType == typeof(Row))
{
    reader.ReadFirstChild();
    Type generatedType = typeBuilder.CreateType();
    object generatedObject = Activator.CreateInstance(generatedType);

    PropertyInfo[] properties = generatedType.GetProperties();

    int propertiesCounter = 0;
    // Read all the cells in the row.

    do
    {
        if (reader.ElementType == typeof(Cell))
        {
            c = (Cell)reader.LoadCurrentElement();

            if (c.DataType != null
                && c.DataType.HasValue
                && c.DataType == CellValues.SharedString
                && int.Parse(c.CellValue.InnerText) < ssTable.ChildElements.Count)
            {
                value = ssTable.ChildElements[int.Parse(c.CellValue.InnerText)].InnerText ?? string.Empty;
            }
            else
            {
                if (c.CellValue != null && c.CellValue.InnerText != null)
                {
                    value = c.CellValue.InnerText;
                }
                else
                {
                    value = string.Empty;
                }
            }
            Debug.WriteLine(value);
            properties[propertiesCounter].SetValue(generatedObject, value, null);
            propertiesCounter++;
        }
    } while (reader.ReadNextSibling());
    listObjectsCustomClasses.Add(generatedObject);
}} while (reader.Read() && reader.ElementType == typeof(Row));

Thank you very much for your kind help!
EDIT: I just found this answer in SO that explains that "The s attribute refers to a style". However, I am still interested in a way to find out programatically if a row is totally void of information using Open XML.

A: can you share the excel file which you are using for testing ?
As per openXML, If any row is empty, then the respective row tag will not be available.
as per below data, row with index 2 is not at all generated. So you can loop through the row tags and if their attribute r is not matching with loop index , then that row is empty.

<row r="1" x14ac:dyDescent="0.35" spans="1:4">
<c r="A1" t="s">
<v>0</v>
</c>
<c r="B1" t="s">
<v>1</v>
</c>
<c r="C1" t="s">
<v>2</v>
</c>
<c r="D1" t="s">
<v>3</v>
</c>
</row>
<row r="3" x14ac:dyDescent="0.35" spans="1:4">
<c r="A3">
<v>1</v>
</c>
<c r="B3">
<v>2</v>
</c>
<c r="C3">
<v>3</v>
</c>
<c r="D3">
<v>4</v>
</c>
</row>


text:
Q: How to preserve selective faces messages across multiple pages? We can ask JSF to keep faces messages intact to show on redirected pages using flash.
But I have a situation, where I have to show a warning message on all pages in a given session. I don't want to use flash because it will keep all the messages, which means even the error messages on a particular page will be propagated to other pages, where they don't make any sense.
Does anyone know how to selectively retain faces messages?


text:
Q: Remake a JQuery function to allow it to be called any time I know it's a stupid question but I'm quite new to JQuery and I have a preatty basic problem...
This function is called on mousemove
How can I remake it so I can call it any time?

$(document).on('mousemove', function(e){
 $('#cursor').css({
  left: e.pageX - 7,
  top: e.pageY - 7
 });
});

A: Since you need to use the pointer coordinates inside a nested function, may be you can keep track of them in some variables.
var posX, posY;

$(document).on('mousemove', function(e){
    $('#cursor').css({
        left:   e.pageX - 7,
        top:    e.pageY - 7
    });
    posX = e.pageX;
    posY = e.pageY;

});

function parentFunction(){
   //Some code

   $('#cursor').css({
        left:   posX - 7,
        top:    posY - 7
    });
}

parentFunction();

A: You might do it like this (please see comments in the code):
$(document).ready(function() {

  // setup an object to store mouse position
  var mousepos = {};
  // update the object on mousemove
  $(document).on('mousemove', function(e) {
    mousepos = {
      x: e.pageX,
      y: e.pageY
    }
  });

  // setup a function to update cursor position
  function setCursor() {
    $('#cursor').css({
      left: mousepos.x - 7,
      top: mousepos.y - 7
    });
  }

  // your code
  list = {
    execute: function() {
      // Some code and the nested function
      setCursor();
    }
  };

  list.execute();

});

Hope it helps.


text:
Q: Measuring TLB miss handling cost in x86-64 I want to estimate the performance overhead due to TLB misses on a x86-64 (Intel Nehalem) machine running Linux. I wish to get this estimate by using some performance counters. Does anybody has some pointers on what is the best way to estimate this?
Thanks
Arka

A: If you can get access to a "Westmere" based system the performance characteristics of your code should be quite similar to what you have on the "Nehalem", but you will have access to a new hardware performance counter event that measures almost exactly what you want.
On Westmere, the best estimate of performance lost while waiting for TLB misses to be handled is probably from the hardware performance counter Event 08H, Mask 04H "DTLB_LOAD_MISSES.WALK_CYCLES", which is described as counting "Cycles Page Miss Handler is busy with a page walk due to a load miss in the Second Level TLB".
This is described in "Intel® 64 and IA-32 Architectures Software Developer's Manual
Volume 3B: System Programming Guide, Part 2" (document number: 253669), available online at
http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-3b-part-2-manual.html
The reason this event is necessary is that TLB miss processing time is dominated by the time required to read the cache line containing the page table entry.  If that cache line is in the L2 cache, then the overhead of a TLB misses will be very small (of the order of 10 cycles).  If the line is in the L3 cache, then maybe 25 cycles.  If the line is in memory, then ~200 cycles.

*

*If there is also a miss in the upper-level page translation caches, it will take multiple trips to memory to find and retrieve the desired page table entry (e.g., https://stackoverflow.com/a/9674980/1264917).

*On some processors the L2 cache counters can tell you how many table walks hit and missed in the L2, but not on Nehalem.  (It would not help a lot in this case since TLB walks that hit in the L3 are also fairly fast and what you really want are the TLB walks that have to go to memory.)


text:
Q: Mojave scroll left/right not working properly for native apps I updated my mac to macOS Mojave and I am facing problems for native apps when I scroll left or right, for instance:

*

*On Safari, I can't go to the previous page scrolling to the left (works on Chrome)

*I can't dismiss pop-up notifications

*"swipe menus" for Mail, for instance, are not accessible

I tried to tick/untick the Trackpad settings, didn't work.


text:
Q: Objective C with some C++ code won't compile I have an Objective C project with some C++ code, and sure enough the C++ code won't compile
I understand that the compiler makes assumptions about which language to compile, but I have seen this app running before so I am curious how to make my Xcode 4 run compile this project
ie. This function declaration produces an error as the compiler does not recognize the c++ std:: syntax
 std::string string_with_formatting(const unsigned int value)
 {

How do I get around this? What #include or #import should I have

A: Objective-C++ is a superset of C++. You can use C++ in Objective-C++ sources.

*

*Make sure the file has .mm extension, otherwise it will be treated as Obj-C, not Obj-C++

*#include <string>

A: Change that file to .mm and also any other that includes that file (or that files accompanying .h).

A: objective C has no concept of std::string.  You need to use something like NSString


text:
Q: Can not check network info programmatically in battery save mode in android device I want to check connection state in my android app. I call the next method in onResume:
public boolean isThereInternetConnection() {
        boolean isConnected = false;
        ConnectivityManager connectivityManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = (connectivityManager != null) ? connectivityManager.getActiveNetworkInfo() : null;
        if (networkInfo != null) {
            isConnected = networkInfo.isConnected();
        }
        return isConnected;
    }

In normal mode it works well. But when my device is on battery saver mode and I open my activity from background, method isThereInternetConnection() returns false sometimes (internet connection was well). For this I checked networkInfo.getDetailedState() and in battery saver mode it returns DetailedState.BLOCKED even I have good internet connection. So how to resolve this bug, how to check internet connection in battery saver mode and obtain real value true or false - connected to internet or not?

A: The best way to check internet is actually pinging to the internet. Sometimes the internet is connected but no network access.
public boolean isOnline() {
    try {
        int timeoutMs = 1500;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, timeoutMs);
        sock.close();

        return true;
    } catch (IOException e) { return false; }
}

The above code will not run on the main thread and requires internet
  connectivity permission.

The code below is a bit slow but will work on the main thread. Requires internet connectivity permission:
public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    }
    catch (IOException e)          { e.printStackTrace(); }
    catch (InterruptedException e) { e.printStackTrace(); }

    return false;
}

Ref: How to check internet access on Android

A: You can use this method :
public void checkInternetAndContinue() {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                int timeoutMs = 1500;
                Socket sock = new Socket();
                SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

                sock.connect(sockaddr, timeoutMs);
                sock.close();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startWork(true);
                    }
                });
            } catch (IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startWork(false);

                    }
                });
            }
        }
    });
    thread.start();
}

and continue work if there is internet
private void startWork(boolean b) {
     if(b){
         // do whatever you want when the internet is available
     } else {
         // No Internet.
     }
}

Hope it help!


text:
Q: RecylcerView item click listener I'm trying to capture the on click event of the items in my RecyclerView, but it isn't working. My research (SO) told me to put the listener in the adapter, so I did. Here's the code :
    public class PoliticianPagerAdapter extends RecyclerView.Adapter<PoliticianPagerAdapter.ViewHolder> {
        private Politician[] mDataset;

        // Provide a reference to the views for each data item
        // Complex data items may need more than one view per item, and
        // you provide access to all the views for a data item in a view holder
        public  class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            // each data item is just a string in this case
            public TextView name;
            public TextView term;
            public TextView position;
            public ImageView image;
            public CardView card ;
            public ViewHolder(View layout) {
                super(layout);
                name = (TextView) layout.findViewById(R.id.politicianNameAndParty);
                term = (TextView) layout.findViewById(R.id.politicianTerm);
                position = (TextView) layout.findViewById(R.id.politicianPosition);
                image = (ImageView) layout.findViewById(R.id.politicianImage);
                card = (CardView) layout.findViewById(R.id.politicianCard);
            }

            @Override
            public void onClick(View view)
            {

                Intent intent = new Intent(getActivity(),PoliticianPage.class);
                startActivity(intent);

            }
        }

        public PoliticianPagerAdapter(Politician[] myDataset) {
            mDataset = myDataset;
        }

        @Override
        public PoliticianPagerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                       int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.fragment_home_politician_block, parent, false);

            return new ViewHolder(v);

        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            // - get element from your dataset at this position
            // - replace the contents of the view with that element
            holder.name.setText(mDataset[position].name + " (" + mDataset[position].party + ")");
            holder.term.setText(Integer.toString(mDataset[position].termBegin) + " - " + Integer.toString(mDataset[position].termEnd));
            holder.term.setText(mDataset[position].position);
            holder.image.setImageResource(mDataset[position].image);

        }

        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return mDataset.length;
        }
    }

A: Use a View inside the CardView to intercept the click event.
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        android:elevation="3dp"
        card_view:cardCornerRadius="4dp">

        <!-- Your card -->

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/clickable_view_card"
            android:clickable="true"/>

    </android.support.v7.widget.CardView>
</LinearLayout>

Adapter:
 public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

        public class ViewHolder extends RecyclerView.ViewHolder {
            public RelativeLayout clickable_layout;

            public ViewHolder(View itemView) {
                super(itemView);
                clickable_layout = (RelativeLayout) itemView.findViewById(R.id.clickable_view_card);

            }
        }

        @Override
        public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.card_view, parent, false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(final Adapter.ViewHolder holder, final int position) {

            holder.clickable_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("OnClick", "position clicked: "+ position);
                }
            });

        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }


text:
Q: JasperReportsPdfView cannot be resolve in my spring boot. In my spring boot I want to generate a list in pdf. According to the tutorial and blog I did everything as the described. But In my controller class when I declare JasperReportsPdfView view = new JasperReportsPdfView(); I am getting red alert. I don't get any suggestion from intellij idea to import class.
My controller class is
@Controller
public class PdfController {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    StudentService studentService;

    @GetMapping("/getreport")
    public ModelAndView getReport()
    {
        JasperReportsPdfView view = new JasperReportsPdfView();
        view.setUrl("classpath:/reports/report.jrxml");
        view.setApplicationContext(applicationContext);

        Map<String, Object> studentMap = new HashMap<>();
        studentMap.put("datalist", studentService.generateReports());
        return new ModelAndView(view, studentMap);
    }
}

And my pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.avijit</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>test</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.0.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>4.2.2</version>
        </dependency>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.0.3.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Please anyone help me to solve this problem.

A: It seems that JasperReports support was removed in Spring 5. See this answer:
https://stackoverflow.com/questions/47271098/spring-5-reporting