text:
Q: Using pySerial with Python 3.3 I've seen many code samples using the serial port and people say they are working codes too. The thing is, when I try the code it doesn't work.
import serial

ser = serial.Serial(
    port=0,
    baudrate=9600
    # parity=serial.PARITY_ODD,
    # stopbits=serial.STOPBITS_TWO,
    # bytesize=serial.SEVENBITS
)

ser.open()
ser.isOpen()

print(ser.write(0xAA))

The error it gives me is : "SerialException: Port is already opened".
Is it me using python3.3 the problem or is there something additional I need to instal ? Is there any other way to use COM ports with Python3.3 ?

A: So the moral of the story is.. the port is opened when initialized. ser.open() fails because the serial port is already opened by the ser = serial.Serial(.....). And that is one thing.
The other problem up there is ser.write(0xAA) - I expected this to mean "send one byte 0xAA", what it actually did was send 170(0xAA) zeros. In function write, I saw the following :
data = bytes(data) where data is the argument you pass. it seems the function bytes() doesn't take strings as arguments so one cannot send strings directly with: serial.write(), but ser.write(bytearray(TheString,'ascii')) does the job.
Although I am considering adding:
if(type(data) == type('String')):
    data = bytearray(data,'ascii')

in ser.write(), although that would make my code not work on other PCs.


text:
Q: Unable to convert a json containing nested json arrays to an equivalent JAVA class using Gson JSON string used:
'{"Sensors":[{\"name\":\"BLRB50CM_A\",\"cameraId\":\"Cam10\",\"id\":1,\"resolution\":\"1280 x 720\",\"officeLocation\":\"Offshore Development Center\",\"tags\":\"Entrance Camera, Parking Lot\",\"isActive\":\"true\",\"hls\":\"https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8\",\"rtsp\":\"rtsp://10.66.102.66:32278/mystream/parking_lot\",\"type\":\"sensor\",\"inputs\":[],\"outputs\":[2]}]}'

java pojo class:
public class ServiceFlowData {

    public ArrayList<Sensor> sensors;

    public ArrayList<Sensor> getSensors() {
        return sensors;
    }

    public void setSensors(ArrayList<Sensor> sensors) {
        this.sensors = sensors;
    }
}

code used for conversion to java object
Gson gson = new Gson();
ServiceFlowData serviceFlowData = gson.fromJson(jsonString,ServiceFlowData.class);
System.out.println("serviceFlowData"+serviceFlowData.getSensors());

iam getting get sensors as null.
what is it iam mising here..?

A: Your json key is Sensors and not sensors.
Solution 1
Try changing
public ArrayList<Sensor> sensors;

to
public ArrayList<Sensor> Sensors;

Solution 2
You can use @SerializedName annotation to map a json key to a java variable with a different name.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom View with two TextViews I want to create a custom view with 2 TextViews, with possibility change text and text appearances from xml. This view should have two state - normal and selected (TextViews style should be different for each state).
I need some example for it.

A: Custom views are pretty basic and there are examples all over the internet.  For something simple like two text views, it's usually easiest to extend LinearLayout.
Here is the LinearLayout with two text views, arranged side by side.
res/double_text.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:id="@+id/left_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"/>
    <TextView
        android:id="@+id/right_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"/>
</LinearLayout>

Next we define a styleable resource block so we can add custom attributes to our custom layout.
res/values/attrs.xml
<resources>
    <declare-styleable name="DoubleText">
        <attr name="leftText" format="string" />
        <attr name="rightText" format="string" />
        <attr name="android:ems" />

    </declare-styleable>
</resources>

Next the class file for DoubleText custom view.  In here we pull out the custom attributes and set each of the TextViews.
DoubleTextView.java
public class DoubleTextView extends LinearLayout {
   LinearLayout layout = null;
   TextView leftTextView = null;
   TextView rightTextView = null;
   Context mContext = null;

   public DoubleTextView(Context context) {

      super(context);
      mContext = context;
   }

   public DoubleTextView(Context context, AttributeSet attrs) {
      super(context, attrs);

      mContext = context;

      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DoubleText);

      String leftText = a.getString(R.styleable.DoubleText_leftText);
      String rightText = a.getString(R.styleable.DoubleText_rightText);

      leftText = leftText == null ? "" : leftText;
      rightText = rightText == null ? "" : rightText;

      String service = Context.LAYOUT_INFLATER_SERVICE;
      LayoutInflater li = (LayoutInflater) getContext().getSystemService(service);

      layout = (LinearLayout) li.inflate(R.layout.double_text, this, true);

      leftTextView = (TextView) layout.findViewById(R.id.left_text);
      rightTextView = (TextView) layout.findViewById(R.id.right_text);

      leftTextView.setText(leftText);
      rightTextView.setText(rightText);

      a.recycle();
   }

   public DoubleTextView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      mContext = context;
   }

   @SuppressWarnings("unused")
   public void setLeftText(String text) {
      leftTextView.setText(text);
   }

   @SuppressWarnings("unused")
   public void setRightText(String text) {
      rightTextView.setText(text);
   }

   @SuppressWarnings("unused")
   public String getLeftText() {
      return leftTextView.getText().toString();
   }

   @SuppressWarnings("unused")
   public String getRightText() {
      return rightTextView.getText().toString();
   }

}

Finally, using the custom class is as simple as declaring it in a layout file.
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/main_text"
        android:text="Hello World!"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/custom"/>

    <example.com.test.DoubleTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:leftText="Text Left"
        app:rightText="Text Right"
        android:layout_below="@+id/main_text"/>
</RelativeLayout>

Easy peasy.


text:
Q: How to select only one checkbox in dynamic form in angular 8 I have a dynamic form which is producing 8 different checkboxes according to the API response. Now I want the user to be able to select only 1 check box at a time. If the user wants to select a different checkbox he first has to deselect the selected checkbox. Please refer to the code below.
<ng-container *ngIf="field.inputType==='group';else singleCase">

{{'label.' + field.name | translate}}

        <ng-container [formArrayName]="field.name"
          *ngFor="let item of group.controls[field.name].controls; let i = index">
          <input type="checkbox" class="hidden" (click)="preventCheck($event)" (change)="onChange($event)" [formControlName]="i"
            [name]="field.name + i+1" [id]="field.name + i+1">

            {{field.options[i].value}}

        </ng-container>

          {{'sub_text.' + field.name | translate}}

      <ng-container *ngFor="let validation of field.validations">

{{validation.message}}

      </ng-container>

  </ng-container>

A: It can be done in multiple ways, with reacting on change/click event and saving the name of checked/clicked element.
Consider below as an example, maybe it's not the most elegant solution, but you can implement logic in many ways actually:
[HTML]

export class YourComponentClass  {
  isChecked;
  isCheckedName;
  checkboxData = [1,2,3,4,5,6,7,8];
  onChange(e){
    this.isChecked = !this.isChecked;
    this.isCheckedName = e.target.name;
  }
}

<input type="checkbox" [name]="name" (change)="onChange($event)" [disabled]="isChecked && (isCheckedName!=name)"> {{'Checkbox ' + name}}

online: you can check it on stackblitz
And in case you don't need much from $event, better to pass to component only data that you need,so you may change to onChange($event.target.name) in html, and in ts code this.isCheckedName = e; accordingly.
Good luck ;)

A: If you are using material/cdk in your app there is an easy to implement solution involving SelectionModel that works well with Reactive Forms/FormBuilder.
In your component declare:
selection = new SelectionModel<any>(false, []);

Then in your template/html:

             <mat-checkbox formControlName="selected" (change)="$event ?
                  selection.toggle(i) : null" [checked]="selection.isSelected(i)">
             </mat-checkbox>


text:
Q: How do I list wp posts with releated images? I would like to list posts in Wordpress and related images. How do I write the mysql_query($ask) in mysql?
I can join two tables but not sure how to do it as I need to use wp_posts two times via wp_postmeta, as I understand it.

A: You don't need to create a custom handmade query to perform this. You only need to run the Wordpress loop and get the releated images for each post. Try this simple code :)
<?php if ( have_posts()) : while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

    <?php the_post_thumbnail(); ?>
<?php endwhile; endif; ?>


text:
Q: How to stash a single untracked file out of a group of hundreds of both modified and untracked files in the git? I did an upgrade to Magento 2.3.5 resulting in hundreds of files being modified while some were newly added. I added another untracked file not related to the upgrade in anyway, and know exactly what the file name is. Is there a git command or something to stash this particular untracked file by mentioning only the file name that I want stashed? I know this files resides on the file system.

A: Sometime if we change files and folder permission than also shows as modified files
so can you try with first this command ?
git config core.filemode false
And than for stashing single file you can give command like below.
git stash push -m <message> <path-of-file>

A: I recommend using Magentos official .gitignore and adding to it, please see;
https://devdocs.magento.com/guides/v2.3/config-guide/prod/config-reference-gitignore.html
Workflow example;

*

*composer.json is tracked in this git repo, you make development and staging changes which update this file.

*When you git pull to your server(s), you should then run composer update, this will check your composer.json file, and update the /vendor directory as required.

*This way of working will keep your git repo clean, and also ensure devs aren't modifying core files /vendor should never be coded into directly, as composer will over-write changes (changes should always be made by over-riding in the /app directory.

So, in your case - you need to add this .gitignore from magento, because you shouldn't see hundreds of git entries in a Magento upgrade. I'd recommend adding this gitignore, back up the composer.json, then git stash all changes, run composer update to pull the 2.3.5 changes, and work this way going forward for no headaches.


text:
Q: How to simulate pressing the END key I have a javascript function that gets called from an aspx.vb file:
using ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "pressKey();", True)

and I need the pressKey function to simulate pressing the END key as if the user pressed it on their keyboard.

A: The charCode for the End key is 35. CSS tricks has a good list of character codes: https://css-tricks.com/snippets/javascript/javascript-keycodes/
Here is the Vanilla JS solution:
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ?
"initKeyboardEvent" : "initKeyEvent";

keyboardEvent[initMethod](
               "keydown", // event type : keydown, keyup, keypress
                true, // bubbles
                true, // cancelable
                window, // viewArg: should be window
                false, // ctrlKeyArg
                false, // altKeyArg
                false, // shiftKeyArg
                false, // metaKeyArg
                35, // keyCodeArg : unsigned long the virtual key code, else 0
                0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);


text:
Q: Assembly - Carry Flag when negative minus negative If the CPU treats the subtraction as add like this question.
Then (-1) - (-2) should be FF...FF + 00...02, and the CARRY FLAG should be set.
I wrote c code to test (-1) - (-2) on linux, but found the CARRY FLAG was not set.
How CPU deal with this situation.
Disassembly Code
00000000004004ed <main>:
  4004ed:   55                      push   %rbp
  4004ee:   48 89 e5                mov    %rsp,%rbp
  4004f1:   c7 45 fc ff ff ff ff    movl   $0xffffffff,-0x4(%rbp)
  4004f8:   c7 45 f8 fe ff ff ff    movl   $0xfffffffe,-0x8(%rbp)
  4004ff:   8b 45 f8                mov    -0x8(%rbp),%eax
  400502:   8b 55 fc                mov    -0x4(%rbp),%edx
  400505:   29 c2                   sub    %eax,%edx
  400507:   89 d0                   mov    %edx,%eax
  400509:   89 45 f4                mov    %eax,-0xc(%rbp)
  40050c:   5d                      pop    %rbp
  40050d:   c3                      retq
  40050e:   66 90                   xchg   %ax,%ax

GDB test
(gdb) ni
0x0000000000400505 in main ()
(gdb)
0x0000000000400507 in main ()
(gdb) p $eflags
$1 = [ IF ]


text:
Q: Input voltage on differential ADC (MCP33131D-05-E/MS) I am evaluating a 16bit ADC (MCP33131D-05-E/MS) for my project. I want to sample in fully differential mode, but I have doubts as to what voltages are allowed on the Ain+ and Ain-.
Signal conditioning prior to the ADC is done with a dual supply so the voltage swing of the sampled signal will be -5V to +5V.
The datasheet states (on page 1 -> Features) that the ADC has a differential input -VREF to +VREF. This would make it -5V to +5V in my design since I will use a 5V voltage reference.
But then in the absolute maximum ratings it states the following:
Analog inputs w.r.t GND .............. .......... –0.3V to VREF+0.3V
I The question is: can I apply a negative (-VREF) signal to the Ain- or will the magic smoke escape?
Link to the datasheet of MCP33131D-05-E/MS

A:
The question is: can I apply a negative (-VREF) signal to the Ain-

No. The Ain signals are DIFFERENTIAL, which means that Ain+ can be 0, and Ain- can be VREF, which is -VREF in internal ADC representation. If Ain+=VREF and Ain-=0, it is +VREF. But both inputs must be positive in relation to ground.


text:
Q: Create a new pandas dataframe from a subset of rows from an existing dataframe I an a newbie with both Python and Pandas. I have a pandas dataframe consisting of many years of timeseries data of a number of stocks e.g. S&P 500. I want to iterate through each unique stock code one by one and calculate technical indicators on the closing prices. I have been trying to create a new dataframe for each unique stock from the main dataframe with all its price history and then pass it to a method which will do the technical analysis rather than passing the main dataframe. Here is some sample data from my dataframe:
Id      Symbol       Date       Open       High        Low      Close   Volume
1       A99     2012-01-02    730.019    730.019    730.019    730.019       0
2       ABA     2012-01-02      4.200      4.200      4.200      4.200       0
3       AFI     2012-01-02      5.360      5.360      5.360      5.360       0
4       AIA     2012-01-02      2.520      2.520      2.520      2.520       0
...
501     A99     2012-01-03    730.019    730.019    730.019    730.019       0
...

I have tried indexers such as loc, iloc and also groupby but with no luck. I have read many articles e.g.
Select rows from a DataFrame based on values in a column in pandas
but none of them quite match my requirements. The main issue with all of these is you have to have a literal search criteria whereas I want a variable filter name i.e. the stock name. Sample of my datatable is as follows:
This is a snippet of my current code which does not work:
# Get the data from the database
    df = stockPrices.get_data()
# Create technical indicators for each distinct stock
# First get a series of all unique stock codes
ts = pd.Series(df.Symbol.unique())

# Iterate through the series and call the technical indicator method
for row in ts:
    # filter for just this stock
    filtered_df = df.loc[df['Symbol'] == row]
    df = stockPrices.calc_technicals(filtered_df, row)

Any pointers would be appreciated.

A: To select all the rows matching symbol as 'A99'
filtered_df = df.loc[df['Symbol'] == 'A99']

also try:
filtered_df = df.loc[df['Symbol'].isin('A99')]

A: Your code is nothing wrong. group_by is not suitable here as there is no group manipulation. Please check your method stockPrices.calc_technicals.
df=pd.DataFrame({'symbol':['a','a','a','b','b'],'v':[1,2,3,4,5]})
ts=pd.Series(df.symbol.unique())
for i in ts:
    filtered_df=df.loc[df.symbol==i]
    print(filtered_df)

  symbol  v
0      a  1
1      a  2
2      a  3
  symbol  v
3      b  4
4      b  5


text:
Q: An Error message, says "Error while processing samples" which occurs while generating Dashboard from Jmeter I am using JMeter 5.4.1 for load testing, I wanted to generate a reporting dashboard from a .jtl file.
When I run the following command from Command Prompt:
jmeter -g E:\Outcode\ProtocolNow\Data\Jmeterlog\scriptresults.jtl -f -o E:\Outcode\ProtocolNow\Data\Jmeterlog\HTMLRESULTS

Error on Command Prompt:
An error occurred: Error while processing samples: Consumer failed with message :Consumer failed with message :Consumer failed with message :Consumer failed with message :Begin size 1 is not equal to fixed size 5
errorlevel=1

I am not able to figure out the reason.
First 3 lines from the .jtl log are posted below:
timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect
1637132376961,1932,oauth/token,200,OK,jp@gc - Ultimate Thread Group 1-10,text,true,,1955,541,2,2,https://app.ex.com/oauth/token,1931,0,1306
1637132377905,1450,oauth/token,200,OK,jp@gc - Ultimate Thread Group 1-9,text,true,,1693,561,3,3,https://app.ex.com/oauth/token,1450,0,862
1637132379774,353,Login/SetDefaultOrganization,200,OK,jp@gc - Ultimate Thread Group 1-10,text,true,,524,653,4,4,https://app.ex.com/api/Login/SetDefaultOrganization,352,0,0

A: It looks like you're using too new JDK version

As per Introducing JMeter 5.4: New Features and Abilities you need to use JDK 8 so you will need to downgrade in order to be able to generate the reporting dashboard.
There is a chance that the issue is fixed in JMeter nightly build.


text:
Q: Hide Site Content for Visitors I am in a need to hide the Site Content option completely from site for Visitors. Can anyone help me how I can achieve this goal?
How to hide Site Content only for Visitors or a particular security group in SharePoint 2013?

A: You'd have to remove it from 2 places, the Quick Launch and the Site Actions menu. You can use JQuery and SPServices to check group membership and hide the link in the Quick Launch. Put the code in your master page(s), not a Content Editor Web Part, to hide it on the entire site. You can also use JQuery to hide "View All Site Content" from the Site Actions menu.
However, you will not be able to prevent users from typing /_layouts/viewlsts.aspx directly into the address bar. Clicking the default "Lists" or "Libraries" headers in the Quick Launch would also take them to the content page. It might be possible to add JQuery to the system master page to redirect visitors to a different page if the URL includes /_layouts/viewlsts.aspx.

A: You have two possibilities in this case that doesn't require code.
Variant 1) Change the permission level of visitor
When you change the permission level from "Read" to "Restricted Read" your user won't see the site contents anymore
Variant 2) Alternate read permission level of visitors
You can simply remove the base permission "View Application Pages" from the "Read" Permission level.
The "site contents" is not the only place where user will see this navigation option. It is also available through the gear icon on the suite bar. By changing the permissions or permission level it will be hidden from there too.

A: *

*Create a separate SharePoint Group (or Audience in Central Admin)

*Check Group Membership with:

*CEWP (on every needed page); (audience) targeted to this group

*or with Code in your MasterPage

*Apply CSS to alter UI

*inside CEWP

*append CSS from MasterPage

Usually your visitors won't go to many pages, so the CEWP option works fine.
Note: If they know the URL they can go where they have rights
So it is kind of pointless to hide it; they should only see what they are allowed to see inside "Site Contents"

A: What you do usually when you have an internet publishing site is to include a SPSecurityTrimmedControl on your masterpage, to restrict the real visibility of the control (here the quicklaunch) for different users.
An other solution is to restrict the link directly on the link itself. When you see the control in the masterpage, you have properties like PermissionsString="ViewFormPages".
The control for the link in the masterpage (seattle.master)
<SharePoint:ClusteredSPLinkButton
                            runat="server"
                            id="idNavLinkViewAll"
                            PermissionsString="ViewFormPages"
                            NavigateUrl="~site/_layouts/15/viewlsts.aspx"
                            Text="<%$Resources:wss,AllSiteContentMore%>"
                            accesskey="<%$Resources:wss,quiklnch_allcontent_AK%>"
                            CssClass="ms-core-listMenu-item ms-core-listMenu-heading" />

You can change the permissionstring to "ManageWeb" to restrict the link to the admin.
For both solution, you should update the masterpage, with SP Designer e.g
Regards,
ps : Don't forget to NOT update standard masterpage but make a copy before and work on this copy :)

A: SharePoint Online doesn't handle the permissions at the same way as SharePoint 2013.
Use this:
<SharePoint:SPSecurityTrimmedControl runat="server" Permissions="AddListItems"
    PermissionContext="CurrentItem" PermissionMode="Any">
    <SharePoint:MenuItemTemplate runat="server" id="MenuItem_ViewAllSiteContents"
        Text="<%$Resources:wss,quiklnch_allcontent_15%>"
        Description="<%$Resources:wss,siteactions_allcontentdescription%>"
        ImageUrl="/_layouts/15/images/allcontent32.png?rev=43"
        MenuGroupId="200"
        Sequence="240"
        UseShortId="true"
        ClientOnClickNavigateUrl="~siteLayouts/viewlsts.aspx"
        PermissionsString="ViewFormPages"
        PermissionMode="Any" />
