text:
Q: How to custom field select options in register and saving them in db I need to add select input in registration from in magento 2 I did all the steps but in InstallData.php file I have this partial code
  $eavSetup->addAttribute(Customer::ENTITY, 'account_type', [
        // Attribute parameters
        'type' => 'int',
        'label' => 'Account Type',
        'input' => 'select',
        'required' => true,
        'visible' => true,
        'user_defined' => true,
        'sort_order' => 990,
        'position' => 990,
        'system' => 0,
        'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
        'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
        'option' => ['values' => [1=>'Customer', 2=>'Designer or Architect']],
        'is_used_in_grid' => 1,
        'is_visible_in_grid' => 1,
    ]);

I think it add select's options in db but it doesn't take values in right way it suppose to be 1 and 2 but it shows 4 and 5 like:
  <option data-title="Customer" value="4">Customer</option>
  <option data-title="Designer or Architect" value="5">Designer or Architect</option>

How to make this take the values I defined?

A: $eavSetup->addAttribute(Customer::ENTITY, 'account_type', [
        // Attribute parameters
        'type' => 'text',
        'label' => 'Account Type',
        'input' => 'select',
        'required' => true,
        'visible' => true,
        'user_defined' => true,
        'sort_order' => 990,
        'position' => 990,
        'system' => 0,
        'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
        'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
        'option' => ['values' => ['Customer', 'Designer or Architect']],
        'is_used_in_grid' => 1,
        'is_visible_in_grid' => 1,
    ]);


text:
Q: Can transactions on main table be delayed/deadlock when maintenance transaction on temporal table runs? I am going to run maintenance procedure similar to described in Cannot delete rows from a temporal history table .
The stored procedure will SET SYSTEM_VERSIONING = OFF , delete 3 million rows on temporal table and set it ON. It will take some time.
The question is how likely transactions on main table  be impacted by running the stored procedure?
Am I right that selects on the main table will not be impacted?
What about inserts/ updates on the main table?
Information for reference from Microsoft documentation Stopping system-versioning on a system-versioned temporal table

When you set SYSTEM_VERSIONING = OFF and don't remove drop the
SYSTEM_TIME period, the system continues to update the period columns
for every insert and update operation.

A: If you are scared about locking you can always delete those rows in a loop preventing table lock
DECLARE @Rows INT SET @Rows = 1

WHILE (@Rows > 0) BEGIN
DELETE TOP (4500) FROM myTable
WHERE date < <date>

SET @Rows = @@ROWCOUNT END

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sentiment Analysis - What does annotating dataset mean? I'm currently working on my final year research project, which is an application which analyzes travel reviews found online, and give out a sentiment score for particular tourist attractions as a result, by conducting aspect level sentiment analysis.
I have a newly scraped dataset from a famous travel website which does not allow to use their API for research/academic purposes. (bummer)
My supervisor said that I might need to get this dataset annotated before using it for the aforementioned purpose. I am kind of confused as to what data annotation means in this context. Could someone please explain what exactly is happening when a dataset is annotated and how it helps in getting sentiment analysis done?
I was told that I might have to get two/three human annotators and get the data annotated to make it less biased. I'm on a tight schedule and I was wondering if there are any tools that can get it done for me? If so, what will be the impact of using such tools over human annotators? I would also like suggestions for such tools that you would recommend.
I would really appreciate a detailed explanation to my questions, as I am stuck with my project progressing to the next step because of this.
Thank you in advance.

A: To a first approximation, machine learning algorithms (e.g., a sentiment analysis algorithm) is learning to perform a task that humans currently perform by collecting many examples of the human performing the task, and then imitating them. When your supervisor talks about "annotation," they're talking about collecting these examples of a human doing the sentiment annotation task: annotating a sentence for sentiment. That is, collecting pairs of sentences and their sentiment as judged by humans. Without this, there's nothing for the program to learn from, and you're stuck hoping the program can give you something from nothing -- which it never will.
That said, there are tools for collecting this sort of data, or at least helping. Amazon Mechanical Turk and other crowdsourcing platforms are good resources for this sort of data collection. You can also take a look at something like: http://www.crowdflower.com/type-sentiment-analysis.


text:
Q: Best way to mock System.Net.WebSockets ClientWebSocket class to unit test (nunit) I have used ClientWebSocket class for webSocket communication. What is the best way of mocking the class?

A: Let us assume you have the following code
class MyDependentClass {

    private AnyDependency _dependency;
    MyDependantClass(AnyDependency dependency){
        _dependency = dependency;
    }

    void DoSomethingWithDependency() {
        _dependency.MethodCall();
    }
}

In your unit test, you can either create an Instance of AnyDependency with mocked parameters.
Or, and that is what I would suggest, you encapsulate your dependency and invert it.
interface IAnyDependencyWrapper {
   void MethodCall();
}

Then create a class that implements your interface and that uses AnyDependency
class AnyDependencyWrapper : IAnyDependencyWrapper {

    private AnyDependency _dep;
    AnyDependencyWrapper(AnyDependency dep){
       _dep = dep;
    }

    void MethodCall(){
        _dep.MethodCall();
    }
}

and then inject it in your class:
class MyDependentClass {

    private AnyDependency _dependencyWrapper;
    MyDependantClass(IAnyDependencyWrapper dependencyWrapper){
        _dependencyWrapper = dependencyWrapper;
    }

    void DoSomethingWithDependency() {
        _dependencyWrapper.MethodCall();
    }
}

Now the dependency is decupled from your code and you can mock IAnyDependencyWrapper. With this solution you can also change the implementation of IAnyDependencyWrapper at any time e.g. you change the dependency or have to update with breaking changes


text:
Q: How can I extract the price from the xpath? The code I currently have is
CurrentPrice=driver.find_element_by_xpath('/html/body/div[2]/div[4]/div[2]/header/div/div[3]/div[1]/div/div/div/div[1]/div[1]').get_attribute("title")

Here is the price from the website I'm trying to extract info from-https://www.tradingview.com/symbols/LINKUSD/technicals/
Here is the thing my xpath is directed to-

23.25627

I don't get anything outputted with my code, it's just blank.

A: Try replace "get_attribute("title")" to ".text"
# Wrong
driver.find_element_by_xpath('/html/body/div[2]/div[4]/div[2]/header/div/div[3]/div[1]/div/div/div/div[1]/div[1]').get_attribute("title")

# Correct
driver.find_element_by_xpath('/html/body/div[2]/div[4]/div[2]/header/div/div[3]/div[1]/div/div/div/div[1]/div[1]').text


text:
Q: Stopping weird outline on checkbox check in table I have a table using datatables that has a checkbox in one of the th's. When I click on the checkbox, I get this:

I'm trying to remove this blue outline. Does anyone know how I would do this or what causes it?

A: You can set the style for the th element to disable outlines like so:
th{outline:none;}


text:
Q: Custom Post type date archive for custom taxonomy Hello WP StackExchange,
I picked up and it deals with Custom Post Type archives.
So we have a CPT called Resources. Under Resources we have a custom taxonomy called Resource Types. For Resource Types we have Media, Gallery, Blog, FAQs.
So each with their own permalink:
/resources/media/
/resources/blog/
etc...
You're probably wondering why have the blog posts under Resources, good question, based on the last developers notes and what marketing team was going for is they wanted the blog to have that permalink structure. Using the regular Posts type there was some conflict issues when the base was added in the Permalink settings for the Posts. 2-3 other developers have touched this and I'm hoping I can finalize it. This route isn't the best I know but it's what I'm working with :/ any help is appreciated.
What I'm trying to fix is the archives for the blog. So if we hit /resources/blog/2012/02/ we get a 404. I been looking and can't find a way to get this to work or if I can be pointed to the right direction. I tried some archive templates but nothing seemed to work for me.
Also some quick backstory, we have duplicate posts under Posts and Resources. So if you hit /2012/02 you get the feed from Posts. We are going to delete the posts under Posts so that Resources would be the only method for the blog.
EDIT:
Code for CPT and Taxonomy
// Resource
function cpt_pt_resources() {

$labels = array(
    'name'                  => _x( 'Resources', 'Post Type General Name', 'text_domain' ),
    'singular_name'         => _x( 'Resource', 'Post Type Singular Name', 'text_domain' ),
    'menu_name'             => __( 'Resources', 'text_domain' ),
    'name_admin_bar'        => __( 'Resources', 'text_domain' ),
    'archives'              => __( 'Resource Archives', 'text_domain' ),
    'attributes'            => __( 'Resource Attributes', 'text_domain' ),
    'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
    'all_items'             => __( 'All Items', 'text_domain' ),
    'add_new_item'          => __( 'Add New Resource', 'text_domain' ),
    'add_new'               => __( 'Add Resource', 'text_domain' ),
    'new_item'              => __( 'New Item', 'text_domain' ),
    'edit_item'             => __( 'Edit Item', 'text_domain' ),
    'update_item'           => __( 'Update Item', 'text_domain' ),
    'view_item'             => __( 'View Item', 'text_domain' ),
    'view_items'            => __( 'View Items', 'text_domain' ),
    'search_items'          => __( 'Search Item', 'text_domain' ),
    'not_found'             => __( 'Not found', 'text_domain' ),
    'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
    'featured_image'        => __( 'Featured Image', 'text_domain' ),
    'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
    'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
    'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
    'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
    'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
    'items_list'            => __( 'Items list', 'text_domain' ),
    'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
    'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
);
$args = array(
    'label'                 => __( 'Resource', 'text_domain' ),
    'description'           => __( 'Resources', 'text_domain' ),
    'labels'                => $labels,
    'supports'              => array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'page-attributes', 'post-formats', 'custom-fields', ),
    'taxonomies'            => array( 'category', 'post_tag', ),
    'hierarchical'          => true,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_position'         => 5,
    'menu_icon'             => 'dashicons-index-card',
    'show_in_admin_bar'     => false,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => true,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'page',
    'rewrite'               => array( 'slug' => 'resources/%resource-type%', 'with_front' => false ),
);
register_post_type( 'resource', $args );

}
add_action( 'init', 'cpt_pt_resources', 0 );

// Resource URL rewrite
function res_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) ){
    $terms = wp_get_object_terms( $post->ID, 'resource-type' );
    if( $terms ){
        return str_replace( '%resource-type%' , $terms[0]->slug , $post_link );
    }
}
return $post_link;
}
add_filter( 'post_type_link', 'res_post_link', 1, 3 );

// Custom taxonomy Resource Type
function cpt_pt_resource_tax() {

$labels = array(
    'name'              => _x( 'Resource Types', 'taxonomy general name', 'textdomain' ),
    'singular_name'     => _x( 'Resource Type', 'taxonomy singular name', 'textdomain' ),
    'menu_name'         => __( 'Resource Types', 'textdomain' ),
    'search_items'      => __( 'Search Resource Types', 'textdomain' ),
    'all_items'         => __( 'All Resource Types', 'textdomain' ),
    'parent_item'       => __( 'Parent Resource Type', 'textdomain' ),
    'parent_item_colon' => __( 'Parent Resource Type:', 'textdomain' ),
    'edit_item'         => __( 'Edit Resource Type', 'textdomain' ),
    'update_item'       => __( 'Update Resource Type', 'textdomain' ),
    'add_new_item'      => __( 'Add New Resource Type', 'textdomain' ),
    'new_item_name'     => __( 'New Resource Type Name', 'textdomain' ),
);

$args = array(
    'hierarchical'      => true,
    'labels'            => $labels,
    'show_ui'           => true,
    'show_admin_column' => true,
    'query_var'         => true,
    'menu_position'     => 0,
    'rewrite'           => array( 'slug' => 'resources', 'with_front' => false ),
);
register_taxonomy( 'resource-type', array( 'resource' ),  $args );

}
add_action( 'init', 'cpt_pt_resource_tax', 0 );

// Custom URL for FAQs
function faq_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_tax( 'resource-type', 'faq') ){
    $terms = wp_get_object_terms( $post->ID, 'faqs' );
    if( $terms ){
        return str_replace( '%resource-type%' , $terms[0]->slug , $post_link );
    }
}
    return $post_link;
}
add_filter( 'post_type_link', 'faq_post_link', 1, 3 );

A: A couple of things about your current code-

*

*You may find that pagination on your taxonomy term pages currently does not work. The order you register the taxonomy and post type matters here, as the rules are very similar and you need them to cascade a specific way. You can reverse the order they happen in by giving a later priority to the post type registration add_action( 'init', 'cpt_pt_resources', 1 );

*The faq_post_link function hooked to post_type_link at the end is redundant. The res_post_link function hooked to the same filter already does the same thing.
Enabling date archives is pretty straightforward. You need to add a set of rewrite rules, which are URL patterns in the form of regular expressions, plus the corresponding query vars the captured values get placed into.
function cpt_pt_resource_tax_date_archives() {

    add_rewrite_rule(
        'resources/([^/]+)/([0-9]{4})/?$',
        'index.php?resource-type=$matches[1]&year=$matches[2]',
        'top'
    );
    add_rewrite_rule(
        'resources/([^/]+)/([0-9]{4})/page/([0-9]{1,})/?$',
        'index.php?resource-type=$matches[1]&year=$matches[2]&paged=$matches[3]',
        'top'
    );

    add_rewrite_rule(
        'resources/([^/]+)/([0-9]{4})/([0-9]{2})/?$',
        'index.php?resource-type=$matches[1]&year=$matches[2]&monthnum=$matches[3]',
        'top'
    );
    add_rewrite_rule(
        'resources/([^/]+)/([0-9]{4})/([0-9]{2})/page/([0-9]{1,})/?$',
        'index.php?resource-type=$matches[1]&year=$matches[2]&monthnum=$matches[3]&paged=$matches[4]',
        'top'
    );

}
add_action( 'init', 'cpt_pt_resource_tax_date_archives', 2 );

There are two sets of rules here- one for just year archives, plus pagination, and another for year/month archives, plus pagination.
Don't forget to flush rewrite rules after any changes. You can do this quickly by visiting the Settings > Permalinks admin page, which invokes the flush_rewrite_rules function.
If you want to add/change rules, or just get a better understanding of how they work, I recommend the
Monkeyman Rewrite Analyzer plugin.


text:
Q: Is intergration and an integral the same thing? And if not whats the difference? I think the integral is the area under the curve and integration is an anti derivative (what ever that means)

A: The words "An integral" represent a noun -- defined as the area under a curve (or, when you get more advanced, some other sort of limit of sums).
The word "integrate" is a verb; the act of computing an integral.
The word "integration" is a noun refering to the general concept of doing the (verb) integrrate.  As in
"Integration is not hard, you just take the anti-derivative of a function and you obtain the integral of that function"
or
"Not hard?  I can't even integrate $e^{x^4}$ because I can't find the anti-derivative"

A: One is the object: the integral, the other is the act of "finding" the integral.
" the mathematician wanted to find the integral of $f$, so the mathematician used integration"

A: Integration is the process of computing the integral of a function. The function being integrated is known as the integrand.
The integral is also known (less commonly) as the anti-derivative, because integration is the inverse of differentiation (loosely speaking).
Integrals are indefinite when there are no bounds imposed, and the result is a family of functions (dependent on the variable of integration) and separated only by an arbitrary additive constant. When an upper and lower bound are specified (as numbers), it is called a definite integral, and the final answer (the integral) is no longer a function dependent on the variable of integration, but just a single number. This is the sort of integral used to calculate the area under a curve between two bounds.
Technically, there are different "flavours" of integral. The most common type is the Riemann Integral, which is the limit of a Riemann Sum. But there are other sorts like the Lebesgue Integral, which is defined differently and not commonly used in elementary courses.

A: Sometimes "integral" is used to refer to integers.  In that case you would not use "integration" when talking about it.


text:
Q: JQuery clicking to show image, then making it disappear after delay? I'm creating a simple game of Simon, and I want the easiest way to code where if one of the four buttons is clicked, it changes the image for a second or so (on mode), plays a sound, then goes back to its original color. Right now I've searched, but everything I've seen has to do with divs, or other types of questions.
As of now the button changes to the on button image, plays the sound, but when I try any function to hide or fadeOut or anything of that sort, it goes to a strange greyish color, but does not disappear. I've tried to use attr() to set the image back to what it originally was with a delay in between, but that doesn't work, either. The code is long, but I'll post what's relevant...
    <audio src="sounds/1.mp3" id ="snd1"></audio>
    <audio src="sounds/2.mp3" id ="snd2"></audio>
    <audio src="sounds/3.mp3" id ="snd3"></audio>
    <audio src="sounds/4.mp3" id ="snd4"></audio>

and from my js file...
    $("#c1").on("click", function() {
            $("#c1i").attr("src", "imgs/1.png").hide("slow");
            $("#snd1")[0].play();
});

edit: I will also add that clicking the button as of now only lets me click it once to perform the function. After one click, it just greys out. No color change, no sound played. Mystifying to me...

A: try this :
$("#c1").on("click", function() {
       // change the image , and make sure this image path exists ...
      $("#c1i").attr("src", "imgs/1.png");
      // make it disappear and play the sound after 1 second
      setTimeout(function(){
        $("#c1i").hide();
        $("#snd1")[0].play();
      },1000);

});


text:
Q: Apache Spark RDD persistence only when exception is thrown I was considering caching one of my RDDs that took longer to process only if an exception was thrown and the job was killed. If I run the job again, I'd like it to continue where it failed, avoiding the processing of that RDD again.
Does it make sense? Would the same job start a different Spark context not being able to locate that cached RDD?
Thanks!

A: Cached data is lost when a Spark program exits. Checkpoint may be an option, though, as it will save the RDD to disk. Check here for further explanation.


text:
Q: Tower of Hanoi WITHOUT using a buffer stack Tower of Hanoi problem :
You have 3 towers and N disks of
different sizes which can slide onto any tower.
The puzzle starts with disks sorted
in ascending order of size from top to bottom (i.e., each disk sits on top of an even
larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto the next rod.
(3) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first tower to the last using Stacks.

Question : Why do we need a second/buffer/intermediate stack ?
I have solved this without using a buffer stack.
I used the implicit stack created by method(recursion).
See code :
public void play(Stack<Integer> aSourceStack,Stack<Integer> aTargetStack){

    if(aSourceStack.isEmpty()){
        return;
    }

    Integer temp = aSourceStack.pop();

    play(aSourceStack,aTargetStack);

    aTargetStack.push(temp);
}

Also am I violating the second constraint : (2) A disk is slid off the top of one tower onto the next rod.
Does this mean that i can't store the plate in a temporary variable ? It has to go on stack only ?
If yes, then i think i have my answer and i can close the question.
Please confirm.

A: Let me search that for you ... this is a classic puzzle.
You are supposed to implement the solution using one instance of the Stack class for each tower.  There are three towers, so you have three Stack instances.  Yes, when you pop a disk off the top of one tower, you must immediately push it onto the next tower.  An appropriate statement might be
aTargetStack.push(aSourceStack.pop())

The code you wrote does not solve the problem; it tosses each disk in turn into the air, and then shoves them onto the target stack in the desired order: N disks in N moves.  A correct, ideal solution will take 2^N-1 moves.


text:
Q: blu-ray archiving in vmware ESXi 4 I need some advice about using blu-ray writer for archiving data on vmware ESXi 4. At office we have IBM System x3400 Tower server with ESXi 4 hipervisor and OpenSuse and CentOS GNU/Linux system as guests. Will blu-ray writer work in this setup, and if it will is there any particular model you can suggest.
Best regards
IBM System x3400 Tower server specification:
1x Intel Quad-Core Xeon E5410 2.33GHz/ 12MB/ 1333MHz (2x CPU max)
Intel 5000P chipset, 2x 1GB PC2-5300 DDR2 667MHz SDRAM ECC Chipkill (32GB max)
2x4GB (2x2GB) PC2-5300 CL5 ECC DDR2 FBDIMM (x3400, x3550, x3650)
SAS/SATA Hot-Swap Open Bay (0xHDD std, 4xHDD max, 8xHDD optional)
ServeRAID 8K dual channel SAS/SATA controller (RAID 0,1,1E,10,5,6, 256MB, Battery Backup)
Graphics ATI® RN50(ES1000) 16MB DDR, CD-RW/DVD Combo
no FDD
GigaEthernet, Tower with Power Supply 835W (opt Redudant)
Slot 1: half-length, PCI-Express x8(x4 electrical)
Slot 2: full, PCI-Express x8
Slot 3: full, PCI-Express x8
Slot 4: full, 64-bit 133MHz 3.3v PCI-X
Slot 5: full, 64-bit 133MHz 3.3v PCI-X ,
Slot 6: half-length, 32-bit 33MHz 5.0v PCI
ports: 4x USB (Vers 2.0), 2x PS/2, parallel, 2x serial (9-pin), VGA, RJ-45 (ethernet ),   RJ-45 (sys mgm)
HDD 4 x TB 7200rpm / Serial ATA II 3.0Gb/s / 16MB, RoHS

A: What software do you envisage backing this up with, ESXi can't do it on it's own and you don't say whether you have vCenter 4 running or whether you're licensed for VMWare Data Recovery. If you intend to backup via a VM and PCI pass-through then you're going to have be very specific with your choice of motherboard, drive controller and drive itself - have you looked into this? Are you storing you VMs locally or on a SAN/NAS?


text:
Q: i need help multiplying two strings The following error is encountered when running the code below.
Traceback (most recent call last):
  File "C:\Users\ladyj\AppData\Local\Programs\Python\Python37-32\bv.py", line 5, in <module>
    earnings=str(base_salary*commission_rate)
TypeError: can't multiply sequence by non-int of type 'str'

base_salary = input(str('what is your base salary'))
commission_rate = input(str('what is your commission rate'))

earnings=str(base_salary*commission_rate)
print(earnings)

A: input will always return a string, but if you want to do calculations with it, then you will need to convert it to a number. The float() function will do this for you. If the value that was input was not a number you will get a ValueError. If you want to check for this you can use a try/except construct to catch the error.
Here is some working code that uses floats to accomplish what you are trying to do.
base_salary = float(input('What is your base salary? '))
commission_rate = float(input('What is your commission rate? '))
earnings = base_salary * commission_rate
print(f'{earnings:.2f}')

By the way, I do a lot of work with commission calculations and I'm not sure I would describe commission rate the way you do. Usually we talk about splits, like 60/40 where 60% is base and 40% is commission, in which case the calculation of total earnings would be base/.6, but your interpretation may be different. When I speak of commission rate, it is usually the percentage of total sales that is paid in commission.


text:
Q: Unresolved External errors linking to SFML (SFML 2.2, Visual Studio Community 2013) Attempting to link a new C++ project with SFML, I did the following:

*

*Created an empty project.

*C/C++ >> General: Additional Include Directories: added SFML include directory and inheriting from project defaults.

*Linker >> Additional Library Directories: added SFML lib directory and inheriting from project defaults.

*Added additional dependencies: winmm.lib, openal32.lib, sndfile.lib, opengl32.lib, gdi32.lib, glew.lib, freetype.lib, jpeg.lib, sfml-system-s-d.lib, sfml-audio-s-d.lib, sfml-window-s-d.lib, sfml-graphics-s-d.lib, plus inheriting from project defaults.

*All other project settings are default.

I copied the sample main() from http://www.sfml-dev.org/tutorials/2.0/start-vc.php .
When I attempt to build the program, I get 15 LNK2019 Unresolved External errors:
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sf::String::String(char const *,class std::locale const &)" (__imp_??0String@sf@@QAE@PBDABVlocale@std@@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sf::String::~String(void)" (__imp_??1String@sf@@QAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sf::VideoMode::VideoMode(unsigned int,unsigned int,unsigned int)" (__imp_??0VideoMode@sf@@QAE@III@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall sf::Window::close(void)" (__imp_?close@Window@sf@@QAEXXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: bool __thiscall sf::Window::isOpen(void)const " (__imp_?isOpen@Window@sf@@QBE_NXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: bool __thiscall sf::Window::pollEvent(class sf::Event &)" (__imp_?pollEvent@Window@sf@@QAE_NAAVEvent@2@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall sf::Window::display(void)" (__imp_?display@Window@sf@@QAEXXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sf::Color::Color(unsigned char,unsigned char,unsigned char,unsigned char)" (__imp_??0Color@sf@@QAE@EEEE@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall sf::RenderTarget::clear(class sf::Color const &)" (__imp_?clear@RenderTarget@sf@@QAEXABVColor@2@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall sf::RenderTarget::draw(class sf::Drawable const &,class sf::RenderStates const &)" (__imp_?draw@RenderTarget@sf@@QAEXABVDrawable@2@ABVRenderStates@2@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sf::RenderWindow::RenderWindow(class sf::VideoMode,class sf::String const &,unsigned int,struct sf::ContextSettings const &)" (__imp_??0RenderWindow@sf@@QAE@VVideoMode@1@ABVString@1@IABUContextSettings@1@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: virtual __thiscall sf::RenderWindow::~RenderWindow(void)" (__imp_??1RenderWindow@sf@@UAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall sf::Shape::setFillColor(class sf::Color const &)" (__imp_?setFillColor@Shape@sf@@QAEXABVColor@2@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sf::CircleShape::CircleShape(float,unsigned int)" (__imp_??0CircleShape@sf@@QAE@MI@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: virtual __thiscall sf::CircleShape::~CircleShape(void)" (__imp_??1CircleShape@sf@@UAE@XZ) referenced in function _main

2 LNK2001 Unresolved Externals:
1>main.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: static class sf::Color const sf::Color::Green" (__imp_?Green@Color@sf@@2V12@B)
1>main.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: static class sf::RenderStates const sf::RenderStates::Default" (__imp_?Default@RenderStates@sf@@2V12@B)

and an LNK1120:
1>C:\Users\<user name>\Documents\DLLTest\Debug\DLLTest.exe : fatal error LNK1120: 17 unresolved externals

No program is built.
I feel like I'm missing something obvious, and it's more likely to be about linking to DLLs than about SFML. What am I doing wrong?
Resolution: This was SFML-specific: I was linking to the static versions of the SFML DLLs (the ones with -s in the name). I switched to the dynamic versions (sfml-system-d.lib, for example), and the project built, although to run it I'll need to have the SFML DLLs in the same directory as the executable.

A: You are linking the Static-Debug Version of the SFML-Libs. Do you really want to build a static version? If so you have to define SFML_STATIC. Otherwise remove the -s option in the Library-names.

A: The dllspec(dllimport) I believe means that you are attempting to dynamically link.  SFML_STATIC needs to be defined, or put the dlls in your working directory and change names in additional libraries.


text:
Q: List of ImageJ color names In ImageJ ROI manager one can define a color by name (green, yellow, magneta, etc). I have been struggling to find a list of allowed color names. Does anybody know where to find a comprehensive list of color names used by ImageJ?

A: In the ROI manager documentation of the ImageJ User Guide, it is written:

The nine default selection colors (black, blue, cyan, green, magenta, orange, red, white, yellow) can be typed textually.

The same can be found in the source code: the RoiProperties dialog uses the ij.plugin.Colors class to set the stroke color.


text:
Q: Creating a dup function inside a module - clashes with dup property of array If I create a dup function inside my D program, I can no longer use the dup property of an array. This code works
import std.stdio;

void main() {
  double[] v = [0.1, 0.2, 0.3];
  writeln(v.dup);
}

But this code returns "clash.d(9): Error: function clash.dup (double x) is not callable using argument types (double[])"
import std.stdio;

double dup(double x) {
  return x;
}

void main() {
  double[] v = [0.1, 0.2, 0.3];
  writeln(v.dup);
}

How can I define a dup function in my program and not lose the dup property of arrays?

A: alias it into the local overload set:
alias dup = object.dup;

right below your own dup function definition.


text:
Q: Do I need to use a comma if a subject follows "and" in a sentence?
Mike went to the shop, and he bought vegetables.

or

Mike went to the shop and bought vegetables.

My understanding is that when the subject is there after 'and', the comma is required.

My understanding is that when there is no subject after 'and', the comma is not required.
Am I correct on the understanding?

A: The general rule we can apply here is that the first sentence calls for a comma because it is a compound sentence consisting of two independent clauses joined by a coordinating conjunction (even though the subjects "Mike" and "he" are complementary, referring to the same person):

1 Mike went to the shop.
  2 He bought vegetables.

However, the comma is not always required. In shorter sentences, writers often leave out the comma:

I walked and Mike ran.
  I called but no one answered.

The second sentence (Mike went to the shop and bought vegetables.) is a simple sentence (one independent clause) with a compound predicate consisting of two verbs ("went" and "bought"), and we should not include a comma.
Note that if the predicate contains three or more verbs, we can apply the "list rule" for commas and separate them:

Mike went to the store, bought groceries, and returned home.

A: This has come apropos! I was just teaching my kid (she had an exam of English) from her textbook. In the textbook (of course Indian), there was no comma. If the subject is same, we don't need to repeat the subject. Said that...

Mike went to the shop and brought vegetables -plain and clear.

However, it's good to learn about the Oxford comma if you are including more than two things.

But if at all I want to dig in further, I can think of a context where I'll have to emphasize on the subject because he did something else* than what he was asked!
Say, you send Mike to drop your kid, see a doctor (for some reason), meet a plumber (for some household work), and buy eggs from the shop. Now, he is a forgetful person. He went to the shop but then he bought vegetables. There, I'd emphasize it on the subject by putting it again in the sentence.

And guess what...Mike went to the shop, and he brought vegetables!

I can stress on "...and he...." to prove my point that he actually did go to the shop but he bought vegetables.


text:
Q: Normal sections Let $S$ be a surface and let $p \in S$ with normal $n_{p}$. Let $q \in S$ nearby $p$, say within the injectivity radius of the exponential map at $p$. Consider the plane $\Pi = \operatorname{span}\{n_p, \vec{pq}\}$. The intersection of $\Pi$ with $S$ gives a curve $\gamma$ from $p$ to $q$. Is $\gamma$ a geodesic? Equivalently is $\Pi \cap S$ a normal section?

A: This is far too good to be true in general - you're trying to use only $p$-local ($n_p$) and averaged ($\vec{pq}$) data to determine the global behaviour of a geodesic, which is determined uniquely by the tangent to $\Pi \cap S$ at $p$ and depends highly on the geometry of $S$ between there and $q$. I expect this is only true when you have some kind of symmetry of $S$ about $\vec{pq}$, and only true for all admissible $q$ when $S$ is a sphere or plane. Here's an explicit counterexample:
Let $S$ be the cylinder $x^2 + y^2 = 1$, $p=(1,0,0)$ and $q=(0,1,1)$. Then $n_p =e_x$ and $\vec{pq}=(-1,1,1)$, so $\Pi = \left\{(1+s-t, t, t) \mid s,t \in \Bbb R\right\}$. The intersection of this with $S$ is the subset where $$(1+s-t)^2 + t^2 = 1,$$ which has local solution (between $p$ and $q$)
$$ S \cap \Pi \supset \left\{ (\sqrt{1-t^2}, t, t) \mid t \in \Bbb [0,1] \right\}.$$
Plotting this curve on the cylinder shows it's clearly curved in the surface, particularly near $q$:

Indeed, changing to cylindrical coordinates $(\theta,z)$ via $x= \cos \theta, y = \sin \theta$ we see that $$S \cap \Pi = \left\{ (\theta, \sin \theta)\mid \theta \in \Bbb R\right\}.$$
Since the metric in these coordinates is $d\theta^2 + dz^2$, the geodesics are "straight lines" $a \theta + b z = c$, and $S \cap \Pi$ is clearly not one of these. You can replace $q$ with closer points $(\cos \theta_0, \sin \theta_0, \sin \theta_0)$ to get counterexamples with $d(p,q)$ arbitrarily small.


text:
Q: How to get HDMI video out to work with ATI Radeon HD mobility? I have an ATI Radeon HD mobility 5400 series, and I believe I am running the open source driver. Currently, VGA out works fine for running an external monitor. HDMI out does not work at all. xrandr does not even list an HDMI output.
I really appreciate the help. Thank you.


text:
Q: Zend_Search_Lucene massive - similar to ZF-5545 issue EDIT:
Solved with a hack for now. Added at line 473:
if (isset($this->_termsFreqs[$termId][$docId])) {

}

This happens only when I'm searching for multiple words, e.g.:
+word1 +word2 + word3

I get this massive error:
Notice: Undefined offset: 2 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 2 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 4 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 4 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 6 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 6 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 1 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 1 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 9 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Notice: Undefined offset: 9 in C:\wamp\www\project\library\Zend\Search\Lucene\Search\Query\MultiTerm.php on line 473

Funny thing is that the result set that is returned is correct, so in production I could just turn off the error reporting and it would work like a charm but I don't want to do that.
Similar issue is documented here: http://framework.zend.com/issues/browse/ZF-5545
And apparently there is no solution.
I have also tried using UTF-8 compatible text analyzer (even though I have only Latin 1 characters in the index):
Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8());

A: Undefined offset just means that it is trying to get an array value that doesn't exist. The solution is just to check array_key_exists first to make sure the key is set. From the source for the file mentioned in the error, you'd need to add this if condition near line 473 (the second and sixth lines are the addition):
foreach ($this->_terms as $termId => $term) {
     if (array_key_exists($termId,$this->_weights)) {
         $score += $reader->getSimilarity()->tf($this->_termsFreqs[$termId][$docId]) *
                   $this->_weights[$termId]->getValue() *
                   $reader->norm($docId, $term->field);
     }
}

Presently, because $this->_weights[$termId]->getValue() is being multiplied by other values and then added to $score, the result of the multiplication is 0 and nothing gets added, thus the result comes out correctly. Adding the if will not change this as nothing will be added either way.

A: You have to put this condition to surpress the warning:
if (array_key_exists($termId, $this->_termsFreqs) && array_key_exists($docId, $this->_termsFreqs[$termId])) { ... }
But the question remains, if this is helpful. There might be a logical error causing this undefined offset.


text:
Q: Hash a column in CSV and output in Base64 Still getting my feet wet with Python, but my goal is to read a CSV file and hash a specific column using SHA256 then output in Base64.
Here is an example of the conversion that needs to take place

This calculator can be found at https://www.liavaag.org/English/SHA-Generator/
Here is the code I have currently
import hashlib
import csv
import base64

with open('File1.csv') as csvfile:

    with open('File2.csv', 'w') as newfile:

        reader = csv.DictReader(csvfile)

        for i, r in enumerate(reader):
            #  writing csv headers
            if i == 0:
                newfile.write(','.join(r) + '\n')

            # hashing the 'CardNumber' column
            r['consumer_id'] = base64.b64encode(hashlib.sha256(r['consumer_id']).encode('utf-8')).digest()

            # writing the new row to the file with hashed 'CardNumber'
            newfile.write(','.join(r.values()) + '\n')

The error I receive is
r['consumer_id'] = base64.b64encode(hashlib.sha256(r['consumer_id']).encode('utf-8')).digest()
TypeError: Strings must be encoded before hashing

A: You are on the right track, just need to take it a step at a time before doing it all at once to see how it pieces together:
import hashlib
import base64

text = "1234567890"
encoded = text.encode('utf-8')
encoded = hashlib.sha256(encoded).digest()
encoded = base64.b64encode(encoded)
print(text, str(encoded, encoding="utf-8"))

That should give you:
1234567890 x3Xnt1ft5jDNCqERO9ECZhqziCnKUqZCKreChi8mhkY=

As a "one-liner":
r['consumer_id'] = str(base64.b64encode(hashlib.sha256(r['consumer_id'].encode('utf-8')).digest()), encoding="utf-8")

As you can see, your current use is close, but just has some parentheses opportunities to fix.
If you wanted to use this in a loop, say when iterating over a list of words or the rows of a csv you might do this:
import hashlib
import base64

def encode_text(text):
    encoded = text.encode('utf-8')
    encoded = hashlib.sha256(encoded).digest()
    encoded = base64.b64encode(encoded)
    return str(encoded, encoding="utf-8")

words = "1234567890 Hello World".split()
for word in words:
    print(word, encode_text(word))

Giving you:
234567890 x3Xnt1ft5jDNCqERO9ECZhqziCnKUqZCKreChi8mhkY=
Hello GF+NsyJx/iX1Yab8k4suJkMG7DBO2lGAB9F2SCY4GWk=
World eK5kfcVUTSJxMKBoKlHjC8d3f7ttio8XAHRjo+zR1SQ=

Assuming the rest of your code works as you like, then:
import hashlib
import csv
import base64

def encode_text(text):
    encoded = text.encode('utf-8')
    encoded = hashlib.sha256(encoded).digest()
    encoded = base64.b64encode(encoded)
    return str(encoded, encoding="utf-8")

with open('File1.csv') as csvfile:

    with open('File2.csv', 'w') as newfile:

        reader = csv.DictReader(csvfile)

        for i, r in enumerate(reader):
            #  writing csv headers
            if i == 0:
                newfile.write(','.join(r) + '\n')

            # hashing the 'CardNumber' column
            r['consumer_id'] = encode_text(r['consumer_id'])

            # writing the new row to the file with hashed 'CardNumber'
            newfile.write(','.join(r.values()) + '\n')

A: In addition to JonSG's answer about getting the hashing/encoding correct, I'd like to comment on how you're reading and writing the CSV files.
It took me a minute to understand how you're dealing with the header vs the body of the CSV here:
with open("File1.csv") as csvfile:
    with open("File2.csv", "w") as newfile:
        reader = csv.DictReader(csvfile)
        for i, r in enumerate(reader):
            print(i, r)
            if i == 0:
                newfile.write(",".join(r) + "\n")  # writing csv headers
            newfile.write(",".join(r.values()) + "\n")

At first, I didn't realize that calling join() on a dict would just give back the keys; then you move on to join the values.  That's clever!
I think it'd be clearer, and easier, to use the complementary DictWriter.
For clarity, I'm going to separate the reading, processing, and writing:
with open("File1.csv", newline="") as f_in:
    reader = csv.DictReader(f_in, skipinitialspace=True)
    rows = list(reader)

for row in rows:
    row["ID"] = encode_text(row["ID"])
    print(row)

with open("File2.csv", "w", newline="") as f_out:
    writer = csv.DictWriter(f_out, fieldnames=rows[0])
    writer.writeheader()
    writer.writerows(rows)

In your case, you'll create your writer and need to give it the fieldnames.  I just passed in the first row and the DictWriter() constructor used the keys from that dict to establish the header values.  You need to explicitly call the writeheader() method, then you can write your (processed) rows.
I started with this File1.csv:
ID, Phone, Email
1234680000000000, 123-456-7890, johnsmith@test.com

and ended up with this File2.csv:
ID,Phone,Email
tO2Knao73NzQP/rnBR5t8Hsm/XIQVnsrPKQlsXmpkb8=,123-456-7890,johnsmith@test.com

That organization means all your rows are read into memory first.  You mentioned having "thousands of entries", but for those 3 fields of data that'll only be a few hundred KB of RAM, maybe a MB of RAM.
If you do want to "stream" the data through, you'll want something like:
reader = csv.DictReader(f_in, skipinitialspace=True)
writer = csv.DictWriter(f_out, fieldnames=reader.fieldnames)

writer.writeheader()

for row in reader:
    row["ID"] = encode_text(row["ID"])
    writer.writerow(row)

In this example, I passed reader.fieldnames to the fieldnames= param of the DictWriter constructor.
For dealing with multiple files, I'll just open and close them myself, because the multiple with open(...) as x can look cluttered to me:
f_in = open("File1.csv", newline="")
f_out = open("File2.csv", "w", newline="")

...

f_in.close()
f_out.close()

I don't see any real benefit to the context managers for these simple utility scripts: if the program fails it will automatically close the files.
But the conventional wisdom is to use the with open(...) as x context managers, like you were.  You could do nested, like you were, separate them with a comma, or if you have Python 3.10+ use grouping parenthesis for a cleaner look (also in that Q/A).


text:
Q: Iteration algorithm in python I want to find and print that how many num of bob in a string with the following program but it isn't working. Can anyone tell what is wrong with it?
s='bob123 bob bob 3434'
num=0
a=0
b=3
for char in s:
    if s[a:b]=='bob':
        num+=1
        a+=1
        b+=2
print(num)

A: s='bob123 bob bob 3434'
print(s.count("bob"))

You can count how many bob occurences are they in your string.
repl.it working

A: what is not working is that your indentation is off: you need to increase a and b also if the string is not found; and both need to be increased by 1 only (you increase b by 2):
for char in s:
    if s[a:b]=='bob':
        num+=1
    a+=1
    b+=1

a slightly more pythonic way to do this might be:
num = 0
for i in range(len(s)+1-3):
    if s[i:i+3] == 'bob':
        num+=1

the count method of string would be the much better version for this:
s.count('bob')


text:
Q: Generate dynamic expressions in ng-repeat I have a ngRepeat element that has a delete button that triggers a confirmation message. I'm trying to make the confirmation message show with a dynamic expression like so:

    Are you sure you want to delete your review?

I'm not sure if this is the right way to create dynamic expressions, but this is the only way I can get the expression to at least generate in html.
But I am getting this error for all the repeated items (with different item ids in each error):
Error: [$parse:syntax] Syntax Error: Token 'cb0a2a73ede6e3a9d7a58_delete' is an unexpected token at column 4 of the expression [543cb0a2a73ede6e3a9d7a58_delete] starting at [cb0a2a73ede6e3a9d7a58_delete].

^ the outputted item._id for that item is 543cb0a2a73ede6e3a9d7a58 for example.

A: Angular is expecting an expression there that returns true or false for ng-show. So just rendering a String won't really help. You could either define a controller function that resolves to true or false or just write the expression inline, like ng-show="item.id === 2".
But it seems that you want a confirmation dialog before deleting, in that case you should write a custom directive that intercepts the click action before executing it (unfortunately there is no such thing as ng-confirm in Angular built-in).
Here is an example of such a directive: https://gist.github.com/asafge/7430497

A: If you simply want to toggle a message to the user, you could simply make your span dependant on a scope variable that gets toggled, like so:
item
Are you sure you want to delete your review?

JSFiddle here.
However, you probably want to wrap it all up into a directive like @frank blizzard mentioned.

A: try this one :)
AH,  if item._id starts with a number it will get a error
Variable names must begin with a letter
link
so ng-show bound to a variable in the scope and it is dynamically creating. a_delete,b_delete will work fine but if it generate like 1_delete,2_delete it will result a error because those are starts with a number.
In your case item._id starts with number like 543cb0a2a73ede6e3a9d7a58 as you mentioned in you question. so ng-show ends with something like ng-show="543cb0a2a73ede6e3a9d7a58_delete". That should get a error because of violation of naming-conventions.


text:
Q: restore disk backup by writing only non-zero blocks Assuming you have a disk backup in raw format sda.img and /dev/sda is initially filled with zeroes, how to skip zeroes while restoring the backup? An analog of dd should detect zero block in input stream and perform an appropriate seek on output device.
Note
I tried cp option --sparse=always, but it looks ineffective, if destination is a block device:
[root@vmarch ~]# truncate sda.img -s1G
[root@vmarch ~]# cat sda.img | cp --sparse=always /dev/stdin sdb.img
[root@vmarch ~]# du -h sda.img sdb.img
0       sda.img
0       sdb.img
[root@vmarch ~]# ls -lh sda.img sdb.img
-rw-r--r-- 1 root root 1.0G Jul 31 09:17 sda.img
-rw------- 1 root root 1.0G Jul 31 09:17 sdb.img
[root@vmarch ~]# losetup -f sdb.img
[root@vmarch ~]# losetup
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE     DIO
/dev/loop0         0      0         0  0 /root/sdb.img   0
[root@vmarch ~]# cp --sparse=always sda.img /dev/loop0
[root@vmarch ~]# du -h sda.img sdb.img
0       sda.img
1.1G    sdb.img

A: With GNU coreutils (e.g. on non-embedded Linux), you can use cp --sparse=always to make the output file as sparse as possible:
cp --sparse=always sda.img /dev/sda

This may or may not be faster than a straight
cat sda.img >/dev/sda

cp --sparse=always has to spend more time reading and analyzing its input. The cat version spends more time writing, but unless the output device is slow, that's not going to affect the duration of the copy much, since in this scenario the reading and writing can mostly be parallelized.


text:
Q: Dependency injection in restful WS I have simple restful WS
@Path("basic")
public class ServiceRS
{

   private IServiceJAX service;

   @GET
   @Produces(MediaType.APPLICATION_JSON)
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   public String find(@FormParam("searchRequest") final String searchRequest)
   {
//...
      final List<Info> response = service.find(search);
//...
   }

}

Where IServiceJAX is @Local interface of jax-webservice.
Can I inject IServiceJAX to ServiceRS using annotation?
I don't want use JNDI lookup...

A: Sure, you can. Although I suppose there are other ways, I have successfully run a simple test project with a @Stateless @WebService, @Local implementation of an interface, injected through @EJB annotation into a @Stateless RESTFul web service annotated with @Path.
This is not properly a CDI injection as you have demanded, but it works nicely and probably fits your needs anyway.
IServiceJAX class:
public interface IServiceJAX {
    public String hello(String txt);
}

IServiceJAXImpl class:
@WebService(serviceName = "NewWebService")
@Local
@Stateless
public class IServiceJAXImpl implements IServiceJAX {

    @WebMethod(operationName = "hello")
    @Override
    public String hello(@WebParam(name = "name") String txt) {
        return "Hello " + txt + " !";
    }
}

ServiceRS class:
@Path("basic")
@Stateless
public class ServiceRS {

    @EJB private IServiceJAX wsi;

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String result(@PathParam("id") String id) {
        return wsi.hello(id);
    }
}

UPDATE
If you prefer CDI injection, you can keep the above code and simply remove @Local and @Stateless annotations from IServiceJAXImpl. You can inject an instance of this class using:
@Inject private IServiceJAX wsi;

instead of
@EJB private IServiceJAX wsi;


text:
Q: Animate change to title text in Navigation Controller I am attempting to animate the change to the title of a detail UITableViewController that is embedded in a UINavigationController.
These two Q&A on stack overflow seem most relevant...

*

*Animate nav bar title text change OP by Jordan H;

*Transition Navigation Bar Title, OP by Jacob

I've attempted a number of code variants, mostly following Ashley Mills answer and others based on his answer, but essentially I cannot seem to make the animation work!
Note writing in Swift 5 using Xcode 10.2.
I'm using a Master-Detail UITableViewController setup to manage a list and the details of the items in that list.
I'm using Large Titles...
navigationController?.navigationBar.prefersLargeTitles = true

...and a search controller...
navigationItem.searchController = <<mySearchController>>
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true

...all set in the viewDidLoad() method for the Master View Controller.
Here's what I've done.
In my project:

*

*import QuartzCore framework, per the comment by Jack Bellis "you'll need to add the QuartzCore framework via [project]>[target]>Build Phases>Link Binaries>QuartzCore.framework.";
In the Master View Controller:

*import QuartzCore;
In the Detail View Controller:

*In the viewDidAppear(_ animated: Bool) method, write the CATransition code similar to the answers to the OP noted above (which changes the Large Title, but without animation).
override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    let animationTransition = CATransition()

    animationTransition.duration = 2.0

    animationTransition.type = CATransitionType.push
    animationTransition.subtype = CATransitionSubtype.fromTop

    navigationController!.navigationBar.layer.add(animationTransition, forKey: "pushText")

    navigationItem.title = <<NEW TITLE TEXT>>
}

*In the viewDidAppear(_ animated: Bool) method, write alternatives to the CATransition code suggested in the answers to the OP noted above (which only adds a separate title into the centre of the navigation bar and does not change the Large Title).
override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    let animationTransition = CATransition()

    animationTransition.duration = 2.0

    animationTransition.type = CATransitionType.fade

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
    label.text = <<NEW TITLE TEXT>>
    navigationItem.titleView = label

    navigationItem.titleView!.layer.add(animationTransition, forKey: "fadeText")
}

*I've also tried including CAMediaTimingFunction...
    animationTransition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)

*I've also tried calling setNeedsLayout and setNeedsDisplay...
    navigationItem.titleView?.setNeedsLayout()
    navigationController?.navigationBar.setNeedsDisplay()

For clarity:

*

*the title text does change, but without animation;

*the code is written in the viewDidAppear(_ animated:) method, because I want the user to see the transition;

*the duration is long (2 seconds) for testing - I may reduce this if/when the animation is working;

*Using the Inspectors in the storyboard, I've read through all the UITableView/Controller and UINavigationController settings to see whether I may have missed something.

Any suggestions?

A: So I've worked it out.
I had to find the specific layer within the UINavigationBar's subviews that contained the title text, then animate that layer. The results are exactly what I wanted.
Here's my answer (Swift 5 iOS 12)...
override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    if (newTitle ?? "").isEmpty == false { // only proceed with a valid value for newTitle.

        // CATransition code
        let titleAnimation = CATransition()
        titleAnimation.duration = 0.5
        titleAnimation.type = CATransitionType.push
        titleAnimation.subtype = CATransitionSubtype.fromRight
        titleAnimation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)

        // this is a detail view controller, so we must grab the reference
        // to the parent view controller's navigation controller
        // then cycle through until we find the title labels.
        if let subviews = parent?.navigationController?.navigationBar.subviews {

            for navigationItem in subviews {

                for itemSubView in navigationItem.subviews {

                    if let largeLabel = itemSubView as? UILabel {

                        largeLabel.layer.add(titleAnimation, forKey: "changeTitle")
                    }
                }
            }
        }
        // finally set the title
        navigationItem.title = newTitle
   }

Note: there is no need to import QuartzCore.

...and here's the process I went through to identify what I had to change...
This SO Q&A How to set multi line Large title in navigation bar? ( New feature of iOS 11)
 helped me identify the process detailed below, so thanks in particular to the original post and the answer by @Krunal .
Using the same code to cycle through the UINavigationBar's subviews (as above), I used a print to terminal to identify the various UINavigationItems and their subviews.
        counter = 0

        if let subviews = parent?.navigationController?.navigationBar.subviews {

            for navigationItem in subviews {

                print("____\(navigationItem)")

                for itemSubView in navigationItem.subviews {

                    counter += 1

                    print("_______\(itemSubView)")
                }
            }
        }
        print("COUNTER: \(counter)")

this code yielded the following prints in terminal (for iPhone 8 Plus running iOS 12.2 in simulator)...
 ____<_UIBarBackground: 0x7f922740c000; frame = (0 -20; 414 116); userInteractionEnabled = NO; layer = <CALayer: 0x6000026ce1c0>>
 _______<UIImageView: 0x7f922740c9c0; frame = (0 116; 414 0.333333); userInteractionEnabled = NO; layer = <CALayer: 0x6000026ce7c0>>
 _______<UIVisualEffectView: 0x7f922740cbf0; frame = (0 0; 414 116); layer = <CALayer: 0x6000026ce880>>
 ____<_UINavigationBarLargeTitleView: 0x7f922740f390; frame = (0 44; 414 52); clipsToBounds = YES; layer = <CALayer: 0x6000026cd840>>
 _______<UILabel: 0x7f9227499fe0; frame = (20.1667 3.66667; 206.333 40.6667); text = 'Event Details'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6000005bf250>>
 ____<_UINavigationBarContentView: 0x7f922740d660; frame = (0 0; 414 44); clipsToBounds = YES; layer = <CALayer: 0x6000026cea00>>
 _______<_UIButtonBarStackView: 0x7f92274984a0; frame = (302 0; 100 44); layer = <CALayer: 0x60000261cc60>>
 _______<_UIButtonBarButton: 0x7f922749a5c0; frame = (0 0; 82.3333 44); layer = <CALayer: 0x60000261ee60>>
 _______<UILabel: 0x7f922749a2d0; frame = (155 11.6667; 104.333 20.3333); text = 'Event Details'; alpha = 0; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6000005bfc50>>
 ____<_UINavigationBarModernPromptView: 0x7f9227602db0; frame = (0 0; 0 50); alpha = 0; hidden = YES; layer = <CALayer: 0x6000026e4600>>
 COUNTER: 2

I've actually applied the animation twice - to the UILabel layer within _UINavigationBarLargeTitleView and the UILabel layer within _UINavigationBarContentView. This does not seem to matter however because, when the large title first appears, the label within content view (which I assume is for the "old style" title in the navigation bar when the large title is scrolled off screen) is hidden on viewDidAppear.
Incidentally, if you drop in the following two lines, you'll also have multi-line large titles:
 largeLabel.numberOfLines = 0
 largeLabel.lineBreakMode = .byWordWrapping

BUT, I've not yet figured out how to animate the increase in size of the large title frame, so a change to two or more lines is immediate and IMHO ruins the animation of the title change.
Not yet tested on device, but does seem to work OK for both iPhone and iPad sims.
If you find any bugs, let me know and I'll update my answer.


text:
Q: Junit Test cases are getting passed in Eclipse but getting exception when running with command line My JUnit test cases are running fine in Eclipse. By fine I mean either GREEN or RED.
However, It giving me following exception when I try to run the test cases using options
mvn test or mvn install.
    testPersistChannelResponseHdr(com.*.systemi.rga.dao.JPAPopulateSubsRes Test)  Time elapsed: 0.65 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:307)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException:
Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http:
//www.springframework.org/schema/jdbc]

Mu understanding is that it is unable to find spring-jdbc in the classpath.
I ran mvn dependency:tree in console to confirm my doubt. However If I run mvn:dependency:tree in eclipse, I can see spring-jdbc.
------------------------UPDATE--------------------------
My pom file has dependency on other pom file(lets say xyz.xml). All the actual dependencies are defined in xyz.xml. This spring-jdbc dependency was added recently in our local repo.

A: Check your xml configuration file for namespace declaration:
xmlns:jdbc="http://www.springframework.org/schema/jdbc"

and schemaLocation:
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd

check if the spring-jdbc-3.0 jars are correctly placed in the WEB-INF lib folder.


text:
Q: How to get given and family from a pandas column I have a pandas dataframe with a column name fullname:
    fullname
Andres Kirk Polsky
Anna Lorensen Polsman Uirch

I want to create two new columns like:
fullname                        given       rest_name
Andres Kirk Polsky              Andres      Kirk Polsky
Anna Lorensen Polsman Uirch     Anna        Lorensen Polsman Uirch

I am trying use str.aplit(' ', expand=True) but this no giving the result I want.

A: A possible solution:
(df.assign(**df['fullname'].str.split(' ', n=1, expand=True)
           .rename({0: 'given', 1: 'rest_name'}, axis=1)))

Output:
                      fullname   given               rest_name
0           Andres Kirk Polsky  Andres             Kirk Polsky
1  Anna Lorensen Polsman Uirch    Anna  Lorensen Polsman Uirch

A: A regex approach would be to use pandas.Series.str.extractall :
df[["given", "rest_name"]] = (df["fullname"].str.extractall(r"^(\S+)\s(.*)")
                                              .reset_index(drop=True))

Output :
print(df)

                      fullname   given               rest_name
0           Andres Kirk Polsky  Andres             Kirk Polsky
1  Anna Lorensen Polsman Uirch    Anna  Lorensen Polsman Uirch


text:
Q: Need help understanding the Dependency Inversion Principle in this context. Just started working and someone mentioned this concept and I still don't understand. I initially thought it meant that the view should use a class IN BETWEEN your business logic class. So that the in between class will always return a default value even if the code behind fails.
They told me this was wrong and said it has more to do with using statements like using HTMLAGILITYPACK. How are you supposed to make it so that the business logic is not dependent on something as crucial to the program as HTMLAGILITYPACK? Does that mean I should import ANOTHER .dll that can search html and write an "in case htmlagilitypack fails somehow" use this .dll instead?
I don't understand. Thank you!
(program purpose) The program goes to a website and downloads some elements using htmlagilitypack and then fills classes with the info gained from the website.

A: you're understanding is wrong. There are tens of Tutorials around the web and it's not something that you can understand just by asking it here at StackOverFlow. you should read the software design pattern and architecture books. here i mention you most important aspects of Dependency Inversion Principle in my opinion but encourage you to read the following links  for and understanding.

1- High Level Modules Should Not Depend On Low Level Modules
2- Abstraction Should Not Depend on Details, Details Should Depend on
Abstractions.

for further reading and implementation techniques simply read these tutorials., they are nice and almost adequate for beginners.
Dependency Inversion Principle (provided with C# Examples)
Inversion of Control – An Introduction with Examples in .NET
Second link of course covers more comprehensive concepts related.

A: Dependency Inversion allows you to write code that doesn't depend on external dependencies.
To your question "Does that mean I should import ANOTHER .dll that can search html" is wrong, dependency if utilized properly should allow for you to bring in another DLL without any changes to your business logic code.
Consider the following method:
The below code has a dependency on the HTML Agility Pack.  Both HtmlWeb, web.Load, and whatever web.load returns are dependencies.
public string GetDocumentInfo(string path)
{
    var web = new HtmlWeb();
    var doc = web.Load(path);
    // ... etc ... etc
}

Now consider a revision:
The below code only depends on the IDocumentReader interface (an interface that you can define).
public string GetDocumentInfo(string path, IDocumentReader reader)
{
    return reader.Read(path);
}

The reason you would want to do this is so that later you can create another class that implements IDocumentReader that reads XML, or that reads .CSV files, etc. etc.  Now your code just needs a class that implements the IDocumentReader interface and doesn't care what framework you use inside the class that implements it.


text:
Q: Pex users: what are your Impressions of Pex and Automated Exploratory Testing in general? Those of you who have used Pex, what do you think its advantages and disadvantages are of Pex as a tool?
Also, what do you think are the advantages and disadvantages of "Automated Exploratory Testing" in general, as a supplement to TDD/Unit Testing?

A: If you look for literature on writing Theories (google David Saff) - which are a more general way of writing unit tests, and use Pex as a theory explorer I've found a step change in productivity from my experience so far.
I've just wrote a blog post detailing my experiences of Pex in TDD, here: http://taumuon-jabuka.blogspot.com/2009/01/theory-driven-development-using_11.html
and as I said - I see it as TDD on steroids! It in no way replaces TDD, but enhances the activity.

A: I'm really pumped about Pex. It will provide tests for edege cases that you won't ever dream up, especially if your team is small and the person writing the methods is the same as the person writing the tests.
It will also provide contractual obligations that your methods will obey.

A: Test-first development makes you structure your code for testability.  In this respect, Pex finds clever and awkward paths thru your code, helping out beyond simple coverage metrics.
Major forte of Pex with Moles is enabling of tracking side effects when doing Brownfield development: run Pex once and save outputs, then apply code changes, and run Pex again to see what got broken.

A: Pex lets your write parameterized unit tests. In that sense, it totally fits into the TDD/unit testing flow: write the test, have Pex 'explore' it, find some failing tests, fix the code, and so forth.
The big advantage is that you can express your tests for classes of inputs, not just a couple hard-coded values. This gives more expressiveness for writing tests and also forces to think about the invariant/expectation that your code should fullfill (i.e. it's harder to write assertions).

A: I think Pex as an exploratory testing tool is really intriguing. In that regard, I see it as something I'd want to hand off to QA to use.
As a TDD tool, it needs some work, as TDD is a design activity. However, I do like the direction that Peli is heading. There's something to be said for automated assisted design. For example, just because TDD is a design tool, there's no reason I can't have an automated tool point out potential edge cases while I'm designing, right? Build quality in from the start.
Check out this post in which Peli uses Pex in a TDD style workflow. http://blog.dotnetwiki.org/TDDingABinaryHeapWithPexPart1.aspx


text:
Q: Why is this simple linked list program giving segmentation fault? I am simply trying to create a linked list of characters. Here's the code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct node{
    char data;
    struct node *next;
};

void push(struct node** head,char ndata)
{
    struct node* temp=(struct node*)malloc(sizeof(node));
    temp->data=ndata;
    temp->next=(*head);
    *head=temp;
}

void display(struct node* head)
{
    struct node* temp=head;

    while(temp)
    {
        printf("%c ",temp->data);
        temp=temp->next;
    }
}

int main()
{
    struct node* head;
    int a=1;
    push(&head,'a');
    push(&head,'b');
    push(&head,'c');
    push(&head,'b');
    push(&head,'a');

    display(head);
    getch();
    return 0;
}

I am using push() function which inserts the values at head. And then using display() method to display the values in the list. When I execute the program,
it says "program10.exe has stopped working".
I don't understand what the problem is. Can anyone help?

A: You didn't initialize head so it's not null but has a garbage value, so it doesn't stop the loop in the display function, and tries to dereference garbage there.
This:
struct node* head;

Should be:
struct node* head = NULL;


text:
Q: Alt + Up closes windows/apps instead of the default behavior I'm on a ThinkPad P15 with Ubuntu 21.10, kernel 5.13.0-39-generic. Whenever I use the shortcut Alt + Up (for instance for moving a line of code up in my IDE or when browsing up one folder) the shortcut closes the window or the application in use instead of the usual behavior I'm used to on other machines. This is regardless of what application I'm using. The strange thing is that Alt + Down works just as expected.

*

*Why does this happen?

*How do I set the shortcut to behave as expected instead?

A: Apparently, the keyboard layout was set differently in the BIOS config as compared to what I had on Ubuntu. Setting it correctly in BIOS solved the problem.


text:
Q: CustomRenderer to dynamically change border color I have an Entry, which I want to add a red border around when a button is pressed if the entry is empty. Therefore I need to be able to change the color dynamically. (standard validator)
xaml:
<local:BorderChange Placeholder="Example Entry" BorderColor="#ff4444"></local:BorderChange>

PCL Control:
namespace Project
{
    public class BorderChange : Entry
    {
        public string BorderColor
        {
            get;
            set;
        }
    }
}

iOS Customrenderer:
[assembly: ExportRenderer(typeof(BorderChange), typeof(BorderColorChange))]
namespace Project.iOS
{
    public class BorderColorChange : EntryRenderer
    {
    //init color

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if(Control != null)
            {
                Control.Layer.BorderColor = UIColor.Blue; //This is where i want to add my color
            }
        }
    }
}

*

*How do I pass my property to the CustomRenderer, so that I can change the BorderColor parameter dynamically?

A: A better approach for such needs is to use Effects.
Here is a well-described example of how to create an effect with parameters as attached properties. You'll be able to bind a property from your view model (Let's say IsValid directly to the attached property of the effect).


text:
Q: Routing is not work with react-router-redux actions When use the Link, router works as expected, though i get a warning [history] pushState is deprecated; use push instead.
Using routeActions from react-router-redux does't work, url was change (http://localhost:3002/addCity), but view still the same (Home) or show error if i go to page by url for example: localhost:3002/addCity.
git: https://github.com/kirsanv43/Weather.git
reducers:
export default combineReducers({
  cities,
  routing: routeReducer
});

store config: https://github.com/kirsanv43/Weather/blob/master/app/redux/config/store.js
import rootReducer from '../reducers'

export default function configureStore(initialState) {
  const history = createHistory();
  const middleware = syncHistory(history)

  const finalCreateStore = compose(
    applyMiddleware(middleware)
  )(createStore)

  const store = finalCreateStore(rootReducer)

  middleware.listenForReplays(store);

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers').default
      store.replaceReducer(nextRootReducer)
    })
  }

  return store
}

Router:
const store = configureStore()

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="addCity" component={AddCity}/>
      </Route>
    </Router>
  </Provider>
  ,
  document.getElementById('root')
);

Component:
class CitiesList extends React.Component {
  onAddCity = () => {
    this.props.route.push('/addCity')
  };

  render() {

    return

ADD CITY

  }

}

function mapDispatchToProps(dispatch) {
  return {
    route:bindActionCreators(routeActions, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(CitiesList)

A: insted createHistory need use createHashHistory from 'history'
that working for me

A: Please try to change  "react-router-redux" version  to "^5.0.0-alpha.8". It solved my problem


text:
Q: How to have a List of a MappedSuperType class in JPA Eclipselink? When generating tables, eclipse says it doest recognize the type of stores in class DogMall. And I cannot make Generic Clases Entity since Their type cannot be determined at generating tables. The exact error is "The target entity of relationship attribute events on the class BaseballGame cannot be determined". the error appear when generating the tables with eclipse and not in the problems view. Im using Eclipse Juno SR1.
I didnt want to post the code since is very large. For a brief description Im using Generics for this reason: If I have a League class and s subclass BaseballLeague. League have a List of Athletes but I wanted that if the instance is of BaseballLeague, athletes must be BaseballPlayers and avoid that client can add BaslketballPlayer to the BaseballLeague class as the League have an Athletes List. That was answered in this question. Here is the affected code:
package pqlrd.bll.sport;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import pqlrd.bll.pim.Person;
@Entity
/**
 * Athlete
 * @author jhonnytunes
 *
 */
public abstract class Athlete extends Person {

/**
 *
 */
private static final long serialVersionUID = 3099827166939719897L;

@OneToOne(cascade=CascadeType.ALL, orphanRemoval=true)
private PhysicalCondition physicalCondition;

@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
private List<PaymentCard> cards;

private List<ScoutingReport> report;

public Athlete() {
    // TODO Auto-generated constructor stub
}

public PhysicalCondition getPhysicalCondition() {
    return physicalCondition;
}

public void setPhysicalCondition(PhysicalCondition physicalCondition) {
    this.physicalCondition = physicalCondition;
}

public List<PaymentCard> getCards() {
    return cards;
}

public void setCards(List<PaymentCard> cards) {
    this.cards = cards;
}

public List<ScoutingReport> getReport() {
    return report;
}

public void setReport(List<ScoutingReport> report) {
    this.report = report;
}

public Athlete(PhysicalCondition physicalCondition,
        List<PaymentCard> cards, List<ScoutingReport> report) {
    super();
    this.physicalCondition = physicalCondition;
    this.cards = cards;
    this.report = report;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    result = prime * result + ((cards == null) ? 0 : cards.hashCode());
    result = prime
            * result
            + ((physicalCondition == null) ? 0 : physicalCondition
                    .hashCode());
    result = prime * result + ((report == null) ? 0 : report.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (!super.equals(obj))
        return false;
    if (getClass() != obj.getClass())
        return false;
    Athlete other = (Athlete) obj;
    if (cards == null) {
        if (other.cards != null)
            return false;
    } else if (!cards.equals(other.cards))
        return false;
    if (physicalCondition == null) {
        if (other.physicalCondition != null)
            return false;
    } else if (!physicalCondition.equals(other.physicalCondition))
        return false;
    if (report == null) {
        if (other.report != null)
            return false;
    } else if (!report.equals(other.report))
        return false;
    return true;
}

}

//////////////////////////////////////////////////////////////

 package pqlrd.bll.sport;

import javax.persistence.Column;
import javax.persistence.Entity;

@Entity
/**
 * @author jhonnytunes
 *
 */
public abstract class BaseballEvent extends SportEvent<BaseballPlayer> {

/**
 *
 */
private static final long serialVersionUID = 8163277354208426840L;

@Column(nullable = false)
private boolean onTop;

public void setOnTop(boolean onTop) {
    this.onTop = onTop;
}

public boolean isOnTop() {
    return onTop;
}

}
////////////////////////////////////////////////////
   package pqlrd.bll.sport;

import java.io.Serializable;
import java.util.LinkedList;
import javax.persistence.Entity;

@Entity
/**
 *  @author jhonnytunes
 *
 */
public class BaseballGame
        extends
    Game<BaseballPark, BaseballPlayer, BaseballEvent, BaseballCategory,             BaseballTeam>
    implements Serializable {

/**
 *
 */
private static final long serialVersionUID = 2260373487163641360L;

}

////////////////////////////////////
package pqlrd.bll.sport;

import java.util.LinkedList;
import javax.persistence.Entity;

@Entity
/**
 * @author jhonnytunes
*/
public class BaseballLeague extends
    League<BaseballPark, BaseballPlayer, BaseballCategory> {

/**
 *
 */
private static final long serialVersionUID = -3600825760889806131L;

}

//////////////////////////////////////////////////

package pqlrd.bll.sport;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
@Entity
/**
 * Baseball Player
 * @author jhonnytunes
 *
 */
public class BaseballPlayer extends Athlete {

@Enumerated(EnumType.STRING)
private Handedness _throws;

@Enumerated(EnumType.STRING)
private Handedness bats;

public BaseballPlayer() {
    // TODO Auto-generated constructor stub
}

public Handedness get_throws() {
    return _throws;
}

public void set_throws(Handedness _throws) {
    this._throws = _throws;
}

public Handedness getBats() {
    return bats;
}

public void setBats(Handedness bats) {
    this.bats = bats;
}

public BaseballPlayer(Handedness _throws, Handedness bats) {
    super();
    this._throws = _throws;
    this.bats = bats;
}

}

//////////////////////////////////////

package pqlrd.bll.sport;

import javax.persistence.Entity;

@Entity
/**
 *
 * @author jhonnytunes
 *
 */
public class BaseballTournament
    extends
    Tournament<BaseballPark, BaseballPlayer, BaseballCategory, BaseballTeam,    TournamentInvitationBaseball, BaseballEvent, BaseballGame, BaseballLeague> {

/**
 *
 */
private static final long serialVersionUID = 5315560497107867141L;

}

/////////////////////////////////

package pqlrd.bll.sport;

import java.io.Serializable;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import pqlrd.bll.pim.Person;

@MappedSuperclass
/**
 * Game
 * @author jhonnytunes
 */
public abstract class Game<P extends Park, A extends Athlete, SE extends SportEvent<A>, SC  extends SportCategory, T extends Team<A, SC>>
    implements Serializable {

/**
 *
 */
private static final long serialVersionUID = -1554044669639703370L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PQLRD_SEQ")
private long id;

@Column(nullable = false)
@Temporal(TemporalType.DATE)
private Calendar date;

@Column(nullable = false)
private boolean played;

@JoinColumn(nullable = false)
private P park;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private Map<Integer, SE> events;

@JoinColumn(nullable = false)
private T homeTeam;
@JoinColumn(nullable = false)
private T visitorTeam;

private Person scorer;

private List<A> homeAthletes;
private List<A> visitorAthletes;
public Calendar getDate() {
    return date;
}
public void setDate(Calendar date) {
    this.date = date;
}
public boolean isPlayed() {
    return played;
}
public void setPlayed(boolean played) {
    this.played = played;
}
public P getPark() {
    return park;
}
public void setPark(P park) {
    this.park = park;
}
public Map<Integer, SE> getEvents() {
    return events;
}
public void setEvents(Map<Integer, SE> events) {
    this.events = events;
}
public T getHomeTeam() {
    return homeTeam;
}
public void setHomeTeam(T homeTeam) {
    this.homeTeam = homeTeam;
}
public T getVisitorTeam() {
    return visitorTeam;
}
public void setVisitorTeam(T visitorTeam) {
    this.visitorTeam = visitorTeam;
}
public List<A> getHomeAthletes() {
    return homeAthletes;
}
public void setHomeAthletes(List<A> homeAthletes) {
    this.homeAthletes = homeAthletes;
}
public List<A> getVisitorAthletes() {
    return visitorAthletes;
}
public void setVisitorAthletes(List<A> visitorAthletes) {
    this.visitorAthletes = visitorAthletes;
}
public long getId() {
    return id;
}

public Person getScorer() {
    return scorer;
}
public void setScorer(Person scorer) {
    this.scorer = scorer;
}
public Game() {
    // TODO Auto-generated constructor stub
}
public Game(Calendar date, boolean played, P park, Map<Integer, SE> events,
        T homeTeam, T visitorTeam, List<A> homeAthletes,
        List<A> visitorAthletes) {
    super();
    this.date = date;
    this.played = played;
    this.park = park;
    this.events = events;
    this.homeTeam = homeTeam;
    this.visitorTeam = visitorTeam;
    this.homeAthletes = homeAthletes;
    this.visitorAthletes = visitorAthletes;
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((date == null) ? 0 : date.hashCode());
    result = prime * result + ((events == null) ? 0 : events.hashCode());
    result = prime * result
            + ((homeAthletes == null) ? 0 : homeAthletes.hashCode());
    result = prime * result
            + ((homeTeam == null) ? 0 : homeTeam.hashCode());
    result = prime * result + (int) (id ^ (id >>> 32));
    result = prime * result + ((park == null) ? 0 : park.hashCode());
    result = prime * result + (played ? 1231 : 1237);
    result = prime * result
            + ((visitorAthletes == null) ? 0 :  visitorAthletes.hashCode());
    result = prime * result
            + ((visitorTeam == null) ? 0 : visitorTeam.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Game other = (Game) obj;
    if (date == null) {
        if (other.date != null)
            return false;
    } else if (!date.equals(other.date))
        return false;
    if (events == null) {
        if (other.events != null)
            return false;
    } else if (!events.equals(other.events))
        return false;
    if (homeAthletes == null) {
        if (other.homeAthletes != null)
            return false;
    } else if (!homeAthletes.equals(other.homeAthletes))
        return false;
    if (homeTeam == null) {
        if (other.homeTeam != null)
            return false;
    } else if (!homeTeam.equals(other.homeTeam))
        return false;
    if (id != other.id)
        return false;
    if (park == null) {
        if (other.park != null)
            return false;
    } else if (!park.equals(other.park))
        return false;
    if (played != other.played)
        return false;
    if (visitorAthletes == null) {
        if (other.visitorAthletes != null)
            return false;
    } else if (!visitorAthletes.equals(other.visitorAthletes))
        return false;
    if (visitorTeam == null) {
        if (other.visitorTeam != null)
            return false;
    } else if (!visitorTeam.equals(other.visitorTeam))
        return false;
    return true;
}

}
////////////////////////////////
package pqlrd.bll.sport;

import java.io.Serializable;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.commons.lang.WordUtils;

import pqlrd.bll.cms.Attachment;
import pqlrd.bll.money.Payment;
import pqlrd.bll.pim.Address;
import pqlrd.bll.pim.ContactInformation;

@MappedSuperclass
/**
 * League class
 * @author jhonnytunes
 *
 */
public abstract class League<P extends Park, A extends Athlete, SC extends  SportCategory> implements Serializable {

/**
 *
 */
private static final long serialVersionUID = -6036071460102749097L;

@Id@GeneratedValue(strategy= GenerationType.SEQUENCE,generator="PQLRD_SEQ")
private int id;

@Column(length=30, nullable=false)
private String name;

@Column(nullable=false)
@Temporal(TemporalType.DATE)
private Calendar dateOfOrigin;

@Column(columnDefinition="text")
private String history;

@ElementCollection
private List<String> requirements;

private List<AthletesCost> athletesCosts;

@Column(nullable=false)
private boolean visible;

private P park;

@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
private List<LeagueStaff> leagueStaffs;

@OneToOne(cascade=CascadeType.ALL, orphanRemoval=true)
private List<ContactInformation>contactInformations;

@OneToOne(cascade=CascadeType.ALL, orphanRemoval=true)
private Address address;

@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
private List<Team<A, SC>> teams;

@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
private List<Attachment> attachments;

public String getName() {
    return WordUtils.capitalizeFully(name);
}

public void setName(String name) {
    this.name = name.toLowerCase();
}

public Calendar getDateOfOrigin() {
    return dateOfOrigin;
}

public void setDateOfOrigin(Calendar dateOfOrigin) {
    this.dateOfOrigin = dateOfOrigin;
}

public String getHistory() {
    return history;
}

public void setHistory(String history) {
    this.history = history;
}

public List<String> getRequirements() {
    return requirements;
}

public void setRequirements(List<String> requirements) {
    this.requirements = requirements;
}

public List<AthletesCost> getAthletesCosts() {
    return athletesCosts;
}

public void setAthletesCosts(List<AthletesCost> athletesCosts) {
    this.athletesCosts = athletesCosts;
}

public boolean isVisible() {
    return visible;
}

public void setVisible(boolean visible) {
    this.visible = visible;
}

public P getPark() {
    return park;
}

public void setPark(P park) {
    this.park = park;
}

public List<LeagueStaff> getLeagueStaffs() {
    return leagueStaffs;
}

public void setLeagueStaffs(List<LeagueStaff> leagueStaffs) {
    this.leagueStaffs = leagueStaffs;
}

public List<ContactInformation> getContactInformations() {
    return contactInformations;
}

public void setContactInformations(List<ContactInformation> contactInformations) {
    this.contactInformations = contactInformations;
}

public Address getAddress() {
    return address;
}

public void setAddress(Address address) {
    this.address = address;
}

public List<Team<A, SC>> getTeams() {
    return teams;
}

public void setTeams(List<Team<A, SC>> teams) {
    this.teams = teams;
}

public List<Attachment> getAttachments() {
    return attachments;
}

public void setAttachments(List<Attachment> attachments) {
    this.attachments = attachments;
}

public int getId() {
    return id;
}

public League() {
    // TODO Auto-generated constructor stub
}

public League(String name, Calendar dateOfOrigin, String history,
        List<String> requirements, List<AthletesCost> athletesCosts,
        boolean visible, P park, List<LeagueStaff> leagueStaffs,
        List<ContactInformation> contactInformations, Address address,
        List<Team<A, SC>> teams, List<Attachment> attachments) {
    super();
    this.name = name;
    this.dateOfOrigin = dateOfOrigin;
    this.history = history;
    this.requirements = requirements;
    this.athletesCosts = athletesCosts;
    this.visible = visible;
    this.park = park;
    this.leagueStaffs = leagueStaffs;
    this.contactInformations = contactInformations;
    this.address = address;
    this.teams = teams;
    this.attachments = attachments;
}

}

/////////////////////////////

package pqlrd.bll.sport;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;

import org.apache.commons.lang.math.NumberUtils;

import pqlrd.bll.util.NumbersUtil;
@IdClass(SportEventPK.class)
@MappedSuperclass
/**
 * Event that occur in a time of a game
 * @author jhonnytunes
 *
 */

public abstract class SportEvent<T extends Athlete> implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 3814280347145588159L;

@Id private T athlete;
@Id private short period;
@Id private long random;
@Id private short quantity;

public T getAthlete() {
    return athlete;
}
public void setAthlete(T athlete) {
    this.athlete = athlete;
}
public short getPeriod() {
    return period;
}
public void setPeriod(short period) {
    this.period = period;
}
public long getRandom() {
    return random;
}

public SportEvent() {

    this.random = NumbersUtil.random.nextLong();
}
public short getQuantity() {
    return quantity;
}
public void setQuantity(short quantity) {
    this.quantity = quantity;
}

}

//////////////////////////////

package pqlrd.bll.sport;

import java.io.Serializable;

import javax.persistence.Embeddable;

public class SportEventPK implements Serializable {

/**
 *
 */
private static final long serialVersionUID = -1251889014150257402L;

private Athlete athlete;
private short period;
private long random;
private short quantity;

public short getQuantity() {
    return quantity;
}

public void setQuantity(short quantity) {
    this.quantity = quantity;
}

public SportEventPK() {
    // TODO Auto-generated constructor stub
}

protected Athlete getAthlete() {
    return athlete;
}

protected void setAthlete(Athlete athlete) {
    this.athlete = athlete;
}

protected short getPeriod() {
    return period;
}

protected void setPeriod(short period) {
    this.period = period;
}

protected long getRandom() {
    return random;
}

protected void setRandom(long random) {
    this.random = random;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((athlete == null) ? 0 : athlete.hashCode());
    result = prime * result + period;
    result = prime * result + (int) (random ^ (random >>> 32));
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    SportEventPK other = (SportEventPK) obj;
    if (athlete == null) {
        if (other.athlete != null)
            return false;
    } else if (!athlete.equals(other.athlete))
        return false;
    if (period != other.period)
        return false;
    if (random != other.random)
        return false;
    return true;
}

}
/////////////////////////

package pqlrd.bll.sport;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
@MappedSuperclass

/**
 * @author jhonnytunes
 *
 */
public abstract class Team<A extends Athlete, SC extends SportCategory > implements     Serializable {

/**
 *
 */
private static final long serialVersionUID = 5556278910044704061L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PQLRD_SEQ")
private int id;

@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
private List<PracticeTime> times;

@JoinColumn(nullable=false)
private SC category;

private List<A> athletes;

public List<PracticeTime> getTimes() {
    return times;
}

public void setTimes(List<PracticeTime> times) {
    this.times = times;
}

public SC getCategory() {
    return category;
}

public void setCategory(SC category) {
    this.category = category;
}

public List<A> getAthletes() {
    return athletes;
}

public void setAthletes(List<A> athletes) {
    this.athletes = athletes;
}

public int getId() {
    return id;
}

public Team() {
    // TODO Auto-generated constructor stub
}

public Team(List<PracticeTime> times, SC category, List<A> athletes) {
    super();
    this.times = times;
    this.category = category;
    this.athletes = athletes;
}

}

A: Solved. Removed the @OneToMany anotations from the atatributes that are collection of a mappedsuperclass.

A: Move the OneToMany fields down to the subclasses.