text:
Q: Django MySQL group by day with timezone Lets say I have a sale model:
class Sale(models.Model):
    total = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    sale_date = models.DateTimeField(auto_now_add=True)

Now, with each sale sale_date get its value saved in UTC, so if I try to group and sum all the sales by day:
report = Sale.objects.extra({'day':"date(sale_date)"}).values('day').annotate(day_total=Sum('total'))

I get all wrong becouse I expect each day in a different timezone (UTC-6).
Is there a way to get the correct sums in a specific tiemezone? Im working with MySQL.

A: Ah, this was a good challenge. I was able to test from PostGres, and I can confirm it is working. The MySQL code should be pretty close. However, there is a note on the CONVERT_TZ documentation:

To use named time zones such as MET or Europe/Moscow, the time zone tables must be properly set up. See Section 10.6, "MySQL Server Time Zone Support", for instructions.

MySQL (using CONVERT_TZ(dt, from_tz, to_tz))
from_tz = 'UTC'
to_tz = 'Australia/ACT'
report = Sale.objects.extra(
    {
        'day': "date(CONVERT_TZ(sale_date, '{from_tz}', '{to_tz}'))".format(
            from_tz=from_tz,
            to_tz=to_tz
         )
    }
).values(
    'day'
).annotate(
    day_total=Sum('total')
)

PostGres: (using AT TIME ZONE)
time_zone = 'Australia/ACT'
report = Sale.objects.extra(
    {'day': "date(sale_date) AT TIME ZONE '{0}'".format(time_zone)}
).values(
    'day'
).annotate(
    day_total=Sum('total')
)


text:
Q: How to create item shadow in RadListView? How is it possible to achieve item shadows in a RadListView? To have a shadow of each item and the shadow is not stripped between the items or on the side paddings.

A: For Android:
XML:
<lv:RadListView xmlns:lv="nativescript-ui-listview" loaded="listLoaded">
    <lv:RadListView.itemTemplate>
        <StackLayout loaded="itemLoaded">
            ...
        </StackLayout>
    </lv:RadListView.itemTemplate>
</lv:RadListView>

JS:
function listLoaded(args) {
    var list = args.object;
    list.androidListView.setClipToPadding(false);
    list.androidListView.setClipChildren(false);
}

function itemLoaded(args) {
    var item = args.object;
    item.nativeView.setOutlineProvider(android.view.ViewOutlineProvider.BOUNDS);
    item.nativeView.setClipToOutline(false);
}

exports.listLoaded = listLoaded;
exports.itemloaded = itemLoaded;

This creates a nics unstripped shadow to every direction:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fullcalendar JS highlight the date that have event, click on that date will go to specific URL In the official example, the event shows like this:
https://fullcalendar.io/js/fullcalendar-3.5.0/demos/basic-views.html
It list every event in the calendar, and click on individual event will trigger the action.
However, I would like to customize a bit to :
Do not show any event,
but highlight the date which has event,
and click on that date go to the URL, e.g.
http://example.com/details?date=2017-09-10

Are there any option to change the layout like this? if not, then where to start the customize?
Thanks a lot for helping.

A: That is possible. You can easily hide events using CSS. Then, using a little jQuery, you can set a color on the date square and a data-url to be used on click.
See comments in this starter snippet.
Have fun!

$("#calendar").fullCalendar({
  events:[
    {title:"Test",
     start:"2017-09-14",
     end:"2017-09-14"
    },
    {title:"Test",
     start:"2017-09-22",
     end:"2017-09-22"
    },
    {title:"Test",
     start:"2017-10-13",
     end:"2017-09-22"
    },
    {title:"Test",
     start:"2017-10-22",
     end:"2017-09-22"
    }
  ],
  eventAfterAllRender : function(view) {

    //Loop through all event to set the highlight and onclick url
    $(".fc-event-container").each(function(){

      // Get this day of the week number
      var weekDayIndex = $(this).index();
      // Get the calendar row
      var row = $(this).closest(".fc-row");
      // Get this date
      var date = row.find(".fc-day-top").eq(weekDayIndex).attr("data-date");
      // Add highlight and data-date
      row.find(".fc-day").eq(weekDayIndex)
        .addClass("highlight")
        .attr("data-url","example.com/details?date="+date);
    });
  }
});

// Click handler
$(document).on("click", ".highlight", function(){
  alert( $(this).data("url") );
});
.fc-event-container{
  display:none;
}
.highlight{
  background-color:red;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.5.0/fullcalendar.css" rel="stylesheet"/>


text:
Q: How to publish a silverlight application I want to publish my silverlight application with my WCFweb service.
Can somebody please give me a step by step process

A: Here is a complete tutorial : http://www.silverlight.net/learn/tutorials/silverlight-4/web-services-and-silverlight/


text:
Q: Automating screenshot workflow I am looking for a way to launch Preview on my Mac automatically, whenever I take a screenshot to my clipboard. I use "cmd + shift + 4" most of the times, then open preview, then hit "cmd+n" which accomplishes what I'm after, but is just time-consuming.
I have looked around but haven't found an option to do this with Automator. I'm not sure if it's even possible that Automator 'monitors' the clipboard and whenever it receives a screenshot, could trigger Preview.
Any help is much appreciated!

A: If you open /System/Applications/Utilities/Screenshot.app, you will be given the option to choose where your screenshot goes.    You can select for the screenshot to automatically open in Preview.

Now anytime you use your keyboard shortcuts to take a screenshot,  the default action would be to open the screenshot in Preview.


text:
Q: how to get more than 100 rows in my jtable? how to make Jtable read more than 100 rows?

I need to know how I can make a next and previous button for my Jtable to get data from the text file.
the code that I've made can only read the first 100 lines from my file.

the code of my button that I use to refresh my Jtable is
 try {
        for (int r = 0; r < 100; r++) { //initializing row
            for (int c = 0; c < 4; c++) { //initializing column
                jTable1.setValueAt(null, r, c);
            }
        }

        BufferedReader rdfile = new BufferedReader(new FileReader("items.txt"));

        String[] item = new String[100];
        String[] temp;

        int x = 0;  //read item
        while ((item[x] = rdfile.readLine()) != null) {
            temp = item[x].split("\t");
            jTable1.setValueAt((1000 + x + 1), x, 0);
            for (int j = 1; j < 4; j++) {
                jTable1.setValueAt(temp[j - 1], x, j);
            }

            x++;
        }
        rdfile.close();

    } catch (IOException e) {
    }

I want to make a "next" button to view the next 100 data from the file

look at the limit " I have more than 400 items and it shows only 100

these are the imports i've used
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

please explain as if i'm a dummy in java

A: Add your data in a DefaultTableModel then set it as the model for the JTable.

A: I am not sure if this is what you mean but you can create a variable that holds the number of the page.
    int page = 1;
    for (int r = 0; r < 100 * page; r++) { //initializing row
        for (int c = 0; c < 4; c++) { //initializing column
            jTable1.setValueAt(null, r, c);
        }
    }

by pressing the button you could increment or decrement the page so page would render the next page.


text:
Q: How to use Jenkins Build Keeper Plugin I would like to use the Jenkins 'Build Keeper Plugin' but I don't know how. The plugin site doesn't describe how to use it. Plugin Site
On this page I found the extension points which I would like to use, e.g. the org.jenkins_ci.plugins.build_keeper.KeepFirstFailedPolicy
But in the configuration part of my project, I can't find any place to configure it to use that policy. So where do I have to add it?
Jenkins version is 1.544

A: Have you tried to open Job configuration page and look for settings ?
For example it is another plugin but it is very similar : Build Discard plugin, may be you will use it for your purposes:
Build discard old build settings

A: You can configure it in the job under the section Build Environment.
For screenshots see also https://issues.jenkins-ci.org/browse/JENKINS-25293

A: If used from within a pipeline, it is enough to write
'currentBuild.rawBuild.keepLog(true)'
That is unfortunately not an interface to the plugin, just a jobs setting, but can solve it when You want to keep all builds, or decide within the build if to keep it.


text:
Q: Javascript code not working from Applescript? I've started learning Applescript - and know no JavaScript - and am having problems getting this code to work.
I'm trying to get open a webpage in Safari and once the page has finished loading, execute some javascript against it.
The javascript is copied from a bookmarklet - when I use the bookmarklet button, the javascript works as expected. However when running my Applescript, it returns a "missing value" error and does nothing to the webpage.
Here is the Applescript:
set makeReadable to "javascript:(function()%7B_readableOptions=%7B'text_font':'quote(Palatino Linotype), Palatino, quote(Book Antigua), Georgia, serif','text_font_monospace':'quote(Courier New), Courier, monospace','text_font_header':'quote(Times New Roman), Times, serif','text_size':'14px','text_line_height':'1.5','box_width':'30em','color_text':'%23282828','color_background':'%23F5F5F5','color_links':'%230000FF','text_align':'normal','base':'blueprint','custom_css':''%7D;if(document.getElementsByTagName('body').length>0);else%7Breturn;%7Dif(window.$readable)%7Bif(window.$readable.bookmarkletTimer)%7Breturn;%7D%7Delse%7Bwindow.$readable=%7B%7D;%7Dwindow.$readable.bookmarkletTimer=true;window.$readable.options=_readableOptions;if(window.$readable.bookmarkletClicked)%7Bwindow.$readable.bookmarkletClicked();return;%7D_readableScript=document.createElement('script');_readableScript.setAttribute('src','http://readable-static.tastefulwords.com/target.js?rand='+encodeURIComponent(Math.random()));document.getElementsByTagName('body')%5B0%5D.appendChild(_readableScript);%7D)();"

tell application "Safari"
set theURL to "http://en.wikipedia.org/wiki/Rocky"
open location theURL
delay 20

set SelectedPage to document of window 1
do JavaScript makeReadable in SelectedPage
delay 15
end tell

Any assistance greatly appreciated!

A: You cannot just paste a bookmarklet (which is an executable URL) into a do JavaScript
I have no experience with AppleScript, but try
set makeReadable to "(function(){_readableOptions={'text_font':'quote(Palatino Linotype), Palatino, quote(Book Antigua), Georgia, serif','text_font_monospace':'quote(Courier New), Courier, monospace','text_font_header':'quote(Times New Roman), Times, serif','text_size':'14px','text_line_height':'1.5','box_width':'30em','color_text':'#282828','color_background':'#F5F5F5','color_links':'#0000FF','text_align':'normal','base':'blueprint','custom_css':''};if(document.getElementsByTagName('body').length>0);else{return;}if(window.$readable){if(window.$readable.bookmarkletTimer){return;}}else{window.$readable={};}window.$readable.bookmarkletTimer=true;window.$readable.options=_readableOptions;if(window.$readable.bookmarkletClicked){window.$readable.bookmarkletClicked();return;}_readableScript=document.createElement('script');_readableScript.setAttribute('src','http://readable-static.tastefulwords.com/target.js?rand='+encodeURIComponent(Math.random()));document.getElementsByTagName('body')[0].appendChild(_readableScript);})();"


text:
Q: Core game logic loop to send data to channels in Netty I want to send world state every 100 msec to all channels. But it calls only once.
My code:
        public class IncomeMessageTcpHandler extends SimpleChannelInboundHandler<byte[]> {

@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        channel.eventLoop().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("send");
                channel.writeAndFlush(GameLogic.Instance.flushMessageData());
            }
        }, 100, 100, TimeUnit.MILLISECONDS);
    }
}

Now the method call only once.
I use 4.1.13.Final
    public class UnityServerTcpChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();

        p.addLast("frameDecoder", new FixedLengthFrameDecoder(6));
        p.addLast("bytesDecoder", new ByteArrayDecoder());

        p.addLast("bytesEncoder", new ByteArrayEncoder());

        p.addLast(new IncomeMessageTcpHandler());
    }
}

When I comment channel.writeAndFlush(GameLogic.Instance.flushMessageData());  task run every 100 msec

A: Omg... my fault.
My method GameLogic.Instance.flushMessageData() generates NullPointerException but I did not know that Runnable do not throw any exception.
That's why it stops running without any warn


text:
Q: How to write the Backand Code for an Android App For AWS my boss has told me to shift all works to the AWS, and I'M facing a lot of problem in gathering information from web.
If anyone can help me out from this trap, it would be very helpful.
I have an Android App(Feedback app), Whenever a person gives feedback the result should store in AWS database.
Q1: What services do i need to use for the whole process
Q2: Where did i need to write the codes for this.

A: There are a number of database services on AWS, and the one you choose depends on your use case and application design. You might want to consider RDS or DynamoDB, and should research both to see which meets your needs. For DynamoDB you can use the AWS SDK for Android. Take a look at the DynamoDB section for instructions on getting started


text:
Q: transformation changing basis Let $T:R^3->R^3 $ be defined by $T(a_1,a_2,a_3)=(3a_1+a_2,a_1+a_3,a_1-a_3)
$
so here first i do transformation to the bases $T \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}=\begin{pmatrix}3\\1\\1\end{pmatrix}$, $T \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}=\begin{pmatrix}1\\0\\0\end{pmatrix}$ , $T \begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix}=\begin{pmatrix}0\\1\\-1\end{pmatrix}$
then express it as linear combination of standard basis and find coordinate respect to it such as $T \begin{pmatrix} 3 \\ 1 \\ 1 \end{pmatrix}=a_1\begin{pmatrix}1\\0\\0\end{pmatrix}+a_2  \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}+a_3 \begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix}$ and do it for three of them then got the coefficient for $a_1,a_2,a_2$
this matrix with respect to standard basis is $A=\begin{bmatrix}3&1&0\\1&0&1\\1&0&-1\end{bmatrix}$
is this the right idea behind with respect to standard basis?
suppose we choose as a basis $V=R^3$ set  ${\begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}, \begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix},  \begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix}}$
the matrix representation of T with respect to this basis is? so if I'm doing the same thing as above such as transform, $T \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}=\begin{pmatrix}3\\1\\1\end{pmatrix}$, $T \begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix}=\begin{pmatrix}4\\1\\1\end{pmatrix}$, $T \begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix}=\begin{pmatrix}4\\2\\0\end{pmatrix}$ and it turns out this is the matrix

A=\begin{bmatrix}3&4&4\\1&1&2\\1&1&0\end{bmatrix}
but why can t i represent the transformation as linear combination of basis b?
$\begin{pmatrix}3\\1\\1\end{pmatrix}=a_1{\begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}+a_2\begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix}+a_3  \begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix}}$ for matrix column? i got different answer
but i know also the detour way $V^{-1}AV$

A: For $A$ in the standard basis you are correct.
The matrix $\bar A$ in the new basis is given by $V^{-1}AV$ where $V$ is the matrix which has for columns the vectors of the new basis. Can you see why and how it works?
Simply note that matrix $V$ changes the coordinates from the new basis to the standard and $V^{-1}$ changes the coordinates from standard to the new basis.
Then we have

*

*$w=Av$

*$v=V\bar v \qquad w=V\bar w$

and then
$$w=V\bar w=Av=AV\bar v\iff \bar w=V^{-1}AV\bar v$$
that is
$$\begin{bmatrix}1&-1&0\\0&1&-1\\0&0&1\end{bmatrix}\begin{bmatrix}3&1&0\\1&0&1\\1&0&-1\end{bmatrix}\begin{bmatrix}1&1&1\\0&1&1\\0&0&1\end{bmatrix}=\begin{bmatrix}2&3&2\\0&0&2\\1&1&0\end{bmatrix}$$
To obtain the result with a different method note that if we indicate with
$$u={\begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}, v=\begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix},  w=\begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix}}$$
the vectors of the new basis, we need first to find the expression of the vectors of the standard basis in term of the new basis vectors that is

*

*$e_1=u$

*$e_2=-u+v$

*$e_3=-v+w$

Then we need to find the expression for $T(e_1)$, $T(e_2)$, $T(e_3)$ with respect to the new basis that is

*

*$a_1u+a_2v+a_3w=T(e_1)=(3,1,1)\implies (a_1,a_2,a_3)=(2,0,1)$

*$b_1u+b_2v+b_3w=T(e_2)=(1,0,0)\implies (b_1,b_2,b_3)=(1,0,0)$

*$c_1u+c_2v+c_3w=T(e_3)=(0,1,-1)\implies (c_1,c_2,c_3)=(-1,2,-1)$

Then for the transformation in the new basis we know that

*

*$T(e_1)=T(u)=2u+w$

*$T(e_2)=T(-u+v)=-T(u)+T(v)=u$

*$T(e_3)=T(-v+w)=-T(v)+T(w)=-u+2v-w$

from wich we obtain

*

*$T(u)=2u+w$

*$T(v)=3u+w$

*$T(w)=2u+2v$

which leads to the same result.


text:
Q: Is the 3.5mm audio jack socket on the Fujitsu Siemens 23 3230T monitor a line in or a line out? I have a Fujitsu Siemens 3230T monitor, which offers HDMI input and can play sound, albeit badly, over internal speakers. There is also a 3.5 audio jacket that I thought was to direct the sound from the HDMI signal through to an external sound system.
As I have trouble getting sound to play over the external sound system (not understanding the menu structure), it leads me to suspect that it is not a line out but a line in audio jacket, so that one could play sound over the monitor's inferior internal speaker from an external source.
I am lacking a 3.5 to 3.5 cable so I cannot test myself to be sure.
Can somebody clear up if the monitor has a line in or a line out?

A: This is the 3.5mm audio line in connector.
Video signal connections: 2 x HDMI (one 1.3 and one HDCP compliant), 1 x D-SUB
Audio:
Audio input 3.5mm stereo jack
Speakers: 2 x 1.5 W(sinus)/2x2W(music)

A: The 3.5 is used for line in only.


text:
Q: Different results between Android Geocoder and Google Geocoding web service I am creating an Android application and I need to use the geolocation.
I have started by using the Geocoder API from Android (android.location.geocoder) but it causes some issues (timed out waiting for response from server) which seems to be common according to what I have read.
To make my application work when this kind of error occurs, I use the Geocoding web service.
Now, the application works every time. The problem is that the results returned by the geocoder from API and the geocoder from the web service are not the same.
For example the web service returns only 3 addresses with only city name and country whereas the geocoding from the API returns about 8 addresses with the feature name, the thoroughfare, the locality...
The question is: is there a way to make the results from the web service exactly the same than the ones from the API?
EDIT
Here is my MainGeocoder class:
public class MainGeocoder {

    private Geocoder geocoderAPI;
    private GeocoderRest geocoderRest;

    public MainGeocoder(Context context) {
        geocoderAPI = new Geocoder(context);
        geocoderRest = new GeocoderRest(context);
    }

    public List<Address> getFromLocationName(String search, int maxResults) {
        List<Address> addresses;
        try {
            addresses = geocoderAPI.getFromLocationName(search, maxResults);
            return addresses;
        } catch (IOException e) {
            e.printStackTrace();
            try {
                addresses = geocoderRest.getFromLocationName(search, maxResults);
                return addresses;
            } catch (IOException e1) {
                return null;
            } catch (LimitExceededException e1) {
                return null;
            }
        }
    }
}

It basically tries to get the list of addresses from the API Geocoder. If an IO exception is thrown it gets this list from the web service by using the GeocoderRest class which has been pasted from here: https://stackoverflow.com/a/15117087/3571822

A:
Is there a way to make the results from the web service exactly the
  same than the ones from the API?

Simply no. In the majority of attempts there will always be a difference between these two geocoders. Because the android.location.Geocoder uses a Service internally, which you can't track down in the source code, you will never now where exactly the difference is, but asking Google. And I don't think they will give this info away.
Btw, the GeocoderRest class you use doesn't parse even the half of the info contained in the response. Usually the web service is much more reliable as the API in the SDK.


text:
Q: Problem removing iSCSI target from ESXi 4.0 host I am new when it comes to working with ESXi 4.0 and connecting to iSCSI devices.
I have a "Lacie 5big Network 2" drive which is setup with RAID 5 and and 3.6TB of available space.  Using instructions from " http://www.techhead.co.uk/vmware-esxi-4-0-vsphere-connecting-to-an-iscsi-storage-target " I was able to add the device to the ESXi host.  Unfortunately it was only allowing me to use 1TB out of the 3TB which was dedicated to iSCSI.  I have no idea why.  This is another problem that I'm facing.
So I went ahead and removed the iSCSI drive from the ESXi host but I'm now running into problems.  I am unable to reconfigure the Lacie iSCSI drive size because it displays the following message: "iSCSI not available while a computer is connected to the target"
Since I've undone all the changes from within VMware vSphere Client, what else is left for me to do?  Is there a file within ESXi that I could edit to clear this issue?
Thanks in advance to anyone who could help me resolve this issue.  If I'm not clear about anything that I've mentioned here please let me know and I'll clarify with more information.

A: I don't understand why you're only able to use 1TB but I suspect it's due to ESX/i's 2TB-per-LUN limit - basically you can't have a single VMFS extent larger than 2TB nor can it address a larger than 2TB LUN properly - carve your iSCSI LUNs into <2TB and try that again.
As for the problem you face, well if ESXi doesn't 'see' it then you're safe to do what you like from the LaCie perspective - i.e. reboot it as it appears to still be locked. This may just be an incompatibility issue, no LaCie storage products are on the VMWare Hardware Compatibility List I'm afraid.


text:
Q: Builder patterns and generic type that extends itself I am trying to implement Builder pattern with inheritance and found the following solution .
This is B class:
public class B extends A {
    public static abstract class Builder<T extends Builder<T>>
        extends A.Builder<T> {

        @Override
        public abstract T getThis();

        public Builder Bmethod() {
            //implementation
            return this;
        }

        public B build() {
            return new B(this);
        }
    }

    private B(Builder builder) {
        super(builder);
        //B field assignment
    }
}

Now I want to make class C also extendable. This is the way I do it:
public class C extends B {
    ...
    public static class Builder<T extends Builder<T>> extends B.Builder<T> {
        ....
    }
}

So, in C we have builder that can be extended in, for example, D. My question is what is the right way to create C.Builder instance. I mean, what should I set in its generics:
C.Builder<WHAT HERE> builder = new C.Builder<>();

A: Since the argument T for C.Builder must be something that extends C.Builder you must create another class that extends C.Builder, as you cannot use C.Builder itself as it is parameterized.
A solution therefore for inherited builders is to create two builders, one which is generic, extensible, protected and abstract, and another one that is public, final and not generic used for the actual building.
Here are sample classes that show this:
public class Person {
  private final String name;

  public Person(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  protected static abstract class ExtensiblePersonBuilder<S, T extends Person> {
    protected String name;

    public S name(String name) {
      this.name = name;
      return self();
    }

    public abstract S self();
    public abstract T build();
  }

  public static final class PersonBuilder extends ExtensiblePersonBuilder<PersonBuilder, Person> {
    @Override
    public PersonBuilder self() {
      return this;
    }

    @Override
    public Person build() {
      return new Person(name);
    }
  }
}

And a subclass, with builder:
  public class Employee extends Person {
    private int number;

    public Employee(String name, int number) {
      super(name);

      this.number = number;
    }

    protected static abstract class ExtensibleEmployeeBuilder<S, T extends Employee> extends ExtensiblePersonBuilder<S, T> {
      protected int number;

      public S number(int number) {
        this.number = number;
        return self();
      }
    }

    public static final class EmployeeBuilder extends ExtensibleEmployeeBuilder<EmployeeBuilder, Employee> {

      @Override
      public EmployeeBuilder self() {
        return this;
      }

      @Override
      public Employee build() {
        return new Employee(name, number);
      }
    }
  }

And a sub sub class:
public class Manager extends Employee {
  private String teamName;

  public Manager(String name, int number, String teamName) {
    super(name, number);

    this.teamName = teamName;
  }

  protected static abstract class ExtensibleManagerBuilder<S, T extends Manager> extends ExtensibleEmployeeBuilder<S, T> {
    protected String teamName;

    public S teamName(String teamName) {
      this.teamName = teamName;
      return self();
    }
  }

  public static final class ManagerBuilder extends ExtensibleManagerBuilder<ManagerBuilder, Manager> {
    @Override
    public ManagerBuilder self() {
      return this;
    }

    @Override
    public Manager build() {
      return new Manager(name, number, teamName);
    }
  }
}

You can use these builders like this:
Person p = new PersonBuilder().name("John").build();

or:
Manager m = new ManagerBuilder().name("Jeff").teamName("X").number(2).build();


text:
Q: How to Create and Add Stickers and Smiley's In You Own Application I have made an Android IM Application, and I'm trying to add some stickers and smileys to it, but after lots of searching, seems there is no training about it and where to Start.
I imagine it's a pain or PNG that is added to the TextView right? Can someone please put me in the right way? Even if I just know What "type" are they (png, paint, canvas, etc...), I could make my own way.

A: Maybe make java add an image view with the image in your drawable folder. Don't know how this would work but try somthing.


text:
Q: Problem with accessing database in windows 7 MS Visual Studio I developed a small application which accesses a MS access database on my computer using VB.net. I developed the program on windows xp 32 bit. At the moment I am using windows 7 64 bit and the program simply will not run. I get a null reference exception when I try to do anything to the database. I have narrowed this down i THINK to the db provider. I was using Provider=Microsoft.Jet.OLEDB.4.0; and tried using Provider=Microsoft.ACE.OLEDB.12.0;. Neither seems to work. The path to my database is 100% correct. This is the error I am getting:
Null reference exception was unhandled.
Object reference not set to an instance of an object.
Like I say the program runs fine on the windows xp machine. If it helps the access database file extension is mdb.

A: No DLL exist for 64 bit access to Access database files so you must go to the project properties and on the "Compile" tab go to "Advanced Compile Options" and set "Target CPU" to "x86" I hope this helps.

A: I was having the exact same problem, except writing to a SQL 2008 DB. VS2008, VB.net code with framework 3.5, Windows 7 64-bit. Code runs fine on XP.
John R's answer provided the right solution: changing the project's advanced compile options to set "Target CPU" to "x86".
This problem can have more symptoms than originally described. I'll generalize them:
Accessing ACCESS isn't the only problem; it happens with SQL (at least MS SQL 2008) too.
Some of the DB calls can and do work. It's as if the calls set you up for failure, but the point of failure happens later, at a random point in your program.
The point of failure I saw was during a subroutine call. (just a normal call to a subroutine I created in VB.) Putting a try-catch block around the call wouldn't catch the error though.
Here's the strangest part: Previous to the errant subroutine call, the code had a HANDLED exception. Ironically, the exception was EXACTLY what was being thrown at the errant call. When I "tweaked" the code to avoid the prior exception, NO exception was thrown at the errant call; the VB program JUST QUIT WITH NO ERROR! It appears that whatever code is having the problem, it is reusing the last handled exception. This would mean that if your code previously had an "index out of bounds" or "divide by 0" error, this is what you'd (probably) see when the code barfs (because of no 64-bit dll.) So this problem can masquerade as a whole bunch of errors!

A: Doesn't sound like a Provider error because the Jet part is fine. Make sure your Data Source path is correct. If you have it in your Projects folder on VS and are using a full path it may need to change because of how the file system is set up with Users vs Documents and Settings.


text:
Q: Internet Dongle Help Ubuntu 12.04 I have a 3Gmobile broadband dongle that is supposed to go on windows XP, Vista, and 7. Is there any way i can use this dongle for ubuntu 12.04? Model #- SCT-UM300

A: As I understand you need to install usb-modeswitch and usb-modeswitch-data packages, and to do that you have to use your Ubuntu CD/DVD as a repository, meaning you have to add it to the Software Sources list. Unless you also have a wired connection and you can already use the Internet. Anyway, you have to type this code in terminal:
  sudo apt-get install usb-modeswitch usb-modeswitch-data

Those 2 packages should be already present on your system and you may get a message in the terminal saying that they are installed but if they are not you need them.
Next step is to visit this page to learn how to setup a 3g connection using ubuntu network manager. I hope this helps because I am no expert in this kind of problems but I thought you can find a solution following the instructions from the link I gave you.
The intructions are targeted to people living in the UK, so you should choose your own location and all the other required data.


text:
Q: Validate input field to display another input field on the same page using spring 3.0
I have page on web flow which has a password input field once the user finishes entering password i need to validate the password if it is right then display email id input field on the same page.
How can i achieve this in flow?
Thanks

A: Your example is a page that has a conditionally displayed element. The easiest way to do this, if you are not using ajax, is to create 2 pages (called page1 and page2).  Page1 has only the password field.  Page2 has both the password field and the email field.  After the user submits page1, if the password has been validated, transition to the view-state that displays page2.  After the user submits page1, if the password is not valid, transition to the view-state that displays page1.
Dont flame me bro, this is an answer targeted at the percieved level of the questioner's experience (new).


text:
Q: Uniform convergence and bounded increasing function. I have $0 \le f_n(x) \le 1$ and $f_n(x)$ is increasing on $\Bbb R$.
 I think I can say $f_n(x)$ converges.
Then I am not sure if it means $f_n(x)$ converges in a both way.
 I eventually need to show that there is a subsequence that converges in $Q$. What am I missing or thinking wrong?


text:
Q: Javascript json data read problem for double quote I'm passing json data to javascript of Google Chart.
My json data format is
["Md. Aslam",170972.7,"gold"]

But in google chart javascript shows like
["JIANGSU LTD",170972.7,"gold"]

Here is showing " in respect of "
I need this data with " as I have given. How do I solve this?
My Controller (sending from data):
def data1 = table.executeQuery("select name, point from table") as JSON
render(view: "/report", model: [data1: data1])

My report.gsp (view of google chart):
<script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawVisualization);

        function drawVisualization() {
            google.charts.load("current", {packages:['corechart']});
            google.charts.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    [ 'Element', "Density", { role: "style" } ],
                    ${data1}
                ]);

                var view = new google.visualization.DataView(data);
                view.setColumns([0, 1,
                    { calc: "stringify",
                        sourceColumn: 1,
                        type: "string",
                        role: "annotation" },
                    2]);

                var options = {
                    title: "Density of Precious Metals, in g/cm^3",
                    width: 600,
                    height: 400,
                    bar: {groupWidth: "95%"},
                    legend: { position: "none" },
                };
                var chart = new google.visualization.ColumnChart(document.getElementById("ord_variation"));
                chart.draw(view, options);
        }}
    </script>

I'm using groovy/grails 3

A: Finally I got my solution as report.gsp
<g:applyCodec encodeAs="none">
    ${data1};
</g:applyCodec>

A: Change your code like below:
<script type="text/javascript">

var j = "${data}"; // data is your json data came from controller
    var result = JSON.parse((j.split(""").join('"')).split("=").join(':')); //use result object

</script>

Hope this will helps you


text:
Q: Caesar Cipher in Python: remove spaces in a list I'm working on a Caesar Cypher project. I take the user's input, turn it into a list, take out spaces, and then encrypt the letters.
My question is: How do I re-add these spaces into the final encrypted message?
Here's what I have achieved so far (pretend word = message)
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

en_de = input("Do you want to encrypt or decrypt your message? ")
word = input("Enter a word: ")
shift = input("Enter a number: ")

word = list(word)

indexes = []

def encrypt():
  for letters in word:
    if letters in alphabet:
      index = (alphabet.index(letters))
      int(index)
      indexes.append(index)
  print(indexes)
  n = 0
  n = n + int(shift)
  for i in range(len(indexes)):
   indexes[i] = indexes[i] + n
  print(indexes)
  ceaser_cipher = ''
  for i in indexes:
    if i > len(alphabet)-1:
      i %= len(alphabet)
    ceaser_cipher = ceaser_cipher + (alphabet[i])
  for
  print(ceaser_cipher)

def decrypt():
  for letters in word:
    index = (alphabet.index(letters))
    int(index)
    indexes.append(index)
  print(indexes)
  n = 0
  n = n + int(shift)
  for i in range(len(indexes)):
   indexes[i] = indexes[i] - n
  print(indexes)
  ceaser_cipher = ''
  for i in indexes:
    if i > len(alphabet)-1:
      i %= len(alphabet)
    ceaser_cipher = ceaser_cipher + (alphabet[i])
  print(ceaser_cipher)

if en_de == "encrypt":
  encrypt()
elif en_de == "decrypt":
  decrypt()

A: The structure I would go for, is like this:
input_string = input("Enter message or cipher: ")
input_list = input_string.split(" ")
# input_list will be a list of each word in input_string
# encrypt each word in input_list and append each encrypted word
# to a new list, let's say that list is called output_list
output = " ".join(output_list)
# output will be a string of each item in the list separated by spaces

The final program could look something like this:
alphabet = list("abcdefghijklmnopqrstuvwxyz")
message = input("message or cipher: ").lower().split(" ")
shift = int(input("shift: "))
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
cipher_list = []
for word in message:
    cipher_word = ""
    for letter in word:
        cipher_word += shifted_alphabet[alphabet.index(letter)]
    cipher_list.append(cipher_word)
print(" ".join(cipher_list))

A: You are in the right path in your learning, and @Toby's answer is a good contribution for you.
I'd like to just tease you here and let you know that the whole "Caesar Cipher" can be fully implemented in a one-liner, once you get familiar with many other Python features and syntax.
Check this:
''.join(chr(a + (i - a + shift) % 26) if (a := 65) <= (i := ord(c)) <= 90 or (a := 97) <= i <= 122 else c for c in word)

Examples:
cipher = lambda w, s: ''.join(chr(a + (i - a + s) % 26) if (a := 65) <= (i := ord(c)) <= 90 or (a := 97) <= i <= 122 else c for c in w)

word = 'Hello, beautiful World!'
print(cipher(word, 4)) # positive shift
# Lipps, fieyxmjyp Asvph!

word = 'Lipps, fieyxmjyp Asvph!'
print(cipher(word, -4)) # -4 shift means decipher a +4 shift
# Hello, beautiful World!

Explanation:

*

*''.join(seq) takes a sequence of strings seq and concatenate them together into one string;

*ord(c) gives index of the character c in the Unicode table. For example, ord('a') returns the integer 97 and ord('A') returns the integer 65;

*chr(i) is the inverse of ord: It gives the character at index i in the Unicode table. For example, chr(122) returns the string 'z' and chr(90) returns the string 'Z';

*... for c in word is a generator expression. Is a nice compact and efficient idiom for creating a sequence from another sequence. In this case, I am taking every character c in the string word, performing an operation, and creating a new sequence with each resulting element.

*... if ... else ... is the ternary operator. It is a shortcut to embed a condition in an expression. Here, if the character index is not between 65 and 90 (uppercase letters) or between 97 and 122 (lowercase letters), I am returning the same character c untouched. That makes any non-letter not get transformed by the cipher (like space, comma, or exclamation mark);

*x <= y <= z is a chained comparisson, it is a nice idiom available in python that resembles the Math conditional expression.

*(a := 65) and (i := ord(c)) make use of the walrus operator :=, aka "assignment expression". With this, you can assign a variable at the same time you use it in an expression, and this variable will be available for use in the enclosed context after the declaration. For example, i is assigned in the left side of the or operator, and is used in the right side. Also, a is assigned in the "test" part of the conditional and used in the "expression" part.

*chr(a + (i - a + shift) % 26) is performing a modulo operation with the python's operator %, where 26 is the count of letters from A to Z. That means, if your shift makes your letter overflow the alphabet, it circles back to the beginning/end. For example, 'B' with a shift of -4 gives 'X', and 'x' with a shift of +30 gives 'b' (because 30 = 26 + 4);

It is a rather contrived implementation, but hopefully you got to know some new stuff today on python!


text:
Q: Anderson-Darling vs Kolmogorov-Smirnov (Many points in sample) Previous question
In my previous question (Kolmogorov-Smirnov test - reliability) I misused two-sample KS test for normality testing of one-sample data. I was given an advice that I should use one-sample KS test, also it was recommended to me to use Anderson-Darling test.
Current situation
I use following C++ implementations of Anderson-Darling (AD) and Kolmogorov-Smirnov  (KS) tests to check if given cluster has normal distribution or not.
Problems
If i deal with lets say hundreds of points per cluster, AD gives me satisfactory results. Nevertheless, If I have thousands points in my cluster, I receive large values of A-squared from AD that are far away from AD's critical values.
I have read here that AD fails for large number of points and that it is better to use KS. However, I am not sure, if I did something wrong, but KS is equal to 1.0 in almost every case (cross checked in Matlab too).
Example data
Example data are located here. It represents a cluster of gaussian mixture points. I want to test this cluster for normality (and I want to fail in that test for this data). Consequently, I want to split data to sub-clusters, test each sub-cluster again and split again until I end up with "leaf clusters" that are normally distributed.


text:
Q: Stackoverflow OpenID Hack : Login with return URL I am reading OpenID in depth. I found a bug / hack. I think this is not good thing in openid.
let me explain what I did :-

*

*clear all history of my Firefox.

*Login into Stackoveflow with Google

*signout from stackoveflow and Google.

*check history and copy google OpenID return (like https://stackoverflow.com/users/authenticate/?s=fe4fde6d-90.......... I am not pasting full URL because it is my account URL :-))

*visit this URL, and I am Logged in my SO account. (I tried that in different browsers, different PC's and different location also)

What is this I think any one can hack my account easily If I don't clear history. What is your thoughts about that.

*

*Is OpenID not secure or have a any procedure for that.

*Why stackoverflow using this kind of insecure login system.

*Why Google provide this kind of insecure Authentication system.

*May be I am wrong please tell me. I am not experienced programmmer.

Edit :
I tried with Livejournal also and same problem here.... :-) wow what is happening?
I tried with some others site and they don't allow to login with that URL multiple time.

A: This is a time limited token, so you will only be able to do this for (n) minutes.

Unable to log in with your OpenID provider:
The message expired at 8/4/2011 8:22:22 AM and it is now 8/4/2011 10:22:19 AM.

A: That should not happen. There should be a "nonce" in the URL, and Stackoverflow should not accept the same URL twice. It is up to Stackoverflow to verify that the URL can only be used once. It should also time out eventually (I guess it will at least do that).


text:
Q: Details of connected users to mobile hotspot If I've enabled Wi-Fi Hotspot in my android phone and 2 other android phones are connected to my Hotspot, then how can I distinguish between each phone?
Does my phone distinguish between the different phones using IEMI numbers or something else?

A: 1) You can use BroadcastReciever "android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED" to detect client connection.
In your AndroidManifest:
<receiver
        android:name=".WiFiConnectionReciever"
        android:enabled="true"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED" />
        </intent-filter>
    </receiver>

and in your activity:
IntentFilter mIntentFilter = new IntentFilter();
  mIntentFilter.addAction("android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED");
                    rcv = new WiFiConnectionReciever();
                    registerReceiver(rcv,
                            mIntentFilter);

2) On other hand please check this answer too: https://stackoverflow.com/a/21545389/1384010
Hope one of above methods will help you !!

A: The IMEI does not take place in the association to the AP (in this case, your Android phone serving as a hotspot), which doesn't even know that the stations asking to connect are phones.  The association takes place via probe request / probe response at the Layer 2 level (i.e. the MAC address).
Here's the whole association process in detail (from https://documentation.meraki.com/MR/WiFi_Basics_and_Best_Practices/802.11_Association_process_explained):
Access points are bridges that bridge traffic between mobile stations and other devices on the network. Before a mobile station can send traffic through an AP, it must be in the appropriate connection state.
The three 802.11 connection states are:

*

*Not authenticated or associated.

*Authenticated but not yet associated.

*Authenticated and associated.

A mobile station must be in an authenticated and associated state before bridging will occur.
The mobile station and AP will exchange a series of 802.11 management frames in order to get to an authenticated and associated state.
A mobile station starts out as not authenticated and associated.

*

*A mobile station sends probe requests to discover 802.11 networks within its proximity. Probe requests advertise the mobile stations supported data rates and 802.11 capabilities such as 802.11n. Because the probe request is sent from the mobile station to the destination layer-2 address and BSSID of ff:ff:ff:ff:ff:ff all AP's  that receive it will respond.

*APs receiving the probe request check to see if the mobile station has at least one common supported data rate. If they have compatible data rates, a probe response is sent advertising the SSID (wireless network name), supported data rates, encryption types if required, and other 802.11 capabilities of the AP.
A mobile station chooses compatible networks from the probe responses it receives. Compatibility could be based on encryption type. Once compatible networks are discovered the mobile station will attempt low-level 802.11 authentication with compatible APs. Keep in mind that 802.11 authentication is not the same as WPA2 or 802.1X authentication mechanisms which occur after a mobile station is authenticated and associated. Originally 802.11 authentication frames were designed for WEP encryption however this security scheme has been proven to be insecure and therefore deprecated. Because of this 802.11 authentication frames are open and almost always succeed.

*A mobile station sends a low-level 802.11 authentication frame to an AP setting the authentication to open and the sequence to 0x0001.

*The AP receives the authentication frame and responds to the mobile station with authentication frame set to open indicating a sequence of 0x0002.
If an AP receives any frame other than a authentication or probe request from a mobile station that is not authenticated it will respond with a deauthentication frame placing the mobile into an unauthenticated an unassociated state. The station will have to begin the association process from the low level authentication step. At this point the mobile station is authenticated but not yet associated. Some 802.11 capabilities allow a mobile station to low-level authenticate to multiple APs. This speeds up the association process when moving between APs. A mobile station can be 802.11 authenticated to multiple APs however it can only be actively associated and transferring data through a single AP at a time.

*Once a mobile station determines which AP it would like to associate to, it will send an association request to that AP. The association request contains chosen encryption types if required and other compatible 802.11 capabilities. If an AP receives a frame from a mobile station that is authenticated but not yet associated, it will respond with a disassociation frame placing the mobile into an authenticated but unassociated state.

*If the elements in the association request match the capabilties of the AP, the AP will create an Association ID for the mobile station and  respond with an association response with a success message granting network access to the mobile station.

*Now the mobile station is successfully associated to the AP and data transfer can begin.
Note: If WPA/WPA2 or 802.1X authentication is required on the wireless network, the mobile station will not be able to send data until dynamic keying and authentication have taken place after the 802.11 Association is complete.

A: when a device connects to your hotspot, hotspot's DHCP server recognize these devices by thier MAC addresses and allocate one or several IP's to the devices and store this data(MAC address and allocated IP) in "/proc/net/arp"
you can get this latest data by using-
Runtime.exec("ip -s -s neigh flush all")


text:
Q: Find Same Duplicate Max Value Excel So i try return value from table which has same percentage using Index match, but it return the same value twice instead of another value that has the same percentage
Here is my Excel View, is there any help for my problem?
Here is my excel formula
enter image description here

A: 1st: you can't and shouldn't use Match(...,...,-1) in unsorted data, use Match(...,...,0) only
2nd: you can't search for the 2nd similar because... the program has no way of  knowing there are 2|3... similar objects. So you must get the positions of ranks when sorting them, and then use that position to get the score and value you want with index(). So Sorting and getting the Position (or ROW()) must be done same time.
3rd: the way to do this is with Matrix formulas that work for on a pre-specified number of cells: So you can look in a table of 200 elements for 10 results and have provision to avoid errors if results are <10, but you'll never get 11. Also Hide the column with the positions to gain clarity...
try this formula:
= LARGE( ROUND( OFFSET($B$3,,,$G$1)*1000,0)*100 + ROW(OFFSET($A$1,,,$G$1)),ROW(OFFSET($A$1,,,$G$2)) )
to get a sorted list from column B Starting w B3 with N rows (N specified in G1) and look for m results (m specified in g2). Offcourse adjust the bolds as needed for your project
4th: Enter the formula in a Column that you will hide, with ctrl+shft+Enter (to enter as matrix) and expand it in as many cells as the results you expect (in the example 2) by selecting them starting with the cell with Array-formula, then F2 (to edit formula) and ctrl+sht+enter. Mind that Arrays can only be EXPANDED, if you want to shrink it you have to delete it and rebuild it...
5th: get the Index with =MOD( ... ,100) ,where ... are the results from steps 3&4

1ST AGAIN: Another simple solution (*not to my Liking). Within your Match(item,range,-1) you should compare item with previous item and use Offset. In your formula you can write:
=Index($C$12:$C$23, Match(DF19, Offset( $CQ$12:$CQ$23 ,if(DF19=DF18, Match(DF19,$CQ$12:$CQ$23,0),0) ,-1) ))
thus pushing the search matrix further down to avoid finding the same.
(added code with BOLD, rest should be same to your original code)


text:
Q: Do not report skipped tests with karma-jasmine-html-reporter Is there a way to prevent karma-jasmine-html-reporter aka kjhtml from reporting skipped/pending tests?
I run some tests using fit and fdescribe and I want to only see results for the selected tests, however, the reporter is always displaying all tests from the suite.

A: Apparently, yes, there's a way to that with Jasmine (starting from v3.3.0). I've been able to do that in an Angular project. In the test.ts I've put something like:
jasmine.getEnv().configure({ hideDisabled: true });

Official documentation here: https://jasmine.github.io/api/3.5/Configuration.html.


text:
Q: Long running WCF in shared hosting I have a WCF (on top of IIS) which will be hosted on a shared hosting environment, so I don't have access to window services or permissions for installations.
This WCF would have a long running computation (it is a spatial interpolation), so my question is about which architecture to use in order to not affect performance, in particular I don't want to grab threads from the ASP.NET tread pool for such long task.
I know that a possible solution would be a window service for multi-threading computation and MSMQ for communicating between the WCf and the window service, but as I said I don't have the possibility to install a service.
Anybody could suggest a solution?
thanks in advance

A: You could simple use an asynchronous/one-way method on your WCF service and call this.
We use a similar method to upload data and kick off the import process. The client will then poll using another WCF method and when the initial process has finished, update the relevant data to indicate that and return it back to the client in the poll.


text:
Q: Internal global property..bad smell? I have run into a bit of a desgin issue with some code that I have been working on:
My code basic looks like this:
Main COM wrapper:
public class MapinfoWrapper
{
    public MapinfoWrapper()
    {
        Publics.InternalMapinfo = new MapinfoWrapper();
    }

    public void Do(string cmd)
    {
        //Call COM do command
    }

    public string Eval(string cmd)
    {
        //Return value from COM eval command
    }
}

Public static class to hold internal referance to wrapper:
internal static class Publics
{
    private static MapinfoWrapper _internalwrapper;
    internal static MapinfoWrapper InternalMapinfo
    {
        get
        {
            return _internalwrapper;
        }
        set
        {
            _internalwrapper = value;
        }
    }
}

Code that uses internal wrapper instance:
    public class TableInfo
    {
        public string Name {
            get { return Publics.InternalMapinfo.Eval("String comman to get the name"); }
            set { Publics.InternalMapinfo.Do("String command to set the name"); }
        }
    }

Does this smell bad to anyone?  Should I be using a internal property to hold a reference to the main wrapper object or should I be using a different design here?
Note:  The MapinfoWrapper object will be used by the outside world, so I don't really want to make that a singleton.

A: You are reducing the testability of your TableInfo class by not injecting the MapInfoWrapper into the class itself.  Whether you use a global cache of these MapInfoWrapper classes depends on the class -- you need to decide whether it is necessary or not, but it would improve your design to pass a wrapper into TableInfo and use it there rather than referencing a global copy directly inside TableInfo methods.  Do this in conjunction with the definition of an interface (i.e., "refactor to interfaces").
I would also do lazy instantiation in the getter(s) of Publics to make sure the object is available if it hasn't already been created rather than setting it in the constructor of MapInfoWrapper.
public class TableInfo
{
     private IMapinfoWrapper wrapper;

     public TableInfo() : this(null) {}

     public TableInfo( IMapinfoWrapper wrapper )
     {
          // use from cache if not supplied, could create new here
          this.wrapper = wrapper ?? Publics.InternalMapInfo;
     }

     public string Name {
        get { return wrapper.Eval("String comman to get the name"); }
        set { wrapper.Do("String command to set the name"); }
     }
}

public interface IMapinfoWrapper
{
    void Do( string cmd );
    void Eval( string cmd );
}

public class MapinfoWrapper
{
    public MapinfoWrapper()
    {
    }

    public void Do(string cmd)
    {
        //Call COM do command
    }

    public string Eval(string cmd)
    {
        //Return value from COM eval command
    }
}

internal static class Publics
{
    private static MapinfoWrapper _internalwrapper;
    internal static MapinfoWrapper InternalMapinfo
    {
        get
        {
            if (_internalwrapper == null)
            {
                _internalwrapper = new MapinfoWrapper();
            }
            return _internalwrapper;
        }
    }
}

Now, when you test the TableInfo methods, you can mock out the MapInfoWrapper easily by providing your own implementation to the constructor.  Ex (assuming a hand mock):
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestTableInfoName()
{
     IMapinfoWrapper mockWrapper = new MockMapinfoWrapper();
     mockWrapper.ThrowDoException(typeof(ApplicationException));

     TableInfo info = new TableInfo( mockWrapper );
     info.Do( "invalid command" );
}

A: I thought about adding this to my original response, but it is really a different issue.
You might want to consider whether the MapinfoWrapper class needs to be thread-safe if you store and use a cached copy.  Anytime you use a single, global copy you need to consider if it will be used by more than one thread at a time and build it so that any critical sections (anywhere data may be changed or must be assumed to not change) are thread-safe. If a multithreaded environment must be supported -- say in a web site -- then this might argue against using a single, global copy unless the cost of creating the class is very high.   Of course, if your class relies on other classes that are also not thread-safe, then you may need to make your class thread-safe anyway.


text:
Q: Cisco sg500-24p web-based configuration utility ip adress How can i know what is the ip adress to the web-based control panel for my Cisco sg500 if it is not the default and if i don't want to rest the switch, i need to change vlan for a port ?
The switch is already diveded into 3 vlan, the port 24 located on vlan 1 with ip 192.168.47.5
Regards

A: Have you tried to plug a console cable into the console port and configure it that way using a serial connection?
If you log in that way and check the config it will tell you any IP's assigned to it and if http/https access is enabled on the switch.


text:
Q: "Not supported for this JVM" when attempting to connect to a remote host on VisualVM After successfully attaching VisualVM to a remote host I keep getting "Not supported for this JVM" label on the CPU panel, system properties, etc. Also, I don't seem to have access to the "Threads" panel, that I need in order to do thread dumps.
I've tried to run 32 and 64 bit versions of VisualVM, from both JDK7 and JDK8 (the target process is running on a Linux machine in 64 bits mode). The problem seems to be just the same in both cases for VisualVM configurations.
This is what java -version gets me on that machine:
java version "1.7.0_55"
Java(TM) SE Runtime Environment (build 1.7.0_55-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.55-b03, mixed mode)

Is there anything I should take into special consideration or is there some kind of limitation when doing remote access?

A: It doesn't mean the JVM that you're using to run VisualVM when it says "Not supported for this JVM", it means the remote server's VM.
You're probably running a non-oracle VM there (openjdk probably) in which case VisualVM can't work properly. Either change to Oracle's JRE on the server, or get a profiler that can handle OpenJDK too.

A: When you connect to a remote JVM the VisualVM will usually talk over the JMX interface to get the threads etc. However, the remote JVM decides what it will make available to the client, rather than everything being available by default; so it's possible that the JVM you're connecting to just doesn't support reporting on those characteristics.
Assuming that the connection works properly, you will find that there are various isXxxSupported methods that the JVM's returning, possibly false in this case.
One thing you might like to try is to run jcmd on the remote server (or jps) to see if there's some kind of restriction on the processes in the box that are preventing you from seeing the other VMs as that user. It may be that if it's running in something like a container then the RMI calls for the JMX aren't being passed through, or if you're running in an selinux or a Java security policy that it's not letting you read/communicate on the network ports or files.
JMXServiceURL url = new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
JMXConnectionFactory factory = JMXConnectorFactory.connect(url);
MBeanSearverConnection conn = factory.getMBeanServerConnection();
ThreadMXBean threads = ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.THREAD_MXBEAN_NAME,ThreadMXBean.class);
long ids[] = threads.getAllThreadIds();

If you can get the thread IDs then it suggests you can talk to the server; there are other methods on the threads that will allow you to get stack traces etc. This will be the method that's used by the VisualVM and may allow you to do further debugging as to what's going wrong on the responses.


text:
Q: How to show exact solution of Finite Difference Equation? The question requires me to show the exact solution of the finite difference equation$$y''=k^2y$$for $-1<x<1$, $y(-1)=y(1)=1$ and $k>0$.
Given the difference formula$$y''(x_i)=\frac{1}{h^2}[y(x_{i+1})-2y(x_i)+y(x_{i-1})]-O(h^2),$$
and what I can get is $$y_{i+1}-(2+k^2h^2)y_i+y_{i-1}=h^2f_i.$$
How can I show the exact solution of $y_i$ in terms of $x_i$?


text:
Q: Protractor Chained vs Unchained Selectors I think I understand that in Protractor,
$(selector1).$(selector2)

is generally equivalent to:
$(selector1 selector2)

Is there a reason to prefer one over the other, perhaps efficiency?  My inclination is that the combined 2nd version is doing a single search, whereas the original version is doing multiple searches which sounds less efficient.  However, when I read about how CSS actually performs, scanning the entire dom for each additional term in the expression (and doing it right-to-left starting with "key selector"), I wonder whether the code underneath Protractor makes it more efficient to first perform a simple selector to reduce the search space, depending on how the dotted ".$()" works when appended to a previous one.
And would the answer to this question change if comparing:
$$(multiCss).$(singleCss)

vs
$(multiCss singleCss)

And if there are no efficiency or correctness issues involved, is one form considered more readable than the other?  This might be leaning into the area of opinion based answers, but I ask as a matter of whether one or the other is considered canonical style.  If it's just a personal opinion and not a matter of canonical style, then forget this part of the question.

A: I found this to be extremely interesting. Please note that this is NOT A CANONICAL ANSWER
This is only a collection of data from some tests that I ran regarding this subject. I will likely run further tests when I have a few hours to spare to properly setup a clean testing environment, but this is all I had time to do right now.
For my test, I was navigating to a page, then running an expect() on 10 separate elements to validate their text. This was locally hosted so internet speed did not play a factor. I ran the test 5 times with the elements selected like $().$(), and then 5 more like $('CSS CSS'). I then repeated the test in headless mode to see if I would get different results.

$().$() No Headless Times:
1) 16.062
2) 16.297
3) 15.029
4) 15.773
5) 16.699
Average: 15.972

$().$() Headless Times:
1) 14.705
2) 15.081
3) 15.806
4) 14.944
5) 14.997
Average: 15.107

$('CSS CSS') No Headless Times:
1) 16.172
2) 15.556
3) 16.604
4) 16.706
5) 15.733
Average: 16.154

$(CSS CSS) Headless Times:
1) 15.288
2) 15.136
3) 15.11
4) 15.152
5) 14.805
Average: 15.098

Like you, I expected $().$() to be faster, and while this was true for non headless in my tests, not in any considerable way. Headless times ran basically the same speed regardless of how you did the selectors. The only useful take away from this data is that a potential difference in performance depending on selectors is small enough to not make noticeable difference, and would need to be tested on a much larger scale to possibly start seeing significantly different times. For sure something I want to look into more when I have enough free time to set up a properly large test case.


text:
Q: MacBook not turning on (fan loop) I'm in a very frustrating situation of having my MacBook Pro 15' Retina (A1398) stuck in a boot loop. Well, not exactly boot loop: when I connect my MagSafe charger, it goes in a constant cycle of starting up fans and turning off, with a period as long as 1 second (or even less). I tried resetting SMC and NVRAM so far, but had no result apart from having my charger's led turn green from amber (temporary; only when I hold Shift-Control-Option combination). What could be the possible issues?
I'll be getting it to a diagnostics facility (non-Apple) in a few days, it would help clarifying whether I could be lied to or not (considering the fact it's unofficial).

A: How is your backup Situation?, if you've got everything backed up, I recommend that you simply format your Drive and reinstall OS X. if you know how, and have the original Disk. If you don't let me know. -quick pointers-
-Insert reinstall CD in your mac.
-restart mac holding option.
-choose from the two drives the Reins-CD
-Boot into it.

A: Maybe check this out: http://www.apple.com/support/macbookpro-videoissues/. The information you provide could correspond to a Retina Early 2013 model, which is affected.


text:
Q: Automatically shift data down once new data is copied in the same cells using button? I am trying to use a macro button that once clicked copys a set of data A3:E22 from sheet 1 to A3:E22 on sheet 3. After it is copied, I want the data from sheet 1 cleared so that i can start to input new data in the cells that were just cleared.
I am having trouble shifting the data on sheet 3 down so that once I repeat the cycle of copying data from sheet 1 to sheet 3 again, the data that i previously copied on sheet 3 will shift down automatically and keep shifting down as long as i repeat the copy cycle.
Is there a certain set of code that I can program to my button for the copy cycle from sheet 1 to sheet 3 so that the data on sheet 3 will automatically shift down?
11/05/14
I've tried the code from the reply and it works great on a new workbook but I'm having trouble transferring this code to my existing workbook. I keep getting a "Subscript out of range" error where the "Set S1...". do I need to rename my worksheets or call S1 something different to refer to worksheet 1? I am a rookie at coding so any help would be greatly appreciated.Thanks

A: Here is some typical code:
Sub TransferData()
    Dim s1 As Worksheet, s3 As Worksheet
    Dim r1 As Range, r3 As Range
    Set s1 = Sheets("Sheet1")
    Set s3 = Sheets("Sheet3")
    Set r1 = s1.Range("A3:E22")
    Set r3 = s3.Range("A3:E22")

    s3.Activate
    r3.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Set r3 = s3.Range("A3:E22")

    s1.Activate
    r1.Copy r3
    r1.Clear
End Sub


text:
Q: METEOR - Show loader and run methods at specific time I wanna build a loader circle what goes from 1 to 100% and in the meantime to run some methods.
loader circle
The scenario is:

*

*load the page and start counting.
When the counter is at 50% pause counting and run the first method and when I have the result to start counting from where I was left.

*count until 90% and run the second method.

I was trying something with Meteor.setInterval on onCreated but I'm not sure if it's the right method to do this.
Can someone give me some ideas about how to approach this?
Thanks!

A: There are several ways you can do this depending on your specific needs and you might even want to use one of the many Reactive Timer packages that are out there.
Here is one working example that only uses the Meteor API (no packages).  Note, I did not actually incorporate the loader circle animation since it wasn't specifically part of the question.
Template definition
<template name="loader">

Loading...({{loadingPercentage}})

</template>

Template logic
Template.loader.onCreated(function() {
  // used to update loader circle and triggering method invocation
  this.elapsedTime = new ReactiveVar(0);

  // handle for the timer
  var timerHandle;

  // starts a timer that runs every second that can be paused or stopped later
  const startTimer = () => {
    timerHandle = Meteor.setInterval(() => {
      this.elapsedTime.set(this.elapsedTime.get() + 1);
    }, 1000);
  };

  // pauses/stops the timer
  const pauseTimer = () => {
    Meteor.clearInterval(timerHandle);
  };

  // let's first start our timer
  startTimer();

  // runs every second and triggers methods as needed
  this.autorun(() => {
    const elapsedTime = this.elapsedTime.get();

    // call methods based upon how much time has elapsed
    if (elapsedTime === 5) {
      pauseTimer();

      // call method and restart the timer once it completes
      Meteor.call('methodOne', function(error, result) {
        // do stuff with the result

        startTimer();
      });
    } else if (elapsedTime === 9) {
      pauseTimer();

      // call method and restart the timer once it completes
      Meteor.call('methodOne', function(error, result) {
        // do stuff with the result

        // DO NOT RESTART TIMER!
      });
    }
  });
});

Template.loader.helpers({
  // helper used to show elapsed time on the page
  loadingPercentage: function() {
    return Template.instance().elapsedTime.get();
  },
});

Let me know if you have any questions.

A: This is what i was trying to do:
Template.onboarding.onCreated(function(){
var instance = this;

instance.progress = new ReactiveVar(0);

instance.autorun(function(){
    var loader = {
        maxPercent: 100,
        minPercent: instance.progress.get(),

        start: function(){
            var self = this;

            this.interval = Meteor.setInterval(function(){
                self.minPercent += 1;

                if(self.minPercent >= self.maxPercent) {
                    loader.pause();
                }

                if( self.minPercent == 25) {
                    loader.pause();
                    Meteor.call('runMethodOne', (err,res)=>{
                        if (!err) loader.resume();
                    });
                 }

                if(self.minPercent == 75) {
                    loader.pause();

                    Meteor.call('runMethodTwo', (err,res) =>{
                        if(res) loader.resume();
                    });
                                }
                            }
                    });
                 }

                 instance.progress.set(self.minPercent)

               },50);
           },

           pause: function(){
               Meteor.clearInterval(this.interval);
               delete this.interval;
           },
           resume: function(){
               if(!this.interval) this.start();
           }
       };

       loader.start();
    }
});

});


text:
Q: Traceback error for array of all ones I'm beggining at Python.
I just installed Python 3.5.3 and I tried with my first code in Shell.
I would like to creat an array with dimension 2X3 of all ones.

a=ones((2,3))

But it get error:
Traceback (most recent call last):
File "", line 1, in
  a=ones((2,3))
NameError: name 'ones' is not defined
Actually, I read about it but I still don't understand why it is error.
What is going wrong with my software?
Thanks in advance for your answer,
Chuong


text:
Q: How to combine common dates into 1 row in Oracle SQL My query is:
SELECT EXTRACT(DAY FROM CO.ORDER_DATE) "DATE",
       TO_CHAR(CO.ORDER_DATE, 'DY') "BUSIEST DAY",
       SUM(OLI.QUANTITY) "NO. OF DISHES"
FROM CUSTOMER_ORDER CO INNER JOIN ORDER_LINE_ITEM OLI
ON CO.ORDER_ID = OLI.ORDER_ID
WHERE CO.ORDER_DATE >= TO_DATE('01 SEPTEMBER 2019', 'DD MONTH YYYY')
AND CO.ORDER_DATE <= TO_DATE('30 SEPTEMBER 2019', 'DD MONTH YYYY')
GROUP BY CO.ORDER_DATE
ORDER BY CO.ORDER_DATE

My current output is:
DATE   BUSIEST DAY    NO. OF DISHES
-----------------------------------
1      SUN            27
1      SUN            10
14     SAT            10

The output I want is:
DATE   BUSIEST DAY    NO. OF DISHES
-----------------------------------
1      SUN            37
14     SAT            10

What changes do I need to make in my Oracle SQL query?

A: The problem here is that while you are selecting the day of the month, you are actually aggregating by the date.  This means that two different dates on the first of the month would end up appearing as two separate records.  You should instead aggregate by the actual day value and busiest day values:
SELECT
    EXTRACT(DAY FROM CO.ORDER_DATE) "DATE",
    TO_CHAR(CO.ORDER_DATE, 'DY') "BUSIEST DAY",
    SUM(OLI.QUANTITY) "NO. OF DISHES"
FROM CUSTOMER_ORDER CO
INNER JOIN ORDER_LINE_ITEM OLI
    ON CO.ORDER_ID = OLI.ORDER_ID
WHERE
    CO.ORDER_DATE >= TO_DATE('01 SEPTEMBER 2019', 'DD MONTH YYYY') AND
    CO.ORDER_DATE <= TO_DATE('30 SEPTEMBER 2019', 'DD MONTH YYYY')
GROUP BY
    EXTRACT(DAY FROM CO.ORDER_DATE),
    TO_CHAR(CO.ORDER_DATE, 'DY')
ORDER BY
    "DATE";

A: You seem to have a time component in your "date".  This is hidden in Oracle.  I would actually recommend that you return the full date -- it makes it easier to expand the query across multiple months.
So:
SELECT TRUNC(CO.ORDER_DATE) as DATE,
       TO_CHAR(TRUNC(CO.ORDER_DATE), 'DY') as BUSIEST_DAY,
       SUM(OLI.QUANTITY) as Num_Dishes
FROM CUSTOMER_ORDER CO INNER JOIN
     ORDER_LINE_ITEM OLI
     ON CO.ORDER_ID = OLI.ORDER_ID
WHERE CO.ORDER_DATE >= DATE '2019-09-01' AND
      CO.ORDER_DATE < DATE '2019-10-01'
GROUP BY TRUNC(CO.ORDER_DATE)
ORDER BY TRUNC(CO.ORDER_DATE);

Note that this also changes the WHERE clause.  This will include all data in September, including orders during the day on Sep 30th.  I strongly recommend using these comparisons rather than BETWEEN when working with dates -- precisely because this logic works with and without time components.


text:
Q: parsing 2D array using Codable in swift4 I need to parser two dimensional array using codable in swift 4,please let me how to do it. following is my code snipped
var exclusive = """
{"list":[[{"primary_key":"1","foreign_key":"3"},{"primary_key":"2","foreign_key":"10"}],[{"primary_key":"2","foreign_key":"10"},{"primary_key":"3","foreign_key":"22"}]]}
"""

let exeString = try! exclusive.data(using: .utf8)

struct ListStruct : Codable {

struct listStruct :Codable {
 let primary_key : Int
 let foreign_key : Int
 }

 let list = [[listStruct]] ()
 or
 let list = [][listStruct]

}

let listofData = try! JSONDecoder().decode(ListStruct.self, from: exeString!)

A: There are three basic issues

*

*The values for primary_key and foreign_key are String, not Int.
There is a simple rule: Every JSON value wrapped in double quotes is string, even "1" or "false".

*There is a root object which is a dictionary containing one key list.

*data(using: of String does not throw so marking with try is wrong.

This code uses the Swift naming convention, camelCased and lowercased variable names and uppercased struct names
let exeString = """
{"list":[[{"primary_key":"1","foreign_key":"3"},{"primary_key":"2","foreign_key":"10"}],[{"primary_key":"2","foreign_key":"10"},{"primary_key":"3","foreign_key":"22"}]]}
"""

struct Root : Decodable {
    let list : [[ListStruct]]
}

struct ListStruct :Codable {

    private enum CodingKeys : String, CodingKey {
        case primaryKey = "primary_key"
        case foreignKey = "foreign_key"
    }

    let primaryKey : String
    let foreignKey : String
}

do {
    let data = Data(exeString.utf8)
    let result = try JSONDecoder().decode(Root.self, from: data)
    print(result.list)
} catch { print(error) }

A: see this
struct Language: Codable {
var name: String
var version: Int
}

let swift = Language(name: "Swift", version: 4)
let encoder = JSONEncoder()

if let encoded = try? encoder.encode(swift) {
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}

let decoder = JSONDecoder()
 if let decoded = try? decoder.decode(Language.self, from: encoded) {
 print(decoded.name)
}
}


text:
Q: Check element visibility that is visible for less than a second in Rails Capybara I am trying to write an integration test in which I must check the visibility of an element on button click. The code works perfectly in one machine and failing in the other. The element is displayed until the data comes from the backend. So its visibility depends on the speed of the machine also. Is that the problem? This is the code:
assert page.has_css?('#my_element_id')

assert find('#my_element_id', visible: true)

But I am getting an error: expected false to be truthy.
Is there any other way to assert the visibility of the element?

A: You can also try:
assert find('#my_element_id').visible?
from: https://rubydoc.info/gems/capybara/0.4.0/Capybara/Element#visible%3F-instance_method
It does say however:

visible? ⇒ Boolean
Whether or not the element is visible. Not all drivers support CSS, so
  the result may be inaccurate.

I assume you are talking about whether #my_element_id is visible.
EDIT:
If you are waiting for an element to be visible first before checking for the element with the id #my_element_id this posts might be helpful:
How to make Capybara check for visibility after some JS has run?
So you could wait for the backend data to come through then check visibility. If you are try to check that it is visible before that data, I am not quite sure, it seems like it would depend on the machine's internet connection to me.

A: Don't use plain assert, use the assertions provided by Capybara which include retrying behavior
assert_css('#my_element_id')

By default that would check only for visible elements, but if you've set Capybara.ignore_hidden_elements = false (don't do that, really dont) then you would need to also pass the :visible option
Note: you may still have issues if it's only visible for a very short time - in that case if you're using Chrome you can set the network conditions to very slow in order to increase the time data takes to return


text:
Q: highlight dates in arshaw fullcalendar I am using arshaw fullcalendar api for rendering calendar.
Now I know that TODAY is highlighted. Same I have a list of dates, that I want to highlight in week view. Also dates can be in different weeks.
Any help is appreciated. Thank You.

A: For agendaWeek and agendaDay view it can be possible by changing fullcalendar.js file.
Pass an additional paramter to fullcalendar say highlightDays
highlightDays: [0,3,4]   // List of days to highlight  0 - Sunday ... 6 - Saturday

In fullcalendar.js updateCells() method
if(opt('highlightDays').indexOf(date.getDay()) > -1)
{
    bodyCell.removeClass('ui-widget-content');
    bodyCell.addClass('fc-day-highlight');
}

Add colour you want to give to those days in  fc-day-highlight css class as
background-color: #dddddd;

A: hi you can render custom highlight with a little hack inside the viewDisplay callback :
viewDisplay : function( view ) {

            startDate = view.start;

                var d = startDate.getDate();
                var m = startDate.getMonth();
                var y = startDate.getFullYear();

            cols = $('.fc-view-agendaWeek [class*="fc-col"].fc-widget-content')

            for(i = 0 ; i<  cols.length ; i++){

                var colDate = new Date(y, m, d+i);

                if($.inArray(colDate.getTime() , hightligthedDays) > -1){

                    $(cols[i]).addClass("fc-state-highlight-other");

                   }
                else{

                    $(cols[i]).removeClass("fc-state-highlight-other");

                }
            }

            }

jsfiddle


text:
Q: Writing an object to python file I have a following code:
 matrix_file = open("abc.txt", "rU")
 matrix = matrix_file.readlines()
 keys = matrix[0]
 vals = [line[1:] for line in matrix[1:]]
 ea=open("abc_format.txt",'w')
 ea.seek(0)
 ea.write(vals)
 ea.close()

However I am getting the following error:
TypeError: expected a character buffer object

How do I buffer the output and what data type is the variable vals?

A: vals is a list. If you want to write a list of strings to a file, as opposed to an individual string, use writelines:
 ea=open("abc_format.txt",'w')
 ea.seek(0)
 ea.writelines(vals)
 ea.close()

Note that this will not insert newlines for you (although in your specific case your strings already end in newlines, as pointed out in the comments). If you need to add newlines you could do the following as an example:
 ea=open("abc_format.txt",'w')
 ea.seek(0)
 ea.writelines([line+'\n' for line in vals])
 ea.close()

A: First of all instead of opening and closing the file separately you can use with statement that does the job automatically.and about the Error,as it says the write method only accepts character buffer object so you need to convert your list to a string.
For example you can use join function that join the items within an iterable object with a specific delimiter and return a concatenated string.
with open("abc.txt", "rU") as f,open("abc_format.txt",'w') as out:
   matrix = f.readlines()
   keys = matrix[0]
   vals = [line[1:] for line in matrix[1:]]
   out.write('\n'.join(vals))

Also as a more pythonic way as the file objects are iterators you can do it in following code and get the first line with calling its next method and pass the rest to join function :
with open("abc.txt", "rU") as f,open("abc_format.txt",'w') as out:
   matrix = next(f)
   out.write('\n'.join(f))

A: You cannot "write" objects to files. Rather, use the pickle module:
matrix_file = open("abc.txt", "rU")
matrix = matrix_file.readlines()
keys = matrix[0]
vals = [line[1:] for line in matrix[1:]]
#pickling begins!
import pickle
f = open("abc_format.txt")
pickle.dump(vals, f) #call with (object, file)
f.close()

Then read it like this:
import pickle
f = open("abc_format.txt")
vals = pickle.load(f) #exactly the same list
f.close()

You can do this with any kind of object, your own or built-in. You can only write strings and bytes to files, python's open() function just opens it like opening notepad would.
To answer your first question, vals is a list, because anything in [operation(i) for i in iterated_over] is a list comprehension, and list comprehensions make lists. To see what the type of any object is, just use the type() function; e.g. type([1,4,3])
Examples: https://repl.it/qKI/3
Documentation here:
https://docs.python.org/2/library/pickle.html and https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

A: The write function will only handle characters or bytes. To write arbitrary objects, use python's pickle library. Write with pickle.dump(), read them back with pickle.load().
But if what you're really after is writing something in the same format as your input, you'll have to write out the matrix values and newlines yourself.
for line in vals:
    ea.write(line)

ea.close()

You've now written a file that looks like abc.txt, except that the first row and first character from each line has been removed. (You dropped those when constructing vals.)
Somehow I doubt this is what you intended, since you chose to name it abc_format.txt, but anyway this is how you write out a list of lines of text.


text:
Q: Apply implicit function theorem on partial solution to Lagrangian Suppose $\mathcal{L} = f(x,y) + \lambda g(x,y,z)$ where $z$ is actually constant which I would like to take to use implicit function on.
$$\frac{\partial \mathcal{L}}{\partial x} = f_x(x,y)+\lambda g_x(x,y,z)=0$$
$$\frac{\partial \mathcal{L}}{\partial y} = f_y(x,y)+\lambda g_y(x,y,z)=0$$
After rearrange the euquation, I have
$$F(x,y,z) =\frac{f_x(x,y)}{f_y(x,y)} - \frac{ g_x(x,y,z)}{ g_y(x,y,z)} = 0 $$
Can I apply implicit function on $F(x,y,z)$ to find $\frac{dx}{dz}$?


text:
Q: Update all rows in a selected row where time colume has time less than current time by 3 days using mysqli php I have a table of users in my database with time column set to default timestamp and status column have value of either 0 or 1.
I already selected the rows where username='$username' and status= '1'.
Now I want to loop through these selected rows and check for rows where time in the time column is less than current time (i.e time()) by at least 7 days and then update the status column of such rows, setting status=2.
I've read a lot of things online but couldn't get to do this... Below is my current code, I'm using mysqli.
$sql= mysqli_query($conn,
          "select from tables where username=$username and status='1' ") ;

$row=mysqli_query($conn, $sql) ;

A: You don't need to loop through it, because you can specify where condition inside your update statement:
    $sql= mysqli_query($conn, "UPDATE tables SET status = '2' WHERE username = '$username' AND status = '1' AND time <= CURRENT_DATE - INTERVAL 7 DAY") ;

    mysqli_query($conn, $sql) ;

A: I just did a work around my question above and is working perfectly ok for me now. This is what I did:
$query=mysqli_query($conn,"select * from table_name");

while($Row = mysqli_fetch_array($query)) {
$day= abs(time ()-$time)/86400;
$ql= mysqli_query($conn, "update table_name set status='2' where name='$username' and status='1' and $day>4");
//for 4 days interval
}


text:
Q: Select Statement DrillDown I have a Select Statement Like this..
Select * From A Join B on A.ID = B.ID
 And A.Gener = 'M'
 And A.Age = 21
 And B.School = 'Bluh'
--- many more AND Clauses

now these "AND" Clauses are dynamic, they will be build based upon user selection within my  vb.net web application....
for example...
if gener.text <> "" Then
   qry = qry & " And A.Gender='M'"

I dont really want to build my SQL query on the fly like this. is there a way of doing it better using LINQ or something else?
my actual SQL Query will contain up to 30 dynamic AND's (Based upon user selection).
please advise.
Thanks

A: Use for every statement:

qry = qry & " And (A.Gender='" & gender.Text & " ' OR '" & gender.Text
  & "' = '' ) "

A: i would change it this way
Select * From A Join B on A.ID = B.ID
 And (A.Gener = @arg1 or @arg1 is null)
 And (A.Age = @arg2 or @arg2 is null)
 And (B.School = @arg3 or @arg3 is null)

--- many more AND Clausesju
this way if you pass null values into procedure they would be logicly ignored - dont know if it works in your case
definetly building dynamic tsql query application side is a invitation for sql injection


text:
Q: Is breaking my class into multiple classes, the right thing to do? I'm working with Unity and C# and I have a canvas that is about a competition with several milestones. So I have to show a leaderboard and a slider for the player's progress in the competition and the rewards they'v got since now and also some other stuff like the title.
I have a class named CompetitionCanvasManager to handle all these things but actually, they are not related to each other in code and all of them just use one single variable in common to set the proper UI. If I break this class into 3 different classes such as LeaderboardManager and RewardsManager and SliderManager and use my current class to just initialize those 3 classes and set the title, is it a cleaner code than what I have right now? Every class would have only one or two methods and probably something like 50 lines of code but I'm not sure doing this is actually better than having one less-than-200-lines-of-code class to do them all.
I'm aware of Single Responsibility Principle but in both cases, managing a canvas or managing every part of it looks like a Single Responsibility and I need help to understand what is the right way to do.

A: Single Responsibility Principle (SRP) is one of the many software development principles and practices that can be interpreted multiple ways. It's an organizational approach, and any time organization will involve more than a single attribute it can be sliced different ways and in different orders.
A real world example
You have a 10x10 warehouse rack full of 10 widgets and each comes in one of the same 10 colors. Do you put all widgets of the same color on the same row, and the columns are by type? Or type on the same row and columns are color? Both are valid and clearly organized, but you have to step back and look at how they will be used.
When people order multiple widgets do they usually order multiple colors of the same widget, or multiple widgets in the same color (for fitting a color scheme)? Do your order pickers have to return to the ground before moving to the next column, or can they move across a whole row without going back down? You'll want to organize it based on how efficient your pickers are going to be able to move through the majority of their orders.
Back to development
You're in a good mindset to be thinking about this structure now while your class is small. Like the warehouse example, you currently have two attributes to organize by. What it works with: canvas. And what it does: Leaderboard/Rewards/Slider. Some people I have worked with in the past would argue that since they're all canvas based classes they can be kept together. And they might be right. But they also serve very different purposes.
It sounds like you've done a good job of creating very separate classes already even though they're lumped together right now. They're not dependent on one another. They probably shouldn't be, even as they grow over the course of development. Separating them out now will help you in maintaining that separation as you go. If they're all inside the same class then the temptation to use shared variables increases. When you start out with them separate it forces you to use better methods for communicating state between them such as callbacks.
What's the true payoff for this work?
You view this as an SRP issue, but the consequences reach very far and into other principles. A set of classes that are kept separate and have proper ways of interfacing and communicating with each other are easier to test. Unit Testing is a very useful tool for both initial development (Test Driven Development) and in helping prevent bugs from appearing (Regression Testing) as you make changes. Unit Testing depends heavily on Dependency Injection to properly isolate the code being tested.
A mega class with many different methods that share common variables is harder to test because changes to those variables caused by one method may affect how another behaves. If you're not already aware of the dangers of "global scope" variables you should read up on it. When classes get too large, because they're trying to do a bunch of loosely related things all in one place, the class level variables that are used throughout become more and more likely to be as dangerous as global scope variables.
Final thoughts
I'm a bit of a structure snob in my work, and I definitely would be splitting those classes up. It may seem excessive right now, but future you will likely thank you for the minimal effort you put in at this stage. And lastly, as an example of when splitting classes up becomes more obvious, think about data access classes for a large system.
We have a project at work that has a lot of tables and views. We could have put all the data access methods into one class and said, "its single responsibility is to access the database." And that class would be thousands of lines long. Instead, we have them split out by the entities they work with. As a result, we had to create a manager class that makes it easier to wrangle all those classes in the upper levels.  And as a result of having the manager class, we now have a place where we can handle transaction scoping for all our data access.
The manager class is what actually handles the commits and rollbacks. So no single data access class has to ever be aware of what other data access class is calling it, or how they behave. They simply do their reads, updates, etc and we know that the manager will handle the rest. Their actual single responsibility is to interact with the database for every action that happens on their respective table/view.


text:
Q: saving an Int to Core Data I am trying to save in Int to core data and am struggling.
I have an array with a SQLite with about 2000 records and all are listed on a tableview.  When one of the records are selected, it goes to the "speciesDetailViewController" were it displays details of that item.
all currently displayed is not editable.
I am adding the ability for the user to add notes and the option to change one of the fields.
The minor changes are saved in CoreData as I have no experience with SQLite (hired someone).
I have all working, except saving the Int.
Below are other details.
var specieId: Int = -1
var speciesDetailData : SpeciesDetailData?
lazy var coreDataStack = CoreDataStack()

The below is the save func used.
func saveResults () {

    if let speciesDetailData = speciesDetailData {

        let x = Int32(self.specieId)

        speciesDetailData.commonName = ckCommonNameTextField.text!
        speciesDetailData.commonForeignName = ckCommonForeignNameTextField.text!.isEmpty ? "" : ckCommonForeignNameTextField.text
        speciesDetailData.speciesName = speciesLabel.text!
        speciesDetailData.speciesID = x
        speciesDetailData.speciesNote = ckNotesTextView.text!.isEmpty ? "" : ckNotesTextView.text

    } else if speciesDetailData == nil {

        if let savedData = NSEntityDescription.entity(forEntityName: "SpeciesDetailData", in: coreDataStack.managedObjectContext1) {

            let x = Int32(self.specieId)

            let speciesDetailData = SpeciesDetailData(entity: savedData, insertInto: coreDataStack.managedObjectContext1)

            print (specieId)

            speciesDetailData.commonName = ckCommonNameTextField.text!.isEmpty ? "" : ckCommonNameTextField.text
            speciesDetailData.commonForeignName = ckCommonForeignNameTextField.text!.isEmpty ? "" : ckCommonForeignNameTextField.text
            speciesDetailData.speciesName = speciesLabel.text!
            speciesDetailData.speciesID = x
            speciesDetailData.speciesNote = ckNotesTextView.text!.isEmpty ? "" : ckNotesTextView.text

        }
    }

    coreDataStack.saveMainContext()

The entity is SpeciesDetailData and the speciesID is currently set to Int32.
I have tried the above, I have also tried
speciesDetailData.speciesID = Int32(self.specieId)
speciesDetailData.speciesID = Int32(specieId)

I have tried to set all to Int64, same results.
I have seen other posts, but all suggestions are the same as what I have tried.
Also, I am not getting an error.  I only get the red line of death.
I set a breakpoint and followed it through and when it hits the int line, it just goes red lined with no details.
UPDATE:
I have no idea what "User Scalar Type" is, but I unchecked it and the autocorrect changed it to the below now runs without an error but a nil is saved.  I ran the print (specieId) and it prints the correct integer.
 speciesDetailData.speciesID = Int32(specieId) as NSNumber?

Any suggestions?

A: Apparently, use Scalar type is to assist with the migration to Swift 3.  When I unchecked this box, it seems to run OK.  I ended up needing to add as NSNumber at the backend of the line, but it works.


text:
Q: Print all possible strings of length k that can be formed from a set of n characters returns >n characters Python novice here. The goal of the following Code is, to print all possible combinations to pair n characters of the set.
The Problem is that the following code gives an output, that also has more then n characters.
In the Following Code example n=3, but in the Output there are combinations with more then 3.
Code:
def printAllKLength(set, k):
    n = len(set)
    printAllKLengthRec(set, "", n, k)

def printAllKLengthRec(set, prefix, n, k):
    if (k == 0) :
        print(prefix)
        return

    for i in range(n):
        newPrefix = prefix + set[i]
        printAllKLengthRec(set, newPrefix, n, k-1)

if __name__ == "__main__":
    print("First Test")
    set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S','T','V','W','Y']
    k = 3
    printAllKLength(set1, k)

Output:
WNT
WNV
WNW
WNY
WPQA
WPQC
WPQD
WPQE
WPQF
WPQG
WPQH
WPQI
WPQK
WPQL
WPQM
WPQN
WPQPQ
WPQR
WPQS
WPQT
WPQV
WPQW
WPQY
WRA

The aim would be to generate strictly strings of length 3, so if anyone could point me in the right direction, I would be more than grateful.

A: I rewrote you functions a bit and stripped them to the essentials:
def printAllKLength(set, k):
    printAllKLengthRec(set, "", k)

def printAllKLengthRec(set, string, k):
    if len(string) == k:
        print(string)
        return

    for c in set:
        printAllKLengthRec(set, string + c, k)
    return

if __name__ == "__main__":
    print("First Test")
    set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K',
            'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
    k = 3
    printAllKLength(set1, k)

A little hint for next time, break you sample size down to for example len(set1) = 3. then it is far easier to debug and you don't get lost in your own code.

A: You can use Itertools' combinations function. It takes an iterable and the length of the combination as parameters.
import itertools

num_char = 3
my_set = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}
combinations = itertools.combinations(my_set, num_char)
for i in combinations:
    print("".join(i))


text:
Q: Phonegap/Cordova 2.4 Inappbrowser and Ripple I'm using Inappbrowser for Cordova 2.4  and have it working at last using XCode, the browser window pops up. My problem is we need to be able to test on Windows and don't really want to recompile using Phonegap Build every time we make a change due to the time it takes. PGB is also limited currently to Phonegap 2.3.
I'm using the Ripple Phonegap emulator in Google Chrome on Windows 7 to emulate the iOS app but am having no luck getting the Inappbrowser to work. So my questions are really
1) Is it possible to use Ripple to make use of Inappbrowser?
2) Is it possible to use Ripple to make use of any Phonegap api functions?
3) Am I limited to Phonegap (Cordova) 2.0.0 as this is the version showing as available in the latest version of Ripple.
4) Is there any other way to test Phonegap for iOS functionality without rebuilding/compiling?
Many Thanks,
Gazza

A: It looks like you can open a browser window with inAppBrowser, however the events will not work.  There is a feature request for this on the project:
https://github.com/blackberry/Ripple-UI/issues/701

A: looked all over the web for sulotion and found nothing. Ripple does not suppor Inappbroswer plugin.