</SharePoint:SPSecurityTrimmedControl>


text:
Q: Extend a fluent API from external package in go I've currently got an object from an external package that provides a fluent API, like:
thing := ext.GetThing()
thing.do().stuff()

I'd like to extend this to provide a new function cool so I can use it like
thing.do().cool().stuff()

Unfortunately, since I can't have an external type as a receiver for cool, then best I've got so far seems to be
cool(thing.do()).stuff()

which becomes very difficult to read as I combine my custom stuff with the built-in fluent.
Is there some way in Go to achieve the extended fluent style that I'm missing?

A: No, you can't because you "cannot define new methods on a non-local type", as the compiler will tell you if you try.
Let's say you want to do something silly like:
import "net/http"

func (c *http.Client) SayHi() {
    println("Hi!")
}

This won't compile and you'll get the error message mentioned above as you can check here: https://play.golang.org/p/FxBMAfR_aN


text:
Q: Getting first Image from post Hi I am following the instructions from this article and I cannot get it to work, it gives me a blank screen.
I think there is something wrong with the opening and closing php tags between the div "view view-first" and the div "mask". When I remove these tags I get the site is displayed again but instead of images the is php code displayed.
I did get the code to work briefly but now it is broken again.
Thanks for your help.
RT
<?php get_header(); ?>

     <?php query_posts(array('category__in' => array(5), 'posts_per_page' => 10000)); ?>
            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

                    <?php $currentid = get_the_id(); ?>

                                   <?php
                                   if ( get_the_post_thumbnail($post_id) != '' ) {

                                      echo '';
                                      the_post_thumbnail(array(300,600));
                                      echo '';

                                    } else {

                                     echo '';
                                     echo '';
                                     echo '';

                                    }

                                 wp_reset_query();
                                ?>

<a href="<?php the_permalink(); ?>"><?php echo get_the_title($currentid); ?>

<?php echo get_the_excerpt( $post->parent ); ?>

                                <a href="<?php the_permalink(); ?>" class="info">Read More...

                    <?php
                endwhile;
            endif;

            wp_reset_query();
            ?>

<?php get_footer(); ?>

A: Chris's article looks for the img tag on your post. Since you are using WordPress, and I'm assuming the WordPress uploads feature, here is how you can get the first uploaded image on your post. Paste the following code in your theme's functions.php file.
//function to call first uploaded image in functions file
function main_image() {
$files = get_children('post_parent='.get_the_ID().'&post_type=attachment
&post_mime_type=image&order=desc');
  if($files) :
    $keys = array_reverse(array_keys($files));
    $j=0;
    $num = $keys[$j];
    $image=wp_get_attachment_image($num, 'large', true);
    $imagepieces = explode('"', $image);
    $imagepath = $imagepieces[1];
    $main=wp_get_attachment_url($num);
        $template=get_template_directory();
        $the_title=get_the_title();
    print "";
  endif;
}

Now paste something like this in your template:
<?php if (  (function_exists('has_post_thumbnail')) && (has_post_thumbnail())  ) {
  echo get_the_post_thumbnail($post->ID);
} else {
   echo main_image();
} ?>

Hope that helps.

A: catch_that_image(array(300,600)); should be catch_that_image();
You are not getting the first child attachment (as Syed suggested), you are just searching the post for images and displaying the first one you find, so there is no "dimensions" array to catch_that_image(); like in the_post_thumbnail();

A: I doubt there is anything wrong with the code bit - but please note that get_the_post_thumbnail grabs the featured image, not the first image in the content.


text:
Q: oracle sql plus spool I'm using sql plus to execute a query (a select) and dump the result into a file, using spool option.
I have about 14 millions lines, and it takes about 12 minutes to do the dump.
I was wondering if there is something to make the dump faster?
Here below my sql plus options:
whenever sqlerror exit sql.sqlcode
        set pagesize 0
        set linesize 410
        SET trimspool ON
        set heading on
        set feedback off
        set echo off
        set termout off
        spool file_to_dump_into.txt
        select * from mytable;

Thanks.

A: Are you concatenating & delimiting your columns, or are you exporting fixed-width?
See this documentation on SQL*Plus Script Tuning.  Specific to your script, here are a few possible ways to speed it up:

*

*Make sure LINESIZE is as small as possible.  Add your max column lengths (plus delimiters if not fixed-width). This can have a dramatic effect on performance, as SQL*Plus allocates that amount of memory for every exported line.  410 isn't that big, but if you can decrease it that would help.  This has made a big difference, in my experience.

*Don't turn TRIMSPOOL on.  This can also have a big impact.  Each line will then be padded out to LINESIZE, but with an optimal linesize, and depending on how you're using the file, that may be acceptable.  However if you want to elminate trailing spaces entirely, it can often be faster to trim them using other methods post-export.

*Play around with ARRAYSIZE.  It may help (a little).  It sets the fetch size for SQL*Plus.  Default is 15 rows.  Bumping to, say, 100 may help, but going too large might decrease speed.

Hope this helps!

A: You might find it quicker to use UTL_FILE, but probably not that much faster.
in my test it was slightly faster over about 20k of rows, blow that out over 14 million though and it might be worth it.
I believe if you want to get any quicker than this, the way to go would be pro*c.. but I haven't got into that, so can't really advise.
set pagesize 1000
set FLUSH OFF
drop user usera cascade;
create user usera default tablespace users identified by abc123;
grant create session to usera;
grant resource to usera;

create or replace directory testdir as '/tmp';
grant read,write on directory testdir to usera;
grant execute on UTL_FILE to usera;

connect usera/abc123;

set timing on

spool /tmp/spooltest.txt
select object_name from all_objects;
spool off

DECLARE
 v_file UTL_FILE.FILE_TYPE;
 TYPE t_col is table of all_objects.object_name%type index by PLS_INTEGER;
 v_object_names t_col;

BEGIN
  v_file := UTL_FILE.FOPEN('TESTDIR','utlfiletext.txt','w');

  select object_name BULK COLLECT INTO v_object_names
  from all_objects;

  for idx IN 1 .. v_object_names.COUNT LOOP
    UTL_FILE.PUT_LINE(v_file, v_object_names(idx), FALSE);
  END LOOP;

   UTL_FILE.FCLOSE(v_file);
END;
/

The results. The top result being from sqlplus only, the bottom using UTL_FILE
23931 rows selected.

Elapsed: 00:00:06.60

PL/SQL procedure successfully completed.

Elapsed: 00:00:05.45

A: With a typical query, 14M records is at least several hundred megabytes of data to fetch out of the server, pass across the connection and save to the disk.
Given this, 12 minutes does not sound too much to me.
However, it is still possible that your query can be optimized. Could you please post it here?

A: So is this going over the wire or are you logged into the box that has the database?  If you have access, maybe you can run your sqlplus session on the box where the database lives and zip the file up then send the file to your local machine.  It might be faster to send a big file over the wire instead of sending millions of smaller records. Of course this won't make it super fast, but might shave some time off.
Also with that much data do you really need to spool it to file? Can you do an export instead?

A: You can enable output buffering by adding to you script
SET FLUSH OFF

But result depends on your OS.

A: When getting a lot of results from a query in SQL*Plus, I've found that one thing that takes a lot of time is the actual displaying of the data.  If you're spooling the data to a file, you can SET TERMOUT OFF, and the query runs much faster since it doesn't have to spend the time to write it to the screen.

A: Some options are available from Tom Kyte, who is a real guru.


text:
Q: The default behaviour of mat select changes when I add a search bar So below is my code. What I am doing is showing all the available devices in a dropdown where multi select is allowed and also I have added a search field when devices count is more than 4. The default behaviour of mat-select is that when I select an option and close the dropdown, it opens on the selected option when I reopen it. But here it's not happening. It starts from the start. So I want that when I scroll and select last option, and when I reopen the dropdown the menu should be scrolled enough to show me the selected option.
Is this default behaviour not working because I added a search bar?

<form [formGroup]="gatewayForm" autocomplete="off">
                        <mat-form-field style="font-size:0.83em" class="no-arrow activity-log-field">
                            <mat-select formControlName="gatewayCtrl" multiple disableOptionCentering panelClass="form-panel gpanel" name="Gateway" (openedChange)="checkChanged($event,'gatewayList')" (selectionChange)="gatewaySelectedClick($event)">
                                <mat-select-trigger>
                                    {{selectedText}}
                                    <span *ngIf="extratext!=null" class="example-additional-selection">
                                        {{extratext}}
                                    </span>
                                </mat-select-trigger>

                                <mat-form-field *ngIf="gateways && gateways.length>4" class="organistation-searchField" appearance="outline"  [floatLabel]="'never'" aria-autocomplete="off" style="padding: 5px 8px 5px 8px;font-size: 13px">
                                    <input #search autocomplete="off" formControlName="searchTerm" (keyup)="filterDevices($event.target.value,'gatewayList','gpanel');" (keydown)="$event.stopPropagation()" matInput placeholder="Search Device">
                                    <mat-icon matSuffix style="color:#24539f;position: relative;top: 0.1em;">search</mat-icon>
                                </mat-form-field>
                                <div class="panel-optn" style="max-height: 170px;">
                                    <mat-option *ngIf="gateways && gateways.length>1" (click)="toggleAllSelection()" #allSelected class="gatewayList" [value]="allgateways">All devices</mat-option>
                                    <mat-option (click)="tosslePerOne(allSelected!=null?allSelected.viewValue:null)" class="gatewayList" *ngFor="let gateway of gateways" [value]="gateway">
                                        {{ gateway.panel_name }}
                                    </mat-option>
                                </div>
                            </mat-select>
                        </mat-form-field>
                    </form>

A: this.yourElementHere.focus();

this should focus the dropdown on the element you select.
include the value of your selected option like
this.yourElementHere.focus(selectedOption);

A: So the problem was caused by the mat-option being inside a div tag. I removed it and applied the styling on the mat-select directly through panelClass.


text:
Q: JUnit's own sample tests fail? I just downloaded junit-4.10.jar.  According to the JUnit FAQ, all you have to do is extract the jar file into a directory, and put the jar file in your classpath, and it's installed.  Then you can test the installation by running the sample tests with this command:
java org.junit.runner.JUnitCore org.junit.tests.AllTests

The FAQ must be out of date though, because AllTests doesn't reside in org.junit.tests, it resides in org.junit.runners.  So this is what I get when I try to run the sample tests using AllTests in the org.junit.tests package.  Anyone know why the sample tests are failing?  Yes I checked my CLASSPATH and the junit-4.10.jar is in there.
C:\Users\username\Downloads\junit4.10-extracted>java org.junit.runner.JUnitCore org.junit.runners.AllTests
JUnit version 4.10
.E.E
Time: 0.003
There were 2 failures:
1) initializationError(org.junit.runners.AllTests)
java.lang.Exception: Test class should have exactly one public zero-argument constructor
    at org.junit.runners.BlockJUnit4ClassRunner.validateZeroArgConstructor(BlockJUnit4ClassRunner.java:144)
    at org.junit.runners.BlockJUnit4ClassRunner.validateConstructor(BlockJUnit4ClassRunner.java:121)
    at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:101)
    at org.junit.runners.ParentRunner.validate(ParentRunner.java:344)
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:74)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
    at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:13)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runner.Computer.getRunner(Computer.java:38)
    at org.junit.runner.Computer$1.runnerForClass(Computer.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:98)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:84)
    at org.junit.runners.Suite.<init>(Suite.java:79)
    at org.junit.runner.Computer.getSuite(Computer.java:26)
    at org.junit.runner.Request.classes(Request.java:69)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
    at org.junit.runner.JUnitCore.runMain(JUnitCore.java:98)
    at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:53)
    at org.junit.runner.JUnitCore.main(JUnitCore.java:45)
2) initializationError(org.junit.runners.AllTests)
java.lang.Exception: No runnable methods
    at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:166)
    at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:102)
    at org.junit.runners.ParentRunner.validate(ParentRunner.java:344)
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:74)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
    at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:13)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runner.Computer.getRunner(Computer.java:38)
    at org.junit.runner.Computer$1.runnerForClass(Computer.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:98)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:84)
    at org.junit.runners.Suite.<init>(Suite.java:79)
    at org.junit.runner.Computer.getSuite(Computer.java:26)
    at org.junit.runner.Request.classes(Request.java:69)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
    at org.junit.runner.JUnitCore.runMain(JUnitCore.java:98)
    at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:53)
    at org.junit.runner.JUnitCore.main(JUnitCore.java:45)

FAILURES!!!
Tests run: 2,  Failures: 2

A: AllTests is for running JUnit 3.8 tests. If you look at the source code, you can see it doesn't extend TestCase (JUnit 3.8 style) or have @Test methods (JUnit 4.0 style.)  It also doesn't have a public no arguments constructor.  Which it doesn't need to because it isn't a class you can run as a unit test.
As Shengyuan notes, check the tests folder.  The AllTests class you found would be in the source folder which means you might be in the wrong folder looking for the actual sample tests.


text:
Q: Get state of ASP.NET page life cycle I need the following functionality in my method: if the method is called before OnLoad event of ASP.NET life cycle throw an exception else continue execution of the method.
I was thinking of something like this:
if (Page.LifeCycleState < LifeCycleState.OnLoad) {
    throw new InvalidPageStateException();
}

Is it possible to retrieve the state of ASP.NET page life cycle?

A: One approach would be to use a Basepage that you always use in your site. This would contain a variable called PageLoadComplete, which you would set at the end of your PageLoad event. Then you could check the state of this variable from within your method.
public abstract class BasePage : System.Web.UI.Page
{
    public bool PageLoadComplete { get; private set; }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        PageLoadComplete = true;
    }
}

If you want to access the variable from code external to your page such as a UserControl, you would have to make it public and cast your page as BasePage.
public partial class MyUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BasePage basePage = this.Page as BasePage;
        if (basePage != null && !basePage.PageLoadComplete)
        {
            throw new InvalidPageStateException();
        }
    }
}

A: There is property in a realization of System.Web.UI.Control class(realization):
    internal ControlState ControlState {
        get { return _controlState; }
        set { _controlState = value; }
    }

Where ControlState is enum that contains members such as: Initialized, ViewStateLoaded, Loaded etc. here declaration
But as you can see this property is internal. So only way to get control state is proposed by Daniel Dyson.

A: You maybe able to find what you are looking for, by looking at the CurrentHandler and PreviousHandler properties of the current HttpContext.

A:
if the method is called before OnLoad event of ASP.NET life cycle
  throw an exception else continue execution of the method.

It is not clear which Onload event is meant, nor where the "method" resides. Is it the Page's Onload or a Control's OnLoad? Is it a Page's "method" or a Control's "method"?
Anyway, one can store sort of flag in the Context.Items Dictionary, which all controls (including Page) have access to during a request. This eliminates the need to use a general base page like suggested obove.
In the OnLoad method (no matter whether it is a Page's OnLoad or a Control's OnLoad):
Context.Items[UniqueID] = this;

In the "method":
if (Context.Items[UniqueID] != null)
{
    throw new InvalidPageStateException();
}


text:
Q: Neither the property "password" nor one of the methods exists in twig/symfony I want to make reuse of the form field by passing show_password_field as true  in the optional value in AddUserType.php. My edit form field should not contain password field. So I have used this
if ($options['show_password_field']) {
      $builder->add('password','password',array('required'=>true));
    }

in form type. Can anybody figure it out? What is the problem in line 37 of twig file.

Neither the property "password" nor one of the methods "password()",
  "getpassword()"/"ispassword()" or "__call()" exist and have public
  access in class "Symfony\Component\Form\FormView" in
  SokosimuEditorBundle:User:addUser.html.twig at line 37.

AddUserType.php
   namespace Sokosimu\EditorBundle\Form\Type;

   use Symfony\Component\Form\AbstractType;
   use Symfony\Component\Form\FormBuilderInterface;
   use Symfony\Component\Form\Extension\Core\Type\SubmitType;
   use Symfony\Component\OptionsResolver\OptionsResolverInterface;

  class AddUserType extends AbstractType
  {

 public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $builder->add('alias','text',array('required'=>false));
    $builder->add('email', 'email',array('required'=>false));

    if ($options['show_password_field']) {
        $builder->add('password','password',array('required'=>true));
    }

    $builder->add('mobile','text',array('required'=>false));
    $builder->add('submit', 'submit');
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Sokosimu\UserBundle\Entity\User',
        'show_password_field' => true
    ));
}

/**
 * Returns the name of this type.
 *
 * @return string The name of this type
 */
 public function getName()
 {
     return 'adduser';
  }
}

And line 37 in addUser.html.twig

   Password:
   {{ form_widget(form.password,{'attr':{'class':'form-row'}}) }}
   {{ form_errors(form.password) }}

Controller that renders edit
public function editEditorUserAction(User $user,Request $request){

    $form = $this->createForm(new AddUserType(),$user,array(
        'show_password_field' => false));

    $form->handleRequest($request);
    if($form ->isValid() && $form->isSubmitted()){
        $em = $this->get('doctrine')->getManager();
        $editUser = $user ->getEditoruser();

        $em->persist($editUser);
        $em->flush();

        return $this->redirect($this->generateUrl('sokosimu_editor_userlist'));
    }

    return $this->render('SokosimuEditorBundle:User:addUser.html.twig', array(
        'form' => $form->createView(),
         'user' => $user->getId()
    ));
  }

A: You must check if form.password exists.
{% if form.password is defined %}

        Password:
        {{ form_widget(form.password,{'attr':{'class':'form-row'}}) }}
        {{ form_errors(form.password) }}

{% endif %}


text:
Q: How can we prove that this integral is zero? In solving another problem, I came across this observation that apparently:
$ \int_\mathbb{R} (\tanh(cx+c^2) -\tanh^2(cx+c^2)  ) e^{-\frac{x^2}{2}} dx = 0$.
It seems true (I have checked with numerical methods only) for any $c\in\mathbb{R}$, but I don't know if there is a way to prove it. In particular, as seen in the graph below, the function $(\tanh(cx+c^2) -\tanh^2(cx+c^2)  )$ is not odd (or does not seem to have any nice symmetry features that help simplify the integral.), as seen in the graph below for $c=1$.
One can write this integral as $\sqrt{2\pi} \mathbb{E}[\tanh(cX+c^2) -\tanh^2(cX+c^2)]$ where $X$ is standard-normally distributed.
Any idea is appreciated!

A: Note that $\cosh u-\sinh u=e^{-u}$ so $$(\cosh (c^2+cx)-\sinh (c^2+cx))e^{-x^2/2}=e^{-(c+x)^2/2}e^{-c^2/2}$$
Hence $$\int_\mathbb{R} (\tanh(cx+c^2) -\tanh^2(cx+c^2)) e^{-\frac{x^2}{2}}dx=$$ $$=\int_\mathbb{R}\frac{e^{-(c+x)^2/2}e^{-c^2/2}\sinh(cx+c^2)dx}{\cosh^2(cx+c^2)}$$
But now putting $c+x=y$ one gets that the integral above is:
$$e^{-c^2/2}\int_\mathbb{R}\frac{e^{-y^2/2}\sinh(cy)dy}{\cosh^2(cy)}=0$$ since the integrand is odd!


text:
Q: Command Line for Loop to Change Variables in File I have a script that compiles and runs a piece of idl code. Looks like this,
arg1=$1

idl << EOF
.rnew testvalue_{arg1}.pro
testvalue_{arg1}.pro
EOF

I want to run a for loop from the command line is in which arg1 can take on different names. What I have so far is,
for arg1 in testvalue.sh; do arg1={'value1', 'value2'}; done

I don't think my logic is correct. What am I missing?

A: first, you need to place $ before variable name so bash knows that it is replaced
Also you just need to give testvalue.sh value, because it is copied from $1 to $arg1
But why I don't recommend creating new variables, just use $1 two times
So the testvalue.sh is:
 idl << EOF
 .rnew testvalue_$1.pro
 testvalue_$1.pro

And the loop:
for arg in 'value1' 'value2'; do ./testvalue.sh $arg; done

A: I'm a little hazy on the exact details of the question, but it sounds like you want to put 'value1' and 'value2' inside the list of values the for-loop iterates:
for arg1 in value1 value2
do
    idl <<EOF
    .rnew testvalue_${arg1}.pro
    testvalue_${arg1}.pro
EOF
done

Note that I've also changed {arg1} to ${arg1}, as the dollar sign is required to expand the variable.
A for loop in shell scripts will iterate over every value after the in keyword. In the example above it will set arg1 to value1, then execute the contents of the loop, then move on and set arg1 to value2 and execute again.
You can also store the values in a variable:
values_to_test="value1 value2"

for arg1 in $values_to_test
do
    idl <<EOF
    .rnew testvalue_${arg1}.pro
    testvalue_${arg1}.pro
EOF
done

Bear in mind that this applies word splitting and path expansion to values_to_test, so you will need to ensure that none of the values contain question marks, square brackets, asterisks, spaces, tabs, or newlines.
If it worries you, you can disable path expansion (and thus allow use of question marks, square brackets and asterisks) by running set -f in the script before the loop runs.


text:
Q: Evaluate an expression and send the result to another program in Windows Batch I don't know how can i make this clear in a short sentence, so i give this example
Bash :
./foo $(ls -a)

First, "ls -a" is evaluated and converts to its output. So we 've got this line
./foo some_script Downloads

and then that's executed.
How can i achieve the same by using the windows command line?
P.S. : I need to use it when my IDE makes a build, so using PowerShell or CygWin is not an option

A: Assuming that the filenames contain no embedded spaces:
@echo off
setlocal enabledelayedexpansion

set "args="
for /f "delims=" %%i in ('dir /a /b') do set "args=!args!%%i "

.\foo %args%


text:
Q: Узнать позицию курсора относительно объекта UWP Есть UI объект на странице, как я могу на событие PointerEntered определить координаты мыши относительно этого объекта? Моя задача состоит в том, чтобы отобразить курсор изменения размера в правильном положении. я вроде получаю координаты объекта и мыши, но когда, как я думаю, навожу мышь в 0:0 и мой объект там же, то координаты разные
Мой метод
 private void Border_PointerEntered(object sender, PointerRoutedEventArgs e)
    {
        var border = sender as Border;
        var ct = (CompositeTransform)border.RenderTransform;
        var ttv = border.TransformToVisual(Window.Current.Content);
        var bordercoords = ttv.TransformPoint(new Point(0, 0));
        var borderHeight = border.ActualHeight+ct.ScaleY;
        var borderWidth = border.ActualWidth+ct.ScaleX;
        var mouseAbsoluteCoords = Window.Current.CoreWindow.PointerPosition;

        if (bordercoords.Y -3>=mouseAbsoluteCoords.Y || mouseAbsoluteCoords.Y <= bordercoords.Y+3 && mouseAbsoluteCoords.X > bordercoords.X + 10 && mouseAbsoluteCoords.X < borderWidth - 10)
        {
            Window.Current.CoreWindow.PointerCursor = bottomTopCursor;
        }
    }

Проверкой пытаюсь покрыть участок верхней границы, я себе представляю это так: когда курсор в синей зоне, активируется нужный курсор. Так же и для других областей

A: Сделайте там, где обозначено синим, невидимый элемент, и на нем сделайте изменение курсора как нужно при наведении. Тогда ничего высчитывать не придется.


text:
Q: Induction question: $P(n): 2 + 4 + ... + 2n = (n + 2)(n - 1)$ for any integer $n \ge 2$. I have to find an error in an induction exercise and I believe the error is in the basic step.
Here is what I have,
$P(n): 2 + 4 + ... + 2n = (n + 2)(n - 1)$ for any integer $n \ge 2$.
My steps:
$P(2): 2n = (n + 2)(n - 1) \implies 2(2) = (2 + 2)(2 - 1) \implies 4 = 4,$ which is true
$P(3): 2n = (n + 2)(n - 1) \implies 2(3) = (3 + 2)(3 - 1) \implies 6 = 10$, which is false. This is why I believe the basic step has an error. Is this correct?
Thanks

A: First, you are trying to prove an incorrect equation. Note that $$2 + 4 + \cdots + 2n = 2(1 + 2 + \cdots + n) = 2 \cdot \left(\dfrac{n(n+1)}{2}\right) = n(n+1)$$
So $P(n)$ should be $$P(n):\quad2 + 4 +\cdots + n = n(n+1)$$
Then, you need only one base case: $P(2): \quad 2 + 4 = (2)(2 + 1) = 6$.
Now, the inductive hypothesis we want to assume: Assume $P(k): 2 + 4 \cdots + 2k = k(k+1)$
The task then is to show that, given the base case and the inductive hypothesis, it follows that $$P(k+1): 2 + 4 + \cdots + 2k + 2(k+1) = (k+1)(k+2)$$ To do this, start from the left-hand side of $P(k+1)$ and use the inductive hypothesis to show that the right-hand side follows.


text:
Q: Using transform_lookup for an Altair choropleth figure For the life of me, I can't figure out how to use the transform_lookup method for a choropleth figure in Altair. I've put together an example. I'm simply trying to color the states based on the latitude of the state capital. Here is my code.
import pandas as pd
import altair as alt
from vega_datasets import data

states = alt.topo_feature(data.us_10m.url, feature='states')

state_abbr = pd.read_csv('https://worldpopulationreview.com/static/states/name-abbr.csv', names=['state', 'abbr'])
capitals = pd.read_csv('https://raw.githubusercontent.com/jasperdebie/VisInfo/master/us-state-capitals.csv')
capitals.columns = ['state', 'city', 'lat', 'lon']
capitals = pd.merge(capitals, state_abbr, how='left', on='state')

I think I need an "id" field in my dataframe. How is the id determined in the Vega dataset? I have tried sorting by state name or state abbreviation.
capitals = capitals.sort_values('abbr')
capitals['id'] = range(1, len(capitals) + 1)
print(capitals.head())

        state         city        lat         lon abbr  id
1      Alaska       Juneau  58.301598 -134.420212   AK   1
0     Alabama   Montgomery  32.377716  -86.300568   AL   2
3    Arkansas  Little Rock  34.746613  -92.288986   AR   3
2     Arizona      Phoenix  33.448143 -112.096962   AZ   4
4  California   Sacramento  38.576668 -121.493629   CA   5

And now the Altair code with the transform_lookup method.
base = alt.Chart(states).mark_geoshape(fill='lightgray', stroke='black', strokeWidth=0.5)

chart = alt.Chart(states).mark_geoshape(stroke='black').encode(
    color='lat:Q'
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(capitals, 'id', ['lat'])
).properties(
    width=500,
    height=300
).project('albersUsa')

base + chart

However, the figure is clearly wrong. The states should be colored darkest in the north and lightest in the south based on latitude. Also, some states with names later in the alphabet are missing data? I need help matching my Pandas dataframe with the Vega state dataset.

A: This comment on github was key. The id field in the us_10m dataset is based on their ANSI standardized code which can be found here.
Working code below.
import pandas as pd
import altair as alt
from vega_datasets import data

states = alt.topo_feature(data.us_10m.url, feature='states')

# per https://gist.github.com/mbostock/4090848#gistcomment-2102151
ansi = pd.read_csv('https://www2.census.gov/geo/docs/reference/state.txt', sep='|')
ansi.columns = ['id', 'abbr', 'state', 'statens']
ansi = ansi[['id', 'abbr', 'state']]

capitals = pd.read_csv('https://raw.githubusercontent.com/jasperdebie/VisInfo/master/us-state-capitals.csv')
capitals.columns = ['state', 'city', 'lat', 'lon']
capitals = pd.merge(capitals, ansi, how='left', on='state')

base = alt.Chart(states).mark_geoshape(fill='lightgray', stroke='black', strokeWidth=0.5)

chart = alt.Chart(states).mark_geoshape(stroke='black').encode(
    color='lat:Q'
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(capitals, 'id', ['lat'])
).properties(
    width=500,
    height=300
).project('albersUsa')

base + chart


text:
Q: selectManyCheckbox elements are not copying to array when items are checked Okay, I am not sure why it is saying that my target is not a collection or array because I am trying to put the results of a selectManyCheckbox into an integer array.  It is simply a checkbox of 1-50 where the user can select multiple numbers to be stored in an array and displayed later but I keep getting the error message  "Target model Type is no a Collection or Array" error reported.  Is this something that needs to be saved in an Object array instead of an integer array?  I know there are other threads dealing with this same issue but the others that I saw was generally someone using the wrong type of checkbox or someone not storing in an array or collection.  Any help would be really appreciated.

        Pick Your Lotto Numbers
        <h:selectManyCheckbox value="#{lottoBean.numbersPicked}"
                 layout="lineDirection">
        <f:selectItems value="#{lottoBean.numberChoices}"/>
        </h:selectManyCheckbox>

        <h:commandButton value="Submit"
                         action="next.xhtml"/>

And myLottoBean class...
int[]choices = new int[50];
int[]picked;
int[]actual;
int test = 5;

/**
 * Creates a new instance of LottoBean
 */
@SuppressWarnings("empty-statement")
public LottoBean() {
    picked = new int[6];
    actual = new int[6];
}

public void setNumbersPicked(int[] chosen)
{
    for(int i =0; i < 6; i++)
    {
        picked[i] = chosen[i];
    }
}

@SuppressWarnings("empty-statement")
public String getNumbersPicked()
{
    return Arrays.toString(picked);
}

public int[] getNumberChoices()
{
    for (int i = 0; i < 50; i++)
    {
        choices[i] = i + 1;
    }
    return choices;
}

public String getNumbersDrawn()
{
    Random num = new Random();
    for (int i = 0; i < 6; i++)
    {
        int nextNum = num.nextInt(50);
        int number  = nextNum + 1;
        actual[i] = number;
    }
    return Arrays.toString(actual);
}
}

A: You selectManyCheckobox value is #{lottoBean.numbersPicked}. This means that you should have property named numbersPicked which is Collection or Array. Example with array:
private int[] numbersPicked;

public int[] getNumberPicked() {
  return numbersPicked;
}

public void setNumberPicked(int[] numbersPicked) {
  this.numbersPicked = numbersPicked;
}

You should have this in your backing bean. Problem is that your getter method returns String.

A: I ended up using a LinkedHashMap, that way if I ever need something similar that uses anything other than integers it will be easy to plug items in.
public class LottoBean {

private Integer[] numbers;
private int[] actual = new int[6];
private Random generator;

private static Map<Integer,Integer> numbersName;

static
{
    numbersName = new LinkedHashMap<Integer,Integer>();
    for (int i = 1; i < 51; i++)
    {
        numbersName.put(i,i);
    }
}

/*
 * returns Integer array
 */
public Integer[] getNumbers()
{
    return numbers;
}

/*
 * Sets array to numbers picked
 */
public void setNumbers(Integer[] numbers)
{
    this.numbers = numbers;
}

/**
 * Returns map
 * @return numbersName
 */
public Map<Integer,Integer> getNumbersName()
{
    return numbersName;
}

/**
 * Returns the numbers array
 * @return the numbers array in string form
 */
public String getNumbersNameArray()
{
    return Arrays.toString(numbers);
}

/**
 * Generates numbers drawn
 * @return actual the numbers drawn
 */
public String getActualNumbersArray()
{

    for (int i = 0; i < 6; i++)
    {
        generator = new Random();
        int number = 1 + generator.nextInt(50);
        actual[i] = number;
    }
    return Arrays.toString(actual);
}

/**
 * Compares numbers picked to numbers drawn
 * @return the number of matching numbers
 */
public int getSame()
{
    int same = 0;
      for (int i = 0; i < numbers.length; i++)
      {
         for(int j = 0; j < actual.length; j++)
         {
            if (numbers[i] == actual[j])
            {
               same++;
            }
         }
      }
      return same;
}

}

index...

<title>Lotto Numbers</title>

<h:form>

    Pick six numbers from the list:

<h:selectManyCheckbox id="chkbox1" value="#{lottoNumbers.numbers}"
required="true" requiredMessage="check exactly six numbers"
layout="lineDirection" border="1" readonly="false">
<f:selectItems value="#{lottoNumbers.numbersName}"/>
</h:selectManyCheckbox>
<h:message for="chkbox1" style="color:red"/>

<h:commandButton value="submit" action="next" />
</h:form>

and next...

<title>Lotto Numbers</title>

<h:form>

    <h:outputText value="You have selected : #{lottoNumbers.numbersNameArray}" />

    <h:outputText value="Actual numbers    : #{lottoNumbers.actualNumbersArray}" />

    <h:inputText value="Matching numbers   : #{lottoNumbers.same}" />

</h:form>


text:
Q: Custom UserDetailsService Impl not being Called in SpringSecurity My Custom UserDetailsService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.fimd.entidades.Usuario;
import br.com.fimd.service.UsuarioService;

@Transactional(readOnly=true)
@Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService{

@Autowired
private UsuarioService usuarioService;

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    Usuario usuario = usuarioService.findUserByEmail(email);
    if(usuario == null) {
        throw new UsernameNotFoundException("Usuário nao encontrado.");
    }
    return new User(usuario.getEmail(), usuario.getSenha(), usuario.getAuthorities());
}

}
My Security Configuration
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier("userDetailsServiceImpl")
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.cors().disable().
    csrf().disable().authorizeRequests()
    .antMatchers("/home").permitAll()
    .antMatchers("/public/**").permitAll()
    .antMatchers("/private/**").hasRole("USER")
    //.antMatchers("/admin*").access("hasRole('ROLE_ADMIN')")
    .antMatchers("/admin/**").hasRole("ADMIN")
    .anyRequest().authenticated()
    .and()
    //.addFilterBefore(new JWTAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));

}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/assets/**");
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

}
My User Entity
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name = "usuarios")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class Usuario implements UserDetails, Serializable{

private static final long serialVersionUID = 4038437690572999966L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;

@NotBlank
private String nome;

@NotBlank
private String email;

@NotBlank
private String senha;

@NotBlank
private String cpf;

@Column
private boolean ativo;

@ManyToMany
 @JoinTable(name="perfil_usuario", joinColumns=
    {@JoinColumn(name="user_id")}, inverseJoinColumns=
    {@JoinColumn(name="tipo_perfil")})
private Set<Perfil> perfis = new HashSet<>();

@OneToMany(mappedBy = "usuario", cascade = CascadeType.ALL)
private List<Investimento> investimentos;

@OneToMany(mappedBy = "usuario", cascade = CascadeType.ALL)
private List<Extrato> extratos;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getCpf() {
    return cpf;
}

public void setCpf(String cpf) {
    this.cpf = cpf;
}

public static long getSerialversionuid() {
    return serialVersionUID;
}

public String getSenha() {
    return senha;
}

public void setSenha(String senha) {
    this.senha = senha;
}

public boolean isAtivo() {
    return ativo;
}

public void setAtivo(boolean ativo) {
    this.ativo = ativo;
}

public Set<Perfil> getPerfis() {
    return perfis;
}

public void setPerfis(Set<Perfil> perfis) {
    this.perfis = perfis;
}

public List<Investimento> getInvestimentos() {
    return investimentos;
}

public void setInvestimentos(List<Investimento> investimentos) {
    this.investimentos = investimentos;
}

public List<Extrato> getExtratos() {
    return extratos;
}

public void setExtratos(List<Extrato> extratos) {
    this.extratos = extratos;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return this.perfis;
}

@Override
public String getPassword() {
    return this.senha;
}

@Override
public String getUsername() {
    return this.email;
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}

}
My Perfil Entity
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import org.springframework.security.core.GrantedAuthority;

@Entity
public class Perfil implements GrantedAuthority{

private static final long serialVersionUID = 1L;

@Id
private String tipoPerfil;

@ManyToMany(mappedBy="perfis")
private List<Usuario> usuarios;

public List<Usuario> getUsuarios() {
    return usuarios;
}

public void setUsuarios(List<Usuario> usuarios) {
    this.usuarios = usuarios;
}

public String getTipoPerfil() {
    return tipoPerfil;
}

public void setTipoPerfil(String tipoPerfil) {
    this.tipoPerfil = tipoPerfil;
}

@Override
public String getAuthority() {
    return this.tipoPerfil;
}

}
My Spring Filter Initializer
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

@Configuration
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}

When i call a "/private/service" my loadUserByUsername not being called never, my application ever send me a 403 forbidden, access denied.
Why that?
I tried a lot of tutorials from internet and my code seems to be correct, i'm using spring starter 2.0.5.RELEASE
I already tried to call the userDetailsService from a @Bean method in SecurityConfiguration

A: Your security configuration is not complete, you must provide as well the login information:
.formLogin()
.loginPage("/login.html")
.defaultSuccessUrl("/home")
.failureUrl("/login.html?error=true")

Otherwise all your requests will be unauthorized. Please see this tutorial:

https://www.baeldung.com/spring-security-login

Your Custom UserDetails service will be called only when the application will receive a POST to login url with username and password, otherwise it will not have what data to authorize.


text:
Q: How to access to Google AppEngine Managed VM logs? I am trying out Managed VMs Beta from Google AppEngine and while it runs locally in my IDE with the AppEngine dev server, I cannot seem to make it run with mvn appengine:gcloud_app_run.
I consistently and forever get:
"[INFO] INFO: default: "GET /_ah/health?IsLastSuccessful=no HTTP/1.1" 503 298"

And thus need to access the logs outputted in the docker container to diagnose that 503.
I have activated logging with the following line in the appengine-maven-plugin configuration section (works great within the IDE).
<gcloud_app_enable_mvm_logs>true</gcloud_app_enable_mvm_logs>

Then I tried accessing the logs from the docker container with:
➜  ~  docker ps
CONTAINER ID        IMAGE                                                       COMMAND                CREATED             STATUS              PORTS                     NAMES
76369bc9b773        heimdall-dev.default.1:latest                               "/home/vmagent/jetty   5 seconds ago       Up 4 seconds        0.0.0.0:49174->8080/tcp   google.appengine.heimdall-dev.default.1.0.2014-11-13T210256.776274Z

➜  ~  docker logs 76369bc9b773
Info: Limiting Java heap size to: 1456M
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=64M; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=166M; support was removed in 8.0
2014-11-13 21:02:59.384:INFO::main: Logging initialized @372ms
2014-11-13 21:02:59.487:INFO::main: Redirecting stderr/stdout to /var/log/app_engine/STDERR.2014_11_13.log//var/log/app_engine/STDOUT.2014_11_13.log

So I expected the log files to be "magically" mapped to the local /var folder on my local machine (i.e. outside of the docker container`.
However it seems not to be it:
➜  ~  tail -f /var/log/app_engine/STDERR.2014_11_13.log
tail: /var/log/app_engine/STDERR.2014_11_13.log: No such file or directory
➜  ~  tail -f /var/log/app_engine/STDOUT.2014_11_13.log
tail: /var/log/app_engine/STDOUT.2014_11_13.log: No such file or directory

Is it the right way to do so? If yes, what am I missing? Else what is the right way to access the logs?
P.S.: I also tried ssh-ing into the docker container with docker attach 76369bc9b773 but this consistently returned me an error.
P.S.2: my app is a "basic" Spring MVC+Security+Social+DataJPA over Java 8, so I guess there is a glitch with the bean initialization that does not happen in IDE+GAE Dev Server somehow
P.S.3: I followed the tutorial here: https://github.com/GoogleCloudPlatform/appengine-java-vm-guestbook-extras and got stage 3 to run properly with mvn appengine:gcloud_app_run
P.S.4: to make my app run in the IDE, since I am using Spring MVC, I had to implement my own /_ah/start endpoint (inspired from Google App Engine Localhost Backend Error and No mapping found using Spring3 MVC + Maven2 on GAE) however I am unsure whether or not that is the right thing to do
P.S.5: I had a look at the admin console running on port 8000, and the logs there are just the same as the one in the shell (i.e. not much else than the HTTP 503 message)

A: I finally managed to access logs of the appengine VM using volumes of docker. And hacking a file of the google-cloud-sdk after browsing the python code.
However, since I am working on Mac OS X, some extra things where needed because of the VirtualBox layer in between the OS and docker, as described here: http://viget.com/extend/how-to-use-docker-on-os-x-the-missing-guide
So, below are the commands I ran.
1 - stop all docker containers if necessary:
➜  ~ docker stop $(docker ps -a -q)

2 - remove all docker containers if necessary:
➜  ~ docker rm $(docker ps -a -q)

3 - stop the boot2docker VirtualBox VM:
➜  ~ boot2docker down

4 - create the directory where you want it mapped on your local machine (make sure it is one where you have read/write permissions without needing to sudo):
➜  ~ mkdir -p ~/var/log/app_engine

5 - mount the directory into the boot2docker VirtualBox VM:
➜  ~ VBoxManage sharedfolder add boot2docker-vm -name var -hostpath ~/var/log/app_engine

6 - start the boot2docker VirtualBox VM:
➜  ~ boot2docker up

7 - edit line 266 of file google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/vm_runtime_proxy.py
265    external_logs_path = os.path.join(
266        '/var/log/app_engine',
267        self._escape_domain(

with the path to the sharedfolder, in my case:
265    external_logs_path = os.path.join(
266        '/Users/nicolas/var/log/app_engine',
267        self._escape_domain(

8 - run the app:
➜  ~ mvn appengine:gcloud_app_run

9 - check the logs are there:
➜  ~  ls ~/var/log/app_engine/heimdall-dev/default/1/0/
STDERR.2014_11_16.log   STDOUT.2014_11_16.log   app.0.log.json          app.0.log.json.1        app.0.log.json.1.lck    app.0.log.json.2        app.0.log.json.2.lck    app.0.log.json.lck      request.2014_11_16.log

Not exactly straightforward and easy...
It must be possible to make the default /var/mog/app_engine local folder available to the VirtualBox VM by changing the permissions and thus there would be no need to hack into google-cloud-sdk python files. However, I haven't had the time to test that yet. I'll update the answer when I get to test that.

A: Just as a completion to your initial answer @Nicolas, I've created a small shell script that will

*

*Builds the project

*Launch docker

*Launch a console that will show the latest logs

*Launch the gcloud preview app command

I'm sharing the .sh file with you now:
#!/bin/sh
mvn clean install   #build via MAVEN
boot2dockerstatus=$( boot2docker status )
echo $boot2dockerstatus
if [ $boot2dockerstatus != 'running' ]
    then
        boot2docker start
        boot2docker status
fi
open http://localhost:8080

#ADD logs debugging on a separate window (MacOSx only) !!
osascript -e 'tell app "Terminal"
    do script "cd /var/log/app_engine/; tail -F *.log"
end tell'

gcloud --verbosity debug preview app run --enable-mvm-logs "./target/<your-project-build-name-here>"


text:
Q: How to enable marshmallow-enum EnumField to correct serialize EnumField? When I try to serialize Python objects in JSON format using marshmallow and marshmallow-enum package AttributeError has been triggered - 'str' object has no attribute 'name'
I have the following classes linked with foreign keys:
class BusinessUnitsManagement(db.Model, DatabaseObject):
    __tablename__ = 'bu_mngmt'
    id = db.Column(db.Integer(), primary_key=True)
    bu_id = db.Column(db.Integer(), db.ForeignKey('business_units.id'), nullable=False)
    head = db.Column(db.Integer(), db.ForeignKey('user_properties.id'), nullable=True)

    bu_properties = db.relationship('BusinessUnits', foreign_keys=[bu_id], backref='bu_mngmt')
    head_properties = db.relationship('UserProperty', foreign_keys=[head])

class UserProperty(db.Model, DatabaseObject):
    __tablename__ = 'user_properties'
    id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
    seniority = db.Column(db.Enum(Seniority), nullable=True)

class BusinessUnits(db.Model):
    __tablename__ = 'business_units'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(5), nullable=False)
    description = db.Column(db.String(100), nullable=True)

And also, I create Schema classes for these above classes:
from marshmallow import Schema, fields
from marshmallow_enum import EnumField

class BusinessUnitsManagementSchema(Schema):
    id = fields.Int()
    bu_properties = fields.Nested(BusinessUnitsSchema)
    head_properties = fields.Nested(UserPropertySchema)

class UserPropertySchema(Schema):
    id = fields.Int()
    full_name = fields.Str()
    seniority = EnumField(Seniority)

class BusinessUnitsSchema(Schema):
    id = fields.Int()
    name = fields.Str()
    description = fields.Str()

Seniority is defined as:
Seniority = Enum(
    value='Seniority',
    names=[
        ('Intern', 'Intern'),
        ('Junior_Engineer', 'Junior_Engineer'),
        ('Junior Engineer', 'Junior Engineer'),

        ('Design Engineer', 'Design Engineer'),
        ('Design_Engineer', 'Design_Engineer'),

        ('Senior Engineer', 'Senior Engineer'),
        ('Senior_Engineer', 'Senior_Engineer')
    ]
)

When I try to get JSON format of Python objects:
from marshmallow import Schema, fields
from marshmallow_enum import EnumField

objects = BusinessUnitsManagement.query.join(BusinessUnits).all()
result = []
for object in objects:
    marshmallow_item = BusinessUnitsManagementSchema.dumps(object)
    result.append(marshmallow_item.data)
return result

I get this error on Ubuntu, but on Windows everything is ok:
marshmallow-enum version on both Win and Ubuntu --- 1.5.1
Python version on Win 10 ---------- 3.6.6
Python version on Ubuntu 16.04.3 -- 3.5.2

   marshmallow_item = schema.dumps(item)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/schema.py", line 557, in dumps
    deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/schema.py", line 509, in dump
    **kwargs
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 138, in serialize
    index=(index if index_errors else None)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 62, in call_and_store
    value = getter_func(data)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 132, in <lambda>
    getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/fields.py", line 252, in serialize
    return self._serialize(value, attr, obj)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/fields.py", line 450, in _serialize
    update_fields=not self.__updated_fields)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/schema.py", line 509, in dump
    **kwargs
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 138, in serialize
    index=(index if index_errors else None)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 62, in call_and_store
    value = getter_func(data)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 132, in <lambda>
    getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/fields.py", line 252, in serialize
    return self._serialize(value, attr, obj)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow_enum/__init__.py", line 80, in _serialize
    return value.name
AttributeError: 'str' object has no attribute 'name'

A: The problem is related to the database, more specifically the problem was with values for column 'seniority'. Some rows have 'seniority' set as blank (not NULL - just empty string), so that is the reason why serialization is not properly done. I don't know how that happened because the 'seniority' column is set as ENUM type.


text:
Q: node.js sequelize hasMany relations I have a question
there is a model file..
model/user.js
module.exports = {

  get: function () {

    //configuration database
    var database=require(""+appDir+"/config/database");

    //sequelize modul
    var Sequelize=require("sequelize");

    //set connection
    var connection = new Sequelize(database.database,database.user,database.password, {
      host: database.host,
      dialect: database.dialect,

      pool: {
        max: 5,
        min: 0,
        idle: 10000
      }
    });

    //table definition
    var User = connection.define('user', {
      firstName: {
        type: Sequelize.STRING
      },
      lastName: {
        type: Sequelize.STRING
      },

      status: {
        type: Sequelize.INTEGER
      }
    });

    //table definition
    var Tasks = connection.define('tasks', {
      taskname: {
        type: Sequelize.STRING
      },

      user_id: {
        type: Sequelize.INTEGER
      }
    });

    User.hasMany(Tasks, {foreignKey: 'user_id'});
    Tasks.belongsTo(User, {foreignKey: 'user_id'});

    return User;

  }
};

usage following code;
model file is called with require..
this code works without include attribute..but does not work with include attribute
//model call
var model=require("../model/user.js");

    model.sync().then(function()
          {
            model.find({include: [Task]}).then(function(user)
            {
              callback(user);
            })
              .catch(function(error)
              {
                callback(error);
              })
          });

but it does not work..I want to join two table..

A: You export only get function in model/user.js, but then you're trying to call sync function, that is not defined. First, try to get user model (Sequelize model), then call sync function of it:
var model = require("../model/user.js");
model.get().sync()


text:
Q: Effects of Mockito Mocks on Unit Tests When Refactoring If I use a mockito mock of an object being injected into the SUT as an argument, what happens if during refactoring the code is re-organized to call another non-mocked method of that same mock? My tests would fail and I'd have to go back and change my tests and set them up for this new call (the opposite of what I'd want to be doing when refactoring code)
If this is a common occurrence during refactoring, how can using mocks be of any use except for when mocking external, resource-intensive entities (network, db, etc.)?
I'm using mocks to mock out objects that would take hours to set up given my team seems to love monstrously deep aggregate objects.
Thanks!

A: You are correct that refactoring will likely break code that depends on mocks. Mockito doesn't know that method foo(int start, int end) and foo(int start) accomplish the same thing, and if you switch between them while refactoring, your Mockito mocks will very likely break. Mockito does provide reasonable defaults for unstubbed calls, like 0, null, or an empty list; however, many refactors will need more-realistic values.
In general, I've heard the tendency of a test or test fixture to fail when the system is behaving correctly called its "brittleness".
Part of this is derived by the choice of mocking framework: Mockito started life as a fork of EasyMock, where EasyMock will fail by default if there are either too many or too few calls, but Mockito will ignore unexpected calls and otherwise provide "nice" default behavior. The other part is determined by how you use the framework, where verifying unnecessary details (unimportant calls or parameters) may make mocks more brittle than they have to be.
Things Mockito is good at mocking:

*

*External, resource-intensive dependencies (or their wrappers).

*Interfaces. Very little can go wrong here.

*Small API surfaces. If your API surface has one or two methods, it's unlikely to catch the situation you're describing.

*Collaborators that don't exist yet, even if they have large API surfaces. Temporary brittle tests can be fixed later.

Things Mockito is not good for mocking:

*

*Very large API surfaces and DSLs. Imagine implementing a Builder pattern with Mockito! Prefer using the real object, or writing an in-memory fake or other test double.

*Stateful objects like databases and model objects. Fakes are definitely a better choice here, if the real objects won't do.

*Concrete classes you don't control. At that point, implementation details like choices of final start to sneak in. This might be a good reason to create a wrapper you do control.

*Anything with an existing and well-tested implementation. Why go through all that trouble and lose test fidelity when a real implementation is there?

It's worth saying that no test double will be perfectly safe; your system may cache, combine, delay, modify, or otherwise adjust interactions with its collaborators, and all of that can break pretty much any test double you write. The art of writing a flexible test is to rely on as few implementation details as possible, balancing the risk of brittleness against the requirement to thoroughly test the system and its interactions with the outside world.
All of that said, to directly answer the question "how can using mocks be of any use", see JB Nizet's great analogy here: If you're trying to create a bomb detonator, you probably want to test it, but the cost of using the real thing is simply too great. The difficulty involved (and the optimal choice of test double) will vary based on whether the bomb in question has a hundred little triggers, or a single boom() method.
For more details about test doubles (a category that includes mocks, fakes, and dummy objects) and their pros and cons, see Martin Fowler's article "Mocks aren't Stubs".

A: I would suggest that you only mock the bare minimum of what's needed.  Mockito has many facilities for doing this (spies, ability to return specific data/mocks when a method is invoked a certain way, etc.) but it ultimately comes down to having testable "seams" in your code.  If you haven't already, I would recommend reading Michael Feather's book Working Effectively with Legacy Code for many suggestions on how to do this.


text:
Q: Monogame 3.4 OpenGL Song: Specified stream is not a wave file I'm using latest stable Monogame vesion (3.4.0.456)
When i use the MonoGame OpenGL template in Visual Studio i get an exception when try to load a song (previously converted using Content Pipeline):
private Song mySong;
mySong = Content.Load<Song>("Sound/Music");

The exception thrown on says: "Specified stream is not a wave file"
I converted the Music.mp3 via Content Pipeline and have the Music.xnb and Music.m4a on my bin\Content\Music folder
The SoundEffectects plays correctly even in Monogame OpenGL template
The same code but using the Monogame Windows DirectX template runs fine.
Obiously i don't want convert my Music.mp3 to wav an use SoundEffect instead Song, because the final wav is too huge.
Note 1: Also tried with ogg and wma songs formats with the same result
Note 2: I also installed all stuff (Mono, Monogame and Monodevelop) on an Ubuntu Virtual Machie and the same code compile without exceptions but the song is not played (SoundEffects runs fine in Ubuntu Virtual Machine)


text:
Q: Issues with invalid syntax error in a url In my code Im trying to get the user to log in and retrive some information, but I get a syntax error with my variables user and password. bold print is commented out in code
import urllib.request
import time
import pycurl
#Log in
user = input('Please enter your EoBot.com email: ')
password = input('Please enter your password: ')
#gets user ID number
c = pycurl.Curl()
#Error below this line with "user" and "password"
c.setopt(c.URL, "https://www.eobot.com/api.aspx?email="user"&password="password")
c.perform()

A: You must escape double quotation character in string by doubling it(or by using single quotes also):
c.setopt(c.URL, "https://www.eobot.com/api.aspx?email=""user""&password=""password""")

but really it must be like this:
from urllib import parse

# ...
# your code
# ...

url = 'https://www.eobot.com/api.aspx?email={}&password={}'.format(parse.quote(user), parse.quote(password))
c.setopt(c.URL, url)

This service don't want from you to send quotes in uri. But special characters(like '@') must be url-encoded by 'quote' or 'urlencode' methods from 'urllib.parse' class

A: You need to escape your quotation marks inside the string, or use single quotes on the outside.
c.setopt(c.URL, 'https://www.eobot.com/api.aspx?email="user"&password="password"')

A: Nope. Start over.
import urllib.parse

 ...

qs = urllib.parse.urlencode((('email', user), ('password', password)))
url = urllib.parse.urlunparse(('https', 'www.eobot.com', 'api.aspx', '', qs, ''))
c.setopt(c.URL, url)


text:
Q: Count row and repeat the same rows within Loop I'm working on mansory gallery here images fetching into the row first row contains three images and then for the second row contains two images and so on.
Now currently all images coming inside same row. I want to add in a loop I had tried but unable to achieve the result. For inspiration link
<?php
  include('admin/config.php');
  $result = mysqli_query($db, "SELECT * FROM gallery order by id desc");
 // var_dump($result->num_rows);

 while ($row = mysqli_fetch_array($result)) {
   echo "
";
    echo "
";
        echo "";
            echo "";
        echo "";
    echo "
";
  echo "
";
  }
?>

Current output

Expected output

Can anyone suggest me how should i get this output.

A: Check below snippet,
$inc   = 4;
$i     = 1;
while ($row = mysqli_fetch_array($result)) {
    if (empty($temp) || $inc != $temp) {
        $temp = $inc;
        if ($inc == 4) {
            echo "
";
        }
        echo "
";
    }
    if ($i <= $inc) {
        // echo $i . '<>';
        echo "
";
        echo "";
        echo "";
        echo "";
        echo "
";
        $i++;
    }
    if ($i == $inc) {
        echo "
";
        if ($i == 3) {
            echo "
";
        }
        $i   = 1;
        $inc = ($inc == 4 ? 3 : 4);
    }
}


text:
Q: Why my animation speed increases every time I press the button? Here is a link: https://jsfiddle.net/danbogdan/Ltsxnude/6/
I am trying to make some animation that has 'blades', but every time I press the button the speed increases on that specific animation, or the next one!
I would like to increase or decrease the speed based on the option values! So after the user input the number of propellers, he can choose how many blades a propeller can have 2-8, and the speed. Now, every time I click the button in increases the speed of the current animation, and the next one if I choose a 3 blades propeller.

function propellersNumber() {
  var number = document.getElementById('noOfPropellers').value;
  var container = document.getElementById('container');
  while (container.hasChildNodes()) {
    container.removeChild(container.lastChild);
  }

  for (let i = 0; i < number; i++) {
    container.appendChild(document.createTextNode("Propeller " + (i + 1) + " number of blades: "));
    var input = document.createElement("input");
    input.id = "propeller" + i;
    input.type = "number";
    input.defaultValue = 2;
    input.min = 2;
    input.name = "propeller" + i;
    container.appendChild(input);
    container.appendChild(document.createElement('br'));
    container.appendChild(document.createTextNode("Propeller " + (i + 1) + " speed: "));
    var select = document.createElement('select');
    select.id = "innerSelect" + i;
    var option;
    var inputdata = "slow||medium||fast";
    inputdata.split('||').forEach(function(item) {
      option = document.createElement('option');
      option.value = option.textContent = item;
      select.appendChild(option);
    })
    container.appendChild(select);
    container.appendChild(document.createElement('br'));
  }
}

function switchBetween() {
  var numberPropellers = document.getElementById('noOfPropellers').value;
  var el = document.getElementById('propeller0');
  var result = el.value;
  var speed = document.getElementById('innerSelect0');
  var speedResult = speed.options[speed.selectedIndex].value;
  if (result == 2) {
    var canvas = document.getElementById("propellerOne");
    var ctx = canvas.getContext("2d");
    var angle = 0;
    if (speedResult == "slow") {
      angle = 2;
    } else if (speedResult == "medium") {
      angle = 6;
    } else if (speedResult == 'fast') {
      angle = 10;
    }

    requestAnimationFrame(animate);

    function animate() {
      requestAnimationFrame(animate);
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(canvas.width / 2, canvas.height / 2);
      ctx.stroke();
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(canvas.width, 0);
      ctx.lineTo(canvas.width / 2, canvas.height / 2);
      ctx.stroke();
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.rotate(Math.PI / 180 * angle);
      ctx.translate(-canvas.width / 2, -canvas.height / 2)

    }
  } else if (result == 3) {
    // 3 blades

  }

Input number of propellers

    <input type="number" id="noOfPropellers" name="propeller" min="0" value="0" id="propeller">
    <button onclick="propellersNumber()">Add</button>

    <button onclick="switchBetween()">Switch</button>

        <canvas class="propeller" id="propellerOne" height="120px"></canvas>


text:
Q: Ordering of Spring Security annotations If a method has multiple security annotations, in what order are they applied?
For example, is it the order in which the annotations are defined, or is it fixed such that e.g. SecuredAnnotationSecurityMetadataSource is always used before PrePostAnnotationSecurityMetadataSource?
Put another way, what is the evaluation order when calling these methods?
@Secured("ROLE_ADMIN")
@PreAuthorize("hasPermission(#target, 'read')")
void method1();

@PreAuthorize("hasPermission(#target, 'read')")
@Secured("ROLE_ADMIN")
void method2();

@PreAuthorize("hasRole('ADMIN') && hasPermission(#target, 'read')")
void method3();

@PreAuthorize("hasPermission(#target, 'read') && hasRole('ADMIN')")
void method4();

A: tl;dr: Mixing @Secured and @PreAuthorize does not work.
As detailed here, the method security interceptor stops once it has found the first supported annotation.
for (MethodSecurityMetadataSource s : methodSecurityMetadataSources) {
    attributes = s.getAttributes(method, targetClass);
    if (attributes != null && !attributes.isEmpty()) {
        break;
    }
}

it's intentional that DelegatingMethodSecurityMetadataSource only uses one source of metadata, the first which returns a non-null result

The ordering is @PreAuthorize ≻ @Secured ≻ @RolesAllowed. Therefore methods one and two in the question are actually equivalent to
@PreAuthorize("hasPermission(#target, 'read')")
void method();

i.e. the @Secured annotation is silently ignored.