text:
Q: import error but in the program init, can someone help me? (Python 2.7.14) I have those errors when i'm trying to import the matplotlib.
How can i fix this?
I have install matplotlib with the pip install matplotlib and this was a succes.
But when i import the package i have this kind of error.
i see it is in the init block but how can i fix this?
i have already tried the pip matplotlib upgrade but this keeps the same problem.
i just have matplotlib uninstalled and back installed and it is the same problem.
My code:
import matplotlib.pyplot as plt

Error:
Traceback (most recent call last):
  File "C:\Python27\TEST.py", line 1, in <module>
    import matplotlib.pyplot as plt
  File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 26, in <module>
    from matplotlib.figure import Figure, figaspect
  File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 24, in <module>
    import matplotlib.artist as martist
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 7, in <module>
    from transforms import Bbox, IdentityTransform, TransformedBbox, \
  File "C:\Python27\lib\site-packages\matplotlib\transforms.py", line 35, in <module>
    from matplotlib._path import (affine_transform, count_bboxes_overlapping_bbox,
ImportError: DLL load failed: %1 is geen geldige Win32-toepassing

I have tried another code, that I found in the comments. But this generate my another error code.
Code :
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt

Error:
Traceback (most recent call last):
  File "C:\Python27\TEST.py", line 1, in <module>
    import matplotlib as mpl
  File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 1097, in <module>
    rcParams = rc_params()
  File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 933, in rc_params
    fname = matplotlib_fname()
  File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 781, in matplotlib_fname
    for fname in gen_candidates():
  File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 770, in gen_candidates
    yield os.path.join(six.moves.getcwd(), 'matplotlibrc')
AttributeError: '_MovedItems' object has no attribute 'getcwd'

Error
Little test program

A: A "p" seems to be missing from "pyplot". You have pylot instead of pyplot in the import statement.


text:
Q: Access data from dispatched action using Vuex 4 and Vue 3 Composition API In my application I have a Vuex 4 store and a Vue 3 Composition Api setup() method.
In the stores action I use axios to make an api call to get a list of bill payments.
The getAllBills action does not live directly in my Store.js file, it exists as a module.
 getAllBills({ commit }) {
            BillApiCalls.getBills().then(res => {
                commit('GET_ALL_BILLS', res.data)
            }).catch(error => console.log(error))
        },

Then in my Bill.vue file I have the setup() method and am trying to access the data to be used throughout the same Bill.vue file.
setup () {
    //Vuex store
    const store = useStore();
    const billPayments =  store.dispatch('payment/getAllBills').then(res => console.log(res));
}

If I check the console from the above .then() res returns as undefined. If I remove the .then() from the billPayments declaration and just do:
console.log(billPayments)

In the console I get
Promise {<pending>}.

Current Store:
import { bill } from './modules/bill.module';

const store = createStore({
    modules: {
        bill
    }
});

The endpoint is working, if I use Postman all of my data is returned as expected but I am having trouble figuring out how to access that data using a dispatched action with the composition api.
The Vuex 4 docs don't mention how to actually resolve the promise to access the data to be used throughout the same component.

A: An action isn't generally supposed to return data it acts on, data is a part of the state and should be accessed there; this is what another answer shows:
await store.dispatch('payment/getAllBills')
console.log(store.state.payment.bills);

The action doesn't chain promises so it cannot be correctly used. It should be:
return BillApiCalls.getBills()...

Or prefer async..await together with promise to avoid some common mistakes that can be made with raw promises.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby practical for OS X app / iOS app development? I posted a similar query recently but for Android development where I was told Android development, while just about possible using Ruby, is far from ideal.
Now I was wondering is it any more practical / possible to use Ruby to develop iOS or OS X apps in one shape or form or will it just be a matter of mastering Ruby then using that as a basis for learning the more complex Objective-C language?

A: Try Rubymotion.
It's far from free, but if you have U$200 to spare, it might be a good choice.


text:
Q: Custom Template & Rapido Breaks URL Paths Outline
I have a custom type (Dexterity) called "Gallery Profile", for this type I went into the ZMI (portal_skins/custom), created a new "Page Template" and wrote a custom template for my gallery. The gallery contains a bunch of lower down images and one main image of the owner of the gallery, like a News Item view but a gallery tacked on the bottom.
The customer wants this main image to be published to Facebook when someone hits 'Share' and some more specific info in the title when published.
Work carried out
Configured a Rapido script to write the 'og:image' meta data etc HTML that is required to get this to work (the default Plone stuff only publishes the sites logo unless you're viewing one Image type).
If I go to test the HTML coming out of Rapido via direct web address it works swimmingly. (site.com/@@rapido/og_share/block/og_share) - I'm on the slightly older version of Rapido hence the non-plural version of block.
The problem
If you go to my gallery page where we have applied the template, then check the HTML, all of the OG meta data is pointing to the template instead of the current page its on.
This effects queries too (if for example you're using a script to find out what images are within a folder) - it searches /my_template instead of site.com/a_folder/my_template_is_on
In the Rapido Python file I've tried things like:
context.content.absolute_url()
context.content.absolute_url_path()
context.request['URL']
context.request['VIRTUAL_URL']
context.request['ACTUAL_URL']

... and probably more as I've been at this a while.
If you're not on the custom template, it works.
To Reproduce

*

*Create a custom template

*Assign it as the default view of a folder or any type.

*In your template put <div tal:replace="structure python:context.REQUEST"></div> (just to see the difference)

*In your Rapido try using context.app.log() and any of the above

*Refresh your templated folder while checking the logs and the output from the context.REQUEST stuff.

*You will see the differences and how Rapido is having a hard time getting the URL of the page you are on even though its there.

I've always had this problem with Rapido I just tend to work around it but in this particular situation I am stumped.
So in summary

*

*Am I being an idiot and missing something obvious?

*Is this possible?

Thank you for your time.


text:
Q: Textchange event not working I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the
 or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX

Preview

Title

Content

    Title
    <asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
    Content
    <asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
    <asp:Button ID="Submit" runat="server" Text="Submit" />

.CS

protected void Titletxt_TextChanged(object sender, EventArgs e)
{
    NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
    NewsContentPreview.InnerText = Contenttxt.Text;
}

I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(

A: You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:

The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.

So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.

A: Just add this script function in your code and in body write onload and call that function.
Javascript:

<form id="form1" runat="server">

Preview

Title

Content

Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit"  />

</form>

A: Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
        <asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
            <asp:TextBox ID="Contenttxt"  ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.

A: Try this it will work this how change event call using jquery dont forget to add google apis

A: One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server"  UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>

Preview

Title

Content

Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />

</ContentTemplate>
</asp:UpdatePanel>

.CS
 protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}


text:
Q: Why Is My Custom Android ArrayAdapter Not Refreshing Its ListView When New Data Is Added To The Array? As part of my Android app, I am integrating a very simple custom group chat feature; this is just a proof-of-concept feature. I am aware of the fact that this is transient, and that my chats disappear whenever I restart my app. My app uses Fragments and a ViewPager to create tabs within my app.
What I have backing this feature is a LinkedList which holds Message objects (send time, sender name, message). Whenever a chat is sent or received, it is added to the LinkedList. At the start of my MainActivity.java, I declare the list
public static LinkedList<Message> chatList;

In the onCreate method, I initialize the list
chatList = new LinkedList<Message>();

I have a listener thread that runs in the background that listens for incoming messages. I passed the chatList into this thread in its constructor
MyListener myListener = new MyListener(MainActivity.this, chatList);
Thread listenerThread = new Thread(myListener);
listenerThread.start();

Whenever the listener thread receives a message, it sticks it into the LinkedList
chatList.add(new_message_object);

To display the chats, I use a ListView that is backed by a custom ArrayAdapter, in which I have overridden the getView() method. The ArrayAdapter gets the array from the toArray() method of my LinkedList and displays the chats on the screen.
This process almost works. Whenever chats are received, the LinkedList is successfully populated. The problem is getting the ListView to immediately update and display the chats. If I switch to a new fragment/tab within my app, then switch back to my chat tab, then the list is populated; but, I have to do this whenever I want to see any new chats.
This is also true for any chats I enter locally (i.e., within my chat feature). It is still added to the LinkedList, but the ListView does not refresh.
I don't want to use a SwipeRefreshLayout, I would rather the list update itself. I created a method within the custom ArrayAdapter
public void refreshList(){
    this.notifyDataSetChanged();
}

I call this whenever a new message object is added to the LinkedList, but it is not refreshing the list.
So, what am I doing incorrectly? Like I said, I would prefer the ListView update itself like a proper chat program does.
Thanks
EDIT:
As requested, here is my custom ArrayAdapter
public class CustomArrayAdapter extends ArrayAdapter {

    Context context;
    int resource;
    Object[] objects;

    public CustomArrayAdapter(Context context, int resource, Object[] objects) {
        super(context, resource, objects);
        this.context = context;
        this.resource = resource;
        this.objects = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        MessageHolder messageHolder = null;

        if(row == null){
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(resource, parent, false);
            messageHolder = new MessageHolder();
            messageHolder.chat_information = (TextView) row.findViewById(R.id.chat_information);
            messageHolder.chat_message = (TextView) row.findViewById(R.id.chat_message);

            row.setTag(messageHolder);
        } else {
            messageHolder = (MessageHolder) row.getTag();
        }

        Message item = (Message) objects[position];
        messageHolder.chat_information.setText(item.getSenderName() + Constants.NEWLINE + item.getSendTime());
        messageHolder.chat_message.setText(item.getMessageText());

        return row;
    }

    public void refreshList(){
        this.notifyDataSetChanged();
    }

    private class MessageHolder {
        TextView chat_information;
        TextView chat_message;
    }
}

EDIT 2:
I am adding my Chat.java fragment.
public class Chat extends Fragment {

    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.chat, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View rootView, Bundle savedInstanceState) {
        super.onViewCreated(rootView, savedInstanceState);
        displayChats();
    }

    @Override
    public View getView() {
        Button sendChatButton = (Button) rootView.findViewById(R.id.text_send);
        sendChatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Date rightNow = new Date();
                SimpleDateFormat timeSDF = new SimpleDateFormat(Constants.SIMPLE_TIME);
                SimpleDateFormat dateSDF = new SimpleDateFormat(Constants.SIMPLE_DATE);
                SharedPreferences myAppPreferences = getContext().getSharedPreferences(Constants.PREFS_NAME, getContext().MODE_PRIVATE);
                EditText chatEntryWindow = (EditText)rootView.findViewById(R.id.chat_text_compose);
                String message = chatEntryWindow.getText().toString();
                String username = myAppPreferences.getString("username", Constants.TABLET_ID);
                Message myMessage = new Message(username, message, 0, dateSDF.format(rightNow), timeSDF.format(rightNow));
                CustomArrayAdapter caa = new CustomArrayAdapter(getActivity(), R.layout.outgoing_line_of_chat, MainActivity.chatList);
                caa.add(myMessage);
                caa.notifyDataSetChanged();
                new SendChat(getActivity(), message, username).execute();
            }
        });
        return super.getView();
    }

    public void displayChats(){
        ListView list = (ListView) rootView.findViewById(R.id.chat_text_display);
        ArrayAdapter adapter = new CustomArrayAdapter(getActivity(), R.layout.outgoing_line_of_chat, MainActivity.chatList);
        list.setAdapter(adapter);
    }
}

A: use the following after inserting new data in array adapter:
yourAdapterName.notifyDataSetChanged();

A: Your CustomArrayAdapter does not use your LinkedList. It uses an Object[]. I assume, from your question and comments, that when you create your CustomArrayAdapter, at that point, you call toArray() on the LinkedList to get your Object[].
At this point, though, the Object[] is completely decoupled from the LinkedList. Suppose, at the outset, the LinkedList has 5 Message objects. You call toArray(), and you get an Object[5] containing those 5 Message objects. You later call add() on the LinkedList, to add a 6th Message. The Object[5] is still an Object[5] and knows nothing about that 6th Message. The only way the AdapterView will update is if you replace the CustomArrayAdapter entirely.
So, get rid of the Object[]. ArrayAdapter takes a List in half of its constructors. So, replace:
public class CustomArrayAdapter extends ArrayAdapter {

    Context context;
    int resource;
    Object[] objects;

    public CustomArrayAdapter(Context context, int resource, Object[] objects) {
        super(context, resource, objects);
        this.context = context;
        this.resource = resource;
        this.objects = objects;
    }

with:
public class CustomArrayAdapter extends ArrayAdapter<Message> {

    Context context;
    int resource;

    public CustomArrayAdapter(Context context, int resource, List<Message> messages) {
        super(context, resource, messages);
        this.context = context;
        this.resource = resource;
    }

Then, in getView(), replace Message item = (Message) objects[position]; with Message item=getItem(position);.
Finally, when a new Message arrives, call add() on the CustomArrayAdapter, which will both update your List<Message> and update the attached AdapterView.

A: Change the code like this . This will not make too many changes ,
public class CustomArrayAdapter extends ArrayAdapter {

    Context context;
    int resource;
    List objects ;
    Activity activity ;

    public CustomArrayAdapter(Context context, int resource, List objects) {
        super(context, resource, objects);
        this.context = context;
        this.resource = resource;
        //clone the arraylist.
        this.objects = new ArrayList(objects);
        activity = (Activity) context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        MessageHolder messageHolder = null;

        if (row == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            row = inflater.inflate(resource, parent, false);
            messageHolder = new MessageHolder();
            messageHolder.chat_information = (TextView) row.findViewById(R.id.chat_information);
            messageHolder.chat_message = (TextView) row.findViewById(R.id.chat_message);

            row.setTag(messageHolder);
        } else {
            messageHolder = (MessageHolder) row.getTag();
        }

        Message item = (Message) objects.get(position);
        messageHolder.chat_information.setText(item.getSenderName() + Constants.NEWLINE + item.getSendTime());
        messageHolder.chat_message.setText(item.getMessageText());

        return row;
    }

    public void setObjects(List newObjects)
    {
        if (objects != null)
        {
            objects.clear();
            objects.addAll(newObjects);
        }
    }

    public void refreshList() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                notifyDataSetChanged();
            }
        });

    }

    private class MessageHolder {
        TextView chat_information;
        TextView chat_message;
    }
}

And also one each chat message call setObjects() method with the linked list and call refreshList() method


text:
Q: Gropuing the data and show the data in table in AngularJS I am using AngularJS and trying to display data in tabular format.
This is the array I am trying to format:
 $scope.MyList = [{
            id: "559e2bbc9a496034557d6d84",
            text: "Data Sources",
            topParentId: "559e2bbc9a496034557d6d84",
            topParentText: "Data Sources"
        }, {
            id: "559e2bbc9a496034557d6d83",
            text: "India",
            topParentId: "559e2bbc9a496034557d6d83",
            topParentText: "India"
        }, {
            id: "559e2bbc9a496034557d6d82",
            text: "MH",
            topParentId: "559e2bbc9a496034557d6d83",
            topParentText: "India"
        }];

Checkout this fiddle about the implementation details:
Currently data is shown as
559e2bbc9a496034557d6d84
    Data Sources

559e2bbc9a496034557d6d83
     India
     MH

Instead I want to show data in tabular format

559e2bbc9a496034557d6d84    |     Data Sources
559e2bbc9a496034557d6d83    |     India   MH

So far I have tried this:

            Topic
            Tags

            {{tag.topParentText}}

{{tag.text}}

But I am not able to get the desired output. Please help

A: I edited your JSFiddle and put your table in to see what was going on. It looks like it nearly does what you want. As best I can tell, the problem is that you're completely hiding the first  in some cases. Instead, just hide the text inside it.
Here's my version of your JSFiddle that I think works the way you want: http://jsfiddle.net/4Dpzj/162/

A: You can acheive this thing even with Css also
HTML where I applied changes

Multiple Grouping Parameters

{{item.topParentId}}

{{item.text}}

        <form role="form" ng-submit="AddItem()">
            <input type="text" data-ng-model="item.groupfield" placeholder="Group">
            <input type="text" data-ng-model="item.whatever" placeholder="Item">
            <input type="text" data-ng-model="item.deep.category" placeholder="Category">

            <input class="btn" type="submit" value="Add Item">
        </form>

Fiddle for demo:http://jsfiddle.net/4Dpzj/163/


text:
Q: Applying a filter in a Fluent NHibernate mapping using a lambda referencing an inherited property? Is there any way to specify in a fluent nhibernate mapping file a way to only conditionally pull values into a business entity?
My current mapping snippet is:
            HasMany(m => m.GroupUsers)
            .Table("GroupUsers")
            .KeyColumns.Add("UserEntityId")
            .Inverse()
            .Cascade.All();

Ideally, I'd like to have this (which compiles but throws a runtime error that gu isn't defined):
            HasMany(m => m.GroupUsers)
            .Table("GroupUsers")
            .KeyColumns.Add("UserEntityId")
            .Where(gu => gu.DeleteDate == null)
            .Inverse()
            .Cascade.All();

The crux of the issue is that I'd like the mapping to only pull back those group users entries with a null delete date.
Edit:  Delete date is on a base class

A: From the FluentNhibernate API documentation:

T Where(Expression> where)
Sets the where clause for this one-to-many relationship. Note: This
  only supports simple cases, use the string overload for more complex
  clauses.

It seems filtering for base class properties is belongs to the "complex" cases.
So you should use the Where(String) overload (I haven't tested the syntax...):
HasMany(m => m.GroupUsers)
            .Table("GroupUsers")
            .KeyColumns.Add("UserEntityId")
            .Where("DeleteDate is null")
            .Inverse()
            .Cascade.All();

A: I had the same issue and since I didn't believe this should be a "complex" case I ended up changing one line in the FluentNH source code which resolved it. I made a pull request but until it gets merged (or if it doesn't get merged at all) you can build it from here: https://github.com/alexDevBR/fluent-nhibernate/
EDIT: It was merged.


text:
Q: How do you customize SonarLint rules in IntelliJ IDEA? Is it possible to have SonarLint for IntelliJ IDEA enforce only the rules I have enabled on my Sonar server?

A: For Android Studio Chipmunk , Dolphin 2022, Bumblebee and Arctic Fox
File >> Settings >> Tools >> SonarLint >> Rules
Then select your project language and any rule then check/uncheck it, you can edit its options (if exist)

A: As it is now possible with the current release of SonarLint (I'm using version 3.0.0.2041), people might be interested in the solution.

*

*File -> Settings -> Other Settings -> SonarLint General Settings

*Click on the green + in "SonarQube servers" :

*

*Enter a name (ex : SonarQube / localhost)

*Select SonarQube and enter URL like http://localhost:9000

*Authentication : select your user token or your login/pwd

*Click on Finish

*Click on "Update binding" to synchronize with the SonarQube server

*Go to SonarLint Project Settings and bind your project to the SonarQube project

Thus, when you open your files, SonarLint will automatically retrieve the SonarQube server's issues.

A: SonarLint 1.0 for Eclipse and IntelliJ do not allow to edit the quality profile (or set of rules) to be used for the analysis. Moreover, SonarLint 1.x works completely independently of a SonarQube server (having a SonarQube server is not a requirement), and therefore does not have the ability to reuse a quality profile defined there.
SonarLint 2.0 will have an optional mode that connects to a SonarQube server, and will offer this feature - but this isn't available yet.

A: These connections settings for SonarLint in the latest version of IntelliJ (2020.2) are in the Preferences window at Tools>SonarLint>Project Settings.


text:
Q: Following tutorial openstack instal guide I am follwing this tutorial http://docs.openstack.org/mitaka/install-guide-ubuntu/keystone-install.html
I dont pass on this part:
Edit the /etc/apache2/apache2.conf file and configure the ServerName option to reference the controller node: ServerName controller but I dont find ServerName in file apache2.conf It output error: unable to establish connection to http //controller:35357/v3/services

A: Add that directive in a new line, then restart apache2 service, then verify apache2 service is running.
Steps 2 and 3 in apache configuration are very important.


text:
Q: "Slice lists" and "the ellipsis" in Python; slicing lists and lists of lists with lists of slices Original question:  Can someone tell me how to use "slice lists" and the "ellipsis"?  When are they useful?  Thanks.
Here's what the language definition says about "slice_list" and "ellipsis"; Alex Martelli's answer points out their origin, which is not what I had envisioned.
[http://docs.python.org/reference/expressions.html#tok-slicing][1]

5.3.3. Slicings

extended_slicing ::=  primary "["
  slice_list "]"
slice_list       ::=  slice_item (","
  slice_item)* [","]
slice_item       ::=  expression |
  proper_slice | ellipsis

ellipsis         ::=  "..."
[1]:
  http://docs.python.org/reference/expressions.html#tok-slicing

In case anyone (as I was) is looking for ways to attack a list (or a list of lists) with a list of slices, here are 5 ways to get a list of elements from a list that are selected by a list of slices and 2 ways to do the same thing to a list of lists, in that case applying one slice per list.  The output's in a comment at the end.  I find h5, the example that uses nested for loops, the hardest to understand if meaningful variable names aren't used (updated).
#!/usr/bin/env python

import itertools

puz = [(i + 100) for i in range(40)]
puz1 = list( puz)
puz2 = [(i + 200) for i in range(40)]
puz3 = [(i + 300) for i in range(40)]
puzs = [puz1,puz2,puz3]

sa = slice( 0,1,1)
sb = slice( 30,39,4)
sc = slice( -1, -15,-5)
ss = [sa,sb,sc]

def mapfunc( a,b):
    return a[b]

f = map( mapfunc,[puz] * len(ss),ss)
print "f =  ", f  #same as g below

g = [ puz[i]
    for i in ss ]
print "g =  ",g  #same as f, above

h1 = [ i
    for i in itertools.chain( puz[sa],puz[sb],puz[sc]) ]
print "h1 = ", h1  #right

h2 = [ i
    for i in itertools.chain( *(map( mapfunc,[puz] * len(ss),ss))) ]
print "h2 = ",h2  #right

h3 = [ i
    for i in itertools.chain( *f) ]
print "h3 = ",h3  #right

h4 = [ i
    for i in itertools.chain( *g) ]
print "h4 = ", h4 #also right

h5 = []
for slice_object in ss:
    for list_element in puz[slice_object]:
        h5.append( list_element)
print "h5 = ", h5  #right, too

print "=============================="

hh1 = [ i
    for i in itertools.chain( *(map( mapfunc,puzs,ss))) ]
print "hh1 =  ",hh1  #right

puz_s_pairs = zip( puzs,ss)
#print "puz_s_pairs = ",puz_s_pairs
hh2 = [ i
    for i in itertools.chain( *(map( mapfunc,*zip( *puz_s_pairs)))) ]
print "hh2 =  ",hh2  #right

'''
>>> execfile(r'D:/cygwin/home/usr01/wrk/py/pyexpts/list_of_slices_of_list.02.py')
f =   [[100], [130, 134, 138], [139, 134, 129]]
g =   [[100], [130, 134, 138], [139, 134, 129]]
h1 =  [100, 130, 134, 138, 139, 134, 129]
h2 =  [100, 130, 134, 138, 139, 134, 129]
h3 =  [100, 130, 134, 138, 139, 134, 129]
h4 =  [100, 130, 134, 138, 139, 134, 129]
h5 =  [100, 130, 134, 138, 139, 134, 129]
==============================
hh1 =   [100, 230, 234, 238, 339, 334, 329]
hh2 =   [100, 230, 234, 238, 339, 334, 329]
'''

A: Numpy uses them to implement array slicing.

A: Slice lists and ellipsis were originally introduced in Python to supply nice syntax sugar for the precedessor of numpy (good old Numeric).  If you're using numpy (no reason to go back to any of its predecessors!-) you should of course use them; if for whatever strange reason you're doing your own implementation of super-flexible multi-dimensional arrays, you'll definitely want to study the way numpy uses them and probably imitate it closely (it is pretty well designed after all).  I can't think of good uses beyond multi-dimensional arrays.

A: I'm not too sure about ellipsis, so I will not address that, lest I give you a bad answer.
Here goes list slicing:
I hope you know that list indeces begin at 0.
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Indexing into a list:
l[0]
>>> 0

l[5]
>>> 5

Slicing a list. The first index is included, but not the last:
l[0:5]
>>> [0, 1, 2, 3, 4]

l[2:5]
>>> [2, 3, 4]

Return the whole list as ONE slice:
l[:]
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Get a slice of the list containing every element including and after the 3rd index:
l[3:]
>>> [3, 4, 5, 6, 7, 8, 9]

Get a slice of the list containing every element upto but not including the 5th index:
l[:5]
>>> [0, 1, 2, 3, 4]

Here is something that you would not expect python to do:
l[5:18]  # note: there is no 18th index in this list
>>> [5, 6, 7, 8, 9]


text:
Q: If someone knows my Gmail ID and password is it possible to view my YouTube browsing history data from their own PC or mobile? If someone knows my Gmail ID and password is it possible to view my YouTube browsing history data from their own PC or mobile ? If my sync is off in my mobile.

A: Yes if you're logged into google/youtube on the device you're viewing youtube on then the history is added to your google account.
You can view this history (and amend it) here: myactivity.google.com
This will be viewable on any device logged into the same account (in youtube history and google history), or if someone signs into this account on any device.


text:
Q: TeeChart for .NET 2016 and TeeChart for .NET 2006 Our customer has purchased the TeeChart for .NET 2016 this Nov.
And now they got the questions below:

*

*They found out that the chart is more unclear than the TeeChart 2006.

2016

2006

*Is it possible to let the code is the same as TeeChart 2006 for calling Chart Editor Mode?

(I cannot past the code here and don't know how to attache file here, if you need the code, please kindly let me know)

A:

*

*They found out that the chart is more unclear than the TeeChart 2006.

Unfortunately, I haven't seen differences between TeeChart 2016 and TeeChart 2006 adapting the codes because the results, are shown similar in both versions.  You can see below the examples:
TeeChartForNet V2016
 public Form1()
            {
                InitializeComponent();
                InitializeChart();
            }
            private void InitializeChart()
            {
                Steema.TeeChart.Styles.Points point1 = new Steema.TeeChart.Styles.Points(tChart1.Chart);
                this.Text = tChart1.ProductVersion;
                tChart1.Aspect.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;

                tChart1.Walls.Visible = false;
                tChart1.Aspect.View3D = false;
                tChart1.Axes.Bottom.Grid.Visible = true;
                tChart1.Axes.Left.Grid.Visible = true;
                tChart1.Axes.Left.AxisPen.Visible = true;
                tChart1.Axes.Left.Grid.Style = System.Drawing.Drawing2D.DashStyle.Dash;

                point1.FillSampleValues(100);
                point1.Color = Color.Blue;
                point1.Pointer.Pen.Color = Color.Black;
            }

TeeChartForNet V2006
public Form1(){

            InitializeComponent();
            InitializeChart();
        }
        private void InitializeChart()
        {
            Steema.TeeChart.Styles.Points point1 = new Steema.TeeChart.Styles.Points(tChart1.Chart);
            tChart1.Panel.Gradient.Visible = false;
            tChart1.Panel.Color = Color.White;
            tChart1.Walls.Visible = false;
            this.Text = tChart1.ProductVersion;
            tChart1.Aspect.View3D = false;
            point1.FillSampleValues(100);
            point1.Color = Color.Blue;
            point1.Pointer.Pen.Color = Color.Black;
        }

Could you please, check if the above code TeeChartForNet 2016 works in you end?

*Is it possible to let the code is the same as TeeChart 2006 for calling Chart Editor Mode?

The Chart Editor can show using same code lines, in TeeChart 2016 than TeeChart 2006. I have added below different lines code that show what you need do:
Show Chart editor without Editor Component
 tChart1.ShowEditor();

Show  Chart Editor with Editor Component
 ed1.ShowModal();


text:
Q: View an image in WebBrowser1 and resize it I created, through a UserForm in Excel, a simple image viewer; the image is displayed by means of a WebBrowser1 control.
I am looking for ways to resize the image to fit the size of the control and / or resize the control to match its size to those of the images.
I tried to derive the image dimensions with
 With Me.WebBrowser1
     .Navigate ImagePath
     .Width = .Document.images (1) .Width
     .Height = .Document.images (1) .Height
 End With

but it seems that you cannot access from VBA to
WebBrowser1.Document.images

Does anyone know of a way to do this?
Thank you very much, this worked (cFiles (Current) is a File object)
 With Me.WebBrowser1
     .Navigate "about: blank"
     Do While .ReadyState <> READYSTATE_COMPLETE
         DoEvents
     Loop
     .Document.Write "<body style = 'background-color: buttonface; overflow: hidden;'> <img style = 'width: 100%;' src = '"& cFiles (Current) .Path &"'> </body> "

I am left with the problem of detecting the height and width of the image in order to center the image in the UserForm.
So far I have used a hidden Image control with AutoSize = True but it is an extremely inelegant solution and with some images (like png) it doesn't work.


text:
Q: How to use WSAdmin to analyze Heap Dump files (.dmp) I have a .dmp file of a WAS machine.. How can I use WSAdmin.sh to analyze the heap dump?
There are not many resources on this..

A: WSAdmin is only for WAS administrative operations and does not provide any tooling to perform dump analysis, at least that I'm aware of.
I think what you're looking for is something like the Eclipse Memory Analyzer Tool (MAT), which can be found here.  It's specifically designed for processing and analyzing Java dump files.


text:
Q: Rest Api to create a subfolder in document library My code to create a sub folder is behaving abnormally as sometime it works fine and create a sub folder but other time it throws error.
var fName = $("#ID").val();
    CheckFolderExist(fName);
createInfo.set_url("https://test.sharepoint.com/sites/test1/testdoclib/" + "rootFolder" + "/" + folderName + "/" + fileName);

function CreateFolder()
{
var url_web = _spPageContextInfo.webAbsoluteUrl;
    var docLibrary = "testdoclib";
    var folder_name = $("#ID").val();
    var folder_path =  docLibrary + "/" + "rootFolder" + '/' + folder_name;"/"

    jQuery.ajax({
        'url' : url_web + "/_api/Web/Folders/Add('"+ folder_path + "')",
        'type' : 'POST',
        'headers' : {
            'accept' : 'application/json; odata=verbose',
            'content-type' : 'application/json; odata=verbose',
            'X-RequestDigest' : $('#__REQUESTDIGEST').val()
        },
        'success' : function (evt){
            // folder has been created
//alert("Folder Created");
return;
        },
        'error' : function (jqXHR, textStatus, errorThrown){
            // handle the error
            alert("Error Folder Creating");
        }
    });
}

What I have observed during debug is code inside function CheckFolderExist(fName) is running after it has executed the next line i.e  createInfo.set_url. How can I fix this?

A: Although I do not have the definition of your CheckFolderExist function, I can guess that it is an HTTP request which is executing asynchronously. This means that sometimes it may finish executing before the lines that follow (e.g. createInfo.set_url) are executed, and sometimes after that line is executed.
You need to integrate the code that is dependent on the result of the HTTP request (made inside the CheckFolderExist function) in the promise returned by the HTTP request. Namely, the createInfo.set_url statement and CreateFolder function should be implemented somewhere inside the CheckFolderExist function.
Your code should look something like this:
var folderName = $('#ID').val();
var folderPath = '/path/to/' + folderName;
var libraryName = 'MyLibrary';
var fileName = 'MyFile.txt';

function CheckFolderExist(folderPath) {
    var context = SP.ClientContext.get_current();
    var folder = context.get_web().getFolderByServerRelativeUrl(folderPath);

    context.load(folder, 'Exists', 'Name');
    context.executeQueryAsync(successHandler, errorHandler);

    function successHandler() {
        // This executes if folder exists.
    }

    function errorHandler(sender, args) {
        if (args.get_errorTypeName() === 'System.IO.FileNotFoundException') {

            // Folder doesn't exist at all.
            CreateFolder();

        }
        else {
            console.log(sender);
            console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
    }
}

function CreateFolder() {
    var context = new SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(libraryName);

    var folderCreateInfo = new SP.ListItemCreationInformation();
    folderCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
    folderCreateInfo.set_leafName(folderName);
    var listItem = list.addItem(folderCreateInfo);
    listItem.update();

    context.load(listItem);
    context.executeQueryAsync(successHandler, errorHandler);

    function successHandler() {
        // Folder has been created.
        CreateFiles();
    }

    function errorHandler(sender, args) {
        console.log(sender);
        console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
}

function CreateFiles() {
    // Here execute your code for creating one or more files.
}

Note that I did not pay attention to making this code adhere to the best practices. I just wanted to focus on answering the question.


text:
Q: 'NoneType' object has no attribute 'insert' - i'm having trouble appending to a 2D array i'm trying to make a game, however i cannot figure out the code to go into
def deckgeneration(self):
fulldeck = [[]]
for i in range (1,deck):
    name =  takerandomline()
    speed = random.randint(1,5)
    strength = random.randint(1,100)
    agility = random.randint(1,10)
    flexibility = random.randint(1,10)
    fulldeck[i]= fulldeck.insert([name,speed,strength,agility,flexibility])
return fulldeck

to append the 5 variables into a 2D list for each count of 'i' since when I get to the 9th line in the above function it doesn't seem to work no matter what I try- the most recent error is "AttributeError:'NoneType' object has no attribute 'insert'"

A: This is because you are using list.insert() in an incorrect way.
Insert requires two parameters: the index and the element you want to insert.
index = 0 # Example
fulldeck[i]= fulldeck.insert(index, [name,speed,strength,agility,flexibility])

Or, you can always use list.append(), that requires no index since it always add the element to the end of the list.
 fulldeck[i]= fulldeck.append([name,speed,strength,agility,flexibility])


text:
Q: SQL recursive query that gets all ancestors of an item ID       parent_id   name
---------------------
1        2            first
2        4            second
3        3            third
4        5            fourth
5        -           fifth

Ancestors  list of  first should be  (2, 4, 5)

A: You can use something like this:
with parents as
(
  select ID, parent_ID
  from t
  where parent_ID is not null
  union all
  select p.ID, t.parent_ID
  from parents p
    inner join t on p.parent_ID = t.ID
      and t.parent_ID is not null
      and t.ID <> t.parent_ID
)
select *
  , parents = '(' + stuff
    (
      (
        select ', ' + cast(p.parent_ID as varchar(100))
        from parents p
        where t.ID = p.ID
        for xml path('')
      ), 1, 2, ''
    ) + ')'
from t
order by ID

SQL Fiddle with demo.
This combines two very common T-SQL techniques - using a CTE to get a hierarchy and using FOR XML PATH to get a CSV list.

A: with name_tree as (
   select id, parent_id, name
   from the_unknown_table
   where id = 1 -- this is the starting point you want in your recursion
   union all
   select c.id, c.parent_id, c.name
   from the_unknown_table c
     join name_tree p on p.parent_id = c.id  -- this is the recursion
)
select *
from name_tree
where id <> 1; -- exclude the starting point from the overall result

SQLFiddle: http://sqlfiddle.com/#!3/87d0c/1


text:
Q: How to disable the home button of the app I want to disable the home button of my app. I achieve to disable the back button by the following code.
@Override
public void onBackPressed() {
    // Do nothing
    return;
}

Now I want to disable the home button as well.I tried by using various way as mentioned on Internet like,
@Override
public void onAttachedToWindow() {
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
    super.onAttachedToWindow();
}

But it was showing the following exception
java.lang.IllegalArgumentException: Window type can not be changed after the window is added.
                                                       at android.os.Parcel.readException(Parcel.java:1687)
                                                       at android.os.Parcel.readException(Parcel.java:1636)
                                                       at android.view.IWindowSession$Stub$Proxy.relayout(IWindowSession.java:953)
                                                       at android.view.ViewRootImpl.relayoutWindow(ViewRootImpl.java:5695)
                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1758)
                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1258)
                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6348)
                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                                                       at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                                                       at android.view.Choreographer.doFrame(Choreographer.java:619)
                                                       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

So after searching I moved to the another solution like,
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);

but still I am able to interact with the home button.
As well as I tried by using this way.
//disable the home button
    @Override
    protected void onPause() {
        super.onPause();
        Intent intent = new Intent(LoginActivity.this,LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(intent);
    }

This is also the good solution ,but not applicable for here.
My target device is starting from API19 and above. Please help if anyone have the solution.


text:
Q: specific rows style for in custom list table using WP_List_Table I am building a custom WordPress plugin where I create a custom list table for entities in a custom database table, extending the WP_List_Table class.
Everything works as expected but I want to style each row based on the value of a specific column of the row that is returned from the DB.
The iteration of the columns for each row happens inside the column_default() function:
/**
 * Render a column when no column specific method exists.
 *
 * @param array $item
 * @param string $column_name
 *
 * @return mixed
 */
public function column_default( $item, $column_name ) {

    switch ( $column_name ) {
        case 'id':
            return $item[$column_name];
        default:
          return $item[$column_name];
    }
}

For example:
If the viw_status column of the current item that is printed on the list table equals 1 ($item['viw_status '] == 1), the current item's row must have green background color otherwise grey something.
Is there a any way to apply a custom css class to a row based on the values of its columns?

A: It depends where you want to apply your custom css class.
CSS class for table row
If you want to add the custom class to the
 element, I recommend to overwrite the function single_row like so:
public function single_row( $item ) {
    $cssClass = ($item['view_status '] == 1) ? 'make-it-green' : 'make-it-grey';
    echo '
';
    $this->single_row_columns( $item );
    echo '
';
}

CSS class for table cell
Use the column_{column name} functions like you have outlined it with column_default and put a HTML tag as a wrapper within the cell. For example a span element:
public function column_default( $item, $column_name ) {
    $cssClass = ($item['view_status '] == 1) ? 'make-it-green' : 'make-it-grey';
    switch ( $column_name ) {
        case 'id':
            return ''.$item[$column_name].'';
        default:
          return $item[$column_name];
    }
}


text:
Q: How to modify user's display name in MS Bot Framework while using directline channel A bot is being developed using AAD authentication, in which we have chosen directline as our channel. Now, we have tried displaying the username of the authenticated person in the place of userid in the below snippet.
<script>
BotChat.App({
    directLine: { secret: "***********" },
    user: { id: 'userid' },
    bot: { id: 'botid' },
    resize: 'detect'
}, document.getElementById("bot"));
</script>

A: Change
user: { id: 'userid' },

To
user: { id: yourUserIdFromAad },

You can even add  user: { id: yourUserIdFromAad, name: yourUserDisplayName },

A:
we have tried displaying the username of the authenticated person in the place of userid in the below snippet

I assume that you are a .NET developer and you'd like to dynamically pass user identity to BotChat, you can try the following approach:

*

*In ASP.NET MVC application, you can get user information from controller and store it in ViewBag, then you can retrieve the value from ViewBag and dynamically pass it as userid when you initiate your BotChat. The following code snippet is for your reference.

In controller:
public ActionResult Chat()
{
    ViewBag.userinfo = User.Identity.GetUserName();
    return View();
}

In view:
<script>
    $(function () {
        var userid = '@(ViewBag.userinfo)';
        //alert(userid);

        BotChat.App({
            directLine: { secret: "{directline_secret}" },
            user: { id: userid},
            bot: { id: 'fehanbotdg' },
            resize: 'detect'
        }, document.getElementById("bot"));
    })
</script>

Test result:

*

*In ASP.NET webform application, you can get user information from code behind and store it in a hiddenfield, then you can get the user information from hiddenfield and use it to initiate your BotChat.


text:
Q: Taking input as array in swagger not working I have the following code for my swagger documentation. Here I am trying to create an API where I want to take input as an array of objects. so far I am doing like following.
{
    method: 'POST',
    path: '/api/Route',
    handler: function(request, reply) {
        //some operations
        reply('Success');
    },

    config: {
        description: 'Create a Route',
        tags: ['api', 'user'],
        auth: 'UserAuth',
        validate: {
            payload: {
                "array": [{
                        userId: Joi.string().trim().required(),
                        status: Joi.number().required()
                    },
                    {
                        userId: Joi.string().trim().required(),
                        status: Joi.number().required()
                    },
                    {
                        userId: Joi.string().trim().required(),
                        status: Joi.number().required()
                    }
                ]
            }
        },
        plugins: {
            'hapi-swagger': {
                responseMessages: swaggerDefaultResponseMessages
            }
        }
    }
}

so what actually going on when I run the above code the swagger creates the documentation like this.
this is a link to the image. so please can anybody tell me why I am not getting the whole array in swagger documentation instead getting only one element of the array. and I also saw the Following question but unable to understand in which file they are making these changes. Could anybody help? Thanks in advance.

A: You could use the array validation of Joi. Then in the input, you could just pass the array into it. for that, you just need to write the following code in your payload instead of what you are writing at present.
payload: {
         userData: Joi.array().items({
             userName: Joi.string(),
             status: Joi.string()
         })
     }

after that you swagger documentation looks something like this.

userData is your array of objects. and you could give input array of objects as following.
"userData": [{
             "userName": "string", // objects
             "status": "string"
         },
         {
             "userName": "string", // objects this way you can add more
             "status": "string"
         }
     ]


text:
Q: What is wrong with the SQL? I'm trying to use PDO, so i got this together:
So, $_GET['word'] = "Jimi Hendrix" and $_GET['cat'] = "music".
$now = htmlentities(rawurldecode($_GET['word']));
$cat = htmlentities($_GET['cat']);

$dsn = 'mysql:dbname=DATABASE;host=localhost';
$user = "USER";
$password = "PASS";

# connect to the database
try {
    $DBH = new PDO($dsn, $user, $password);
                $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

                # the data to select
                $data = array($cat, $now);

                $STH = $DBH->prepare("SELECT id, name FROM ? WHERE name LIKE ?");
                $STH->execute($data);
    $result = $STH->fetchAll();

}
catch(PDOException $e) {
    echo "Uh-Oh, something wen't wrong. Please try again later.";
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

echo "<pre>";
print_r($result);
echo "</pre>";

But the code above is returning:
SQLSTATE[42000]: Syntax error or access violation: 1064 You Have a Syntax error in your SQL near ''music' WHERE name LIKE 'Jimi Hendrix'' on line 1

A: You can't pass the table name as a parameter for the query. You'd need to construct/execute a dynamic SQL string.

A: It is probably because you are trying to insert the table name as a parameter. You may be able to do this as a stored procedure if necessary.

A: The category is converted into a string and when the query is prepared it is converted into:
SELECT id, name FROM 'cat' WHERE name 'music'
The table shouldn't be a string, what you can do is:
# the data to select
$data = array($now);

$STH = $DBH->prepare("SELECT id, name FROM $cat WHERE name LIKE ?");
$STH->execute($data);

A: As others have said, you cannot parameterize a table name with PDO (Or any other SQL interface that I know of).
You used to be able to find table naming conventions here:
http://www.mysql.com/doc/en/Legal_names.html
But it's been Larry Ellisowned.
I'd recommend finding a regex to validate MySQL table names and using that. A basic regex would be:
/[A-Za-z][A-Za-z0-9_]*/

But that wont account for reserved words.


text:
Q: How to create Ext.Net Charts in Server Side I need to create a chart in server side. It has to be this way because it will be a dynamic number of charts. I did not find anything that could help me.
In short, I need to implement this example in server side :
http://examples2.ext.net/#/Chart/Line/Basic/
Something like this:
public class GraficoMovimentacaoDiaria : Chart
    {
        public GraficoMovimentacaoDiaria(int[] dias, int ultimodia, string StoreId)
        {
            this.StyleSpec = "background:#fff;";
            this.Shadow = true;
            this.Animate = true;
            this.StandardTheme = StandardChartTheme.Category1;
            this.LegendConfig = new ChartLegend { Position = LegendPosition.Right };
            this.Store = ?????

        }
    }

A: Please use:
this.Store.Add(new Store());

Related Ext.NET forum thread.


text:
Q: How to save the current image from viewpager? I have images in a ViewPager and I want user to can save the current image by click on a button to save the image to sd card in phone
This is my demoactivity.java
public class DemoActivity extends Activity {
Button play;
MediaPlayer mp;

public int playstop = 0;

private Button extisaw;
public void onCreate(Bundle ww) {
    super.onCreate(ww);
    setContentView(R.layout.activity_main);
    play = (Button) findViewById(R.id.saw);
    mp = MediaPlayer.create(this, R.raw.raj);
    show1();
    show2();
    play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playstop == 0) {
                    MediaHandler(mp, 1);
                    mp.start();
                    playstop = 1;

                } else {
                    MediaHandler(mp, 2);
                    mp.pause();
                    playstop = 0;
                }
            }
        });
}

private void show2()
{
    // TODO: Implement this method

    this.extisaw =
        (Button)this.findViewById
    (R.id.about);
    this.extisaw.setOnClickListener
    (new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
    });}

public void MediaHandler
(MediaPlayer mp, int e) {
    if (e == 1) {
        mp.start();
    } else {
        mp.pause();
    }
}

public void show1() {
    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    ImagePagerAdapter adapter = new ImagePagerAdapter();
    viewPager.setAdapter(adapter);
}

private class ImagePagerAdapter extends PagerAdapter {
    private int[] mImages = new int[]{
        R.drawable.a1, R.drawable.a2,
        R.drawable.a3, R.drawable.a4,
        R.drawable.a5, R.drawable.a6,
        R.drawable.a7, R.drawable.a8
        , R.drawable.a9, R.drawable.a10, R.drawable.a11, R.drawable.a12
        , R.drawable.a13, R.drawable.a14, R.drawable.a15
        , R.drawable.a16, R.drawable.a17, R.drawable.a18, R.drawable.a19
        , R.drawable.a20, R.drawable.a21, R.drawable.a22, R.drawable.a23
        ,
        R.drawable.a24, R.drawable.a25,
        R.drawable.a26, R.drawable.a27
        , R.drawable.a29,
        R.drawable.a30, R.drawable.a31
        , R.drawable.a32, R.drawable.a33, R.drawable.a34, R.drawable.a35
        , R.drawable.a36, R.drawable.a37, R.drawable.a38
        , R.drawable.a39, R.drawable.a40, R.drawable.a42
        , R.drawable.a43, R.drawable.a44, R.drawable.a45, R.drawable.a46,
        R.drawable.a47, R.drawable.a48,
        R.drawable.a49
        , R.drawable.a51,
        R.drawable.a52, R.drawable.a53
        , R.drawable.a54, R.drawable.a55, R.drawable.a56
        , R.drawable.a58, R.drawable.a59, R.drawable.a60
        , R.drawable.a61, R.drawable.a62, R.drawable.a63
        , R.drawable.a64, R.drawable.a65, R.drawable.a66, R.drawable.a67, R.drawable.a68, R.drawable.a69

        , R.drawable.a70,
        R.drawable.a71, R.drawable.a72
        , R.drawable.a73, R.drawable.a74, R.drawable.a75
        , R.drawable.a76, R.drawable.a77, R.drawable.a78
        , R.drawable.a79, R.drawable.a80, R.drawable.a81
        , R.drawable.a82, R.drawable.a83, R.drawable.a84, R.drawable.a85, R.drawable.a86, R.drawable.a87

        , R.drawable.a88,
        R.drawable.a89, R.drawable.a90
        , R.drawable.a91, R.drawable.a93
        , R.drawable.a94, R.drawable.a95, R.drawable.a96
        , R.drawable.a97, R.drawable.a98, R.drawable.a99

    };

    @Override
    public int getCount() {
        return mImages.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((ImageView) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Context context = DemoActivity.this;
        ImageView imageView = new ImageView(context);
        int padding = context.getResources().getDimensionPixelSize(
            R.dimen.padding_medium);
        imageView.setPadding(padding, padding, padding, padding);
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageView.setImageResource(mImages[position]);
        ((ViewPager) container).addView(imageView, 0);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((ImageView) object);
    }
}

}

A: This is my code
 There is 2 button
Play and stop music
And exit button and all work good
But I want to add a button for user to can save the current image of view pager to the phone memory
public class DemoActivity extends Activity {
Button play;
MediaPlayer mp;

public int playstop = 0;

private Button extisaw;
public void onCreate(Bundle ww) {
    super.onCreate(ww);
    setContentView(R.layout.activity_main);
    play = (Button) findViewById(R.id.saw);
    mp = MediaPlayer.create(this, R.raw.raj);
    show1();
    show2();
    play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playstop == 0) {
                    MediaHandler(mp, 1);
                    mp.start();
                    playstop = 1;

                } else {
                    MediaHandler(mp, 2);
                    mp.pause();
                    playstop = 0;
                }
            }
        });
}

private void show2()
{
    // TODO: Implement this method

    this.extisaw =
        (Button)this.findViewById
    (R.id.about);
    this.extisaw.setOnClickListener
    (new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
    });}

public void MediaHandler
(MediaPlayer mp, int e) {
    if (e == 1) {
        mp.start();
    } else {
        mp.pause();
    }
}

public void show1() {
    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    ImagePagerAdapter adapter = new ImagePagerAdapter();
    viewPager.setAdapter(adapter);
}

private class ImagePagerAdapter extends PagerAdapter {
    private int[] mImages = new int[]{
        R.drawable.a1, R.drawable.a2,
        R.drawable.a3, R.drawable.a4,
        R.drawable.a5, R.drawable.a6,
        R.drawable.a7, R.drawable.a8
        , R.drawable.a9, R.drawable.a10, R.drawable.a11, R.drawable.a12
        , R.drawable.a13, R.drawable.a14, R.drawable.a15
        , R.drawable.a16, R.drawable.a17, R.drawable.a18, R.drawable.a19
        , R.drawable.a20, R.drawable.a21, R.drawable.a22, R.drawable.a23
        ,
        R.drawable.a24, R.drawable.a25,
        R.drawable.a26, R.drawable.a27
        , R.drawable.a29,
        R.drawable.a30, R.drawable.a31
        , R.drawable.a32, R.drawable.a33, R.drawable.a34, R.drawable.a35
        , R.drawable.a36, R.drawable.a37, R.drawable.a38
        , R.drawable.a39, R.drawable.a40, R.drawable.a42
        , R.drawable.a43, R.drawable.a44, R.drawable.a45, R.drawable.a46,
        R.drawable.a47, R.drawable.a48,
        R.drawable.a49
        , R.drawable.a51,
        R.drawable.a52, R.drawable.a53
        , R.drawable.a54, R.drawable.a55, R.drawable.a56
        , R.drawable.a58, R.drawable.a59, R.drawable.a60
        , R.drawable.a61, R.drawable.a62, R.drawable.a63
        , R.drawable.a64, R.drawable.a65, R.drawable.a66, R.drawable.a67, R.drawable.a68, R.drawable.a69

        , R.drawable.a70,
        R.drawable.a71, R.drawable.a72
        , R.drawable.a73, R.drawable.a74, R.drawable.a75
        , R.drawable.a76, R.drawable.a77, R.drawable.a78
        , R.drawable.a79, R.drawable.a80, R.drawable.a81
        , R.drawable.a82, R.drawable.a83, R.drawable.a84, R.drawable.a85, R.drawable.a86, R.drawable.a87

        , R.drawable.a88,
        R.drawable.a89, R.drawable.a90
        , R.drawable.a91, R.drawable.a93
        , R.drawable.a94, R.drawable.a95, R.drawable.a96
        , R.drawable.a97, R.drawable.a98, R.drawable.a99

    };

    @Override
    public int getCount() {
        return mImages.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((ImageView) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Context context = DemoActivity.this;
        ImageView imageView = new ImageView(context);
        int padding = context.getResources().getDimensionPixelSize(
            R.dimen.padding_medium);
        imageView.setPadding(padding, padding, padding, padding);
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageView.setImageResource(mImages[position]);
        ((ViewPager) container).addView(imageView, 0);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((ImageView) object);
    }
}

}

A: i add my code to your activity class now try this..
public class DemoActivity extends Activity {
Button play;
MediaPlayer mp;
private int[] mImages = new int[]{
        R.drawable.a1, R.drawable.a2,
        R.drawable.a3, R.drawable.a4,
        R.drawable.a5, R.drawable.a6,
        R.drawable.a7, R.drawable.a8
        , R.drawable.a9, R.drawable.a10, R.drawable.a11, R.drawable.a12
        , R.drawable.a13, R.drawable.a14, R.drawable.a15
        , R.drawable.a16, R.drawable.a17, R.drawable.a18, R.drawable.a19
        , R.drawable.a20, R.drawable.a21, R.drawable.a22, R.drawable.a23
        ,
        R.drawable.a24, R.drawable.a25,
        R.drawable.a26, R.drawable.a27
        , R.drawable.a29,
        R.drawable.a30, R.drawable.a31
        , R.drawable.a32, R.drawable.a33, R.drawable.a34, R.drawable.a35
        , R.drawable.a36, R.drawable.a37, R.drawable.a38
        , R.drawable.a39, R.drawable.a40, R.drawable.a42
        , R.drawable.a43, R.drawable.a44, R.drawable.a45, R.drawable.a46,
        R.drawable.a47, R.drawable.a48,
        R.drawable.a49
        , R.drawable.a51,
        R.drawable.a52, R.drawable.a53
        , R.drawable.a54, R.drawable.a55, R.drawable.a56
        , R.drawable.a58, R.drawable.a59, R.drawable.a60
        , R.drawable.a61, R.drawable.a62, R.drawable.a63
        , R.drawable.a64, R.drawable.a65, R.drawable.a66, R.drawable.a67, R.drawable.a68, R.drawable.a69

        , R.drawable.a70,
        R.drawable.a71, R.drawable.a72
        , R.drawable.a73, R.drawable.a74, R.drawable.a75
        , R.drawable.a76, R.drawable.a77, R.drawable.a78
        , R.drawable.a79, R.drawable.a80, R.drawable.a81
        , R.drawable.a82, R.drawable.a83, R.drawable.a84, R.drawable.a85, R.drawable.a86, R.drawable.a87

        , R.drawable.a88,
        R.drawable.a89, R.drawable.a90
        , R.drawable.a91, R.drawable.a93
        , R.drawable.a94, R.drawable.a95, R.drawable.a96
        , R.drawable.a97, R.drawable.a98, R.drawable.a99

    };

public int playstop = 0;

private Button extisaw;
private ImagePagerAdapter adapter;
private ViewPager viewPager;
public void onCreate(Bundle ww) {
    super.onCreate(ww);
    setContentView(R.layout.activity_main);
    play = (Button) findViewById(R.id.saw);
    mp = MediaPlayer.create(this, R.raw.raj);
    show1();
    show2();
    play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playstop == 0) {
                    MediaHandler(mp, 1);
                    mp.start();
                    playstop = 1;

                } else {
                    MediaHandler(mp, 2);
                    mp.pause();
                    playstop = 0;
                }
            }
        });
}

private void show2()
{
    // TODO: Implement this method

    this.extisaw =
        (Button)this.findViewById
    (R.id.about);
    this.extisaw.setOnClickListener
    (new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
    });

}

public void MediaHandler
(MediaPlayer mp, int e) {
    if (e == 1) {
        mp.start();
    } else {
        mp.pause();
    }
}

private void saveImageIntoSdcard(Bitmap bitmap) {
    File filename = null;
    FileOutputStream out = null;
    String destination;

    try {
        String path = Environment.getExternalStorageDirectory().toString();
        destination ="/DESTINATIONFOLDER NAME/";
  File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),destination);
    filename = new File(sdCardDirectory, System.currentTimeMillis()+"image.jpg");

                out = new FileOutputStream(filename);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                        out);

                MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(),
                        filename.getName(), filename.getName());

        }
 catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public void show1() {
     viewPager = (ViewPager) findViewById(R.id.view_pager);
     adapter = new ImagePagerAdapter();
    viewPager.setAdapter(adapter);
    Button b1 = (Button) findViewById(R.id.save);
    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            int position=viewPager.getCurrentItem();
            int selectedImage=mImages[position];
            Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),selectedImage);
            saveImageIntoSdcard(largeIcon);
        }
    });
}

private class ImagePagerAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return mImages.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((ImageView) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Context context = DemoActivity.this;
        ImageView imageView = new ImageView(context);
        int padding = context.getResources().getDimensionPixelSize(
            R.dimen.padding_medium);
        imageView.setPadding(padding, padding, padding, padding);
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageView.setImageResource(mImages[position]);
        ((ViewPager) container).addView(imageView, 0);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((ImageView) object);
    }
}
}

A: Firstly add the permission to the manifest for accessing to the external storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Then you must get the bitmap of the desired image and create a file in the external storage:
Bitmap imageBitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File imageFile = new File(sdCardDirectory, "image.png");

Finally write the bitmap into the file:
FileOutputStream outStream;
    try {
        outStream = new FileOutputStream(image);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        outStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        outStream.close();
    }

You can introduce a boolean for checking if the process of writting is properly completed.

A: try this:-

int position = viewPager.setCurrentItem(mPager.getCurrentItem() - 1);
String imagePath= list.get(position);
Bitmap bmp=BitmapFactory.decodeStream(context.getContentResolver().openInputSteam(Uri.fromFile(new File(imagePath))));
    File sdCardDirectory = Environment.getExternalStorageDirectory();
    File imageFile = new File(sdCardDirectory, "image.png");
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(imageFile);
                bmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

A: try this may this help you.
    private void saveImageIntoSdcard(Bitmap bitmap) {
    File filename = null;
    FileOutputStream out = null;
    String destination;

    try {
        String path = Environment.getExternalStorageDirectory().toString();
        destination ="/DESTINATIONFOLDER NAME/";

        new File(path + destination).mkdirs();

        filename = new File(path + destination + ".jpg");
                out = new FileOutputStream(filename);
                bitmapReceipt.compress(Bitmap.CompressFormat.JPEG, 100,
                        out);
                MediaStore.Images.Media.insertImage(getActivity()
                        .getContentResolver(), filename.getAbsolutePath(),
                        filename.getName(), filename.getName());

        }
 catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

A: I have edit your code try this.

private void saveImageIntoSdcard(Bitmap bitmap) {
    File filename = null;
    FileOutputStream out = null;
    String destination;

    try {
        String path = Environment.getExternalStorageDirectory().toString();
        destination ="/DESTINATIONFOLDER NAME/";
  File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),destination);
    filename = new File(sdCardDirectory, System.currentTimeMillis()+"image.jpg");

                out = new FileOutputStream(filename);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                        out);

                MediaStore.Images.Media.insertImage(getActivity()
                        .getContentResolver(), filename.getAbsolutePath(),
                        filename.getName(), filename.getName());

        }
 catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}


text:
Q: Only let plugin add actions to wp_head & wp_footer on single posts I'm using a a plugin (Comments Evolved) on a recently built site.
The issue I'm having is that this plugin  globally enqueueing and adding actions to the head and footer of all pages. I'd like to remove the actions except for single posts only.
I tried this in my functions.php file:
    // strip out the plugin junk slowing down pages it's not used on
    function strip_the_junk() {
        if (!is_single() {
            remove_action('wp_head', 'gplus_comments_enqueue_styles');
            remove_action('wp_footer', 'gplus_comments_enqueue_scripts');
        }
    )};
    add_action('wp_enqueue_scripts', 'strip_the_junk', 11);

That crashes my site. For Comments Evolved, this is what's being pumped in by hook.php:
    function gplus_comments_enqueue_styles()
    {
      wp_enqueue_style('gplus_comments_tabs_css');
    }
    add_action('wp_head', 'gplus_comments_enqueue_styles', 4269);

    function gplus_comments_enqueue_scripts()
    {
      print "\n<script>jQuery('#comment-tabs').tabs();</script>\n";
    /*
    <script type="text/javascript">
      (function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/client:plusone.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
      })();
    </script>
    */
    }
    add_action('wp_footer', 'gplus_comments_enqueue_scripts', 4269);

Any thoughts on where I'm going wrong with this?
Thanks!

A: You need to remove the actions before they are called. In order to ensure this is the case call your function at init, like so:
add_action('init', 'strip_the_junk');
In general, its not a great idea to use the wp_enqueue_scripts hook for anything besides wp_enqueue_script or wp_enqueue_style functions.


text:
Q: How to add a reply to a comment in a post section in Django I am trying to add a reply to comments on a post section for a post
I have commented out the reply that I have added in the views.py as it is not working at all
The templates are working perfectly but with every new reply comment is added not a reply so the issue is with the views I guess
I have added a reply section to the comment models as following:
models.py
class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE)
    reply = models.ForeignKey(
        'Comment', on_delete=models.CASCADE, null=True, related_name="replies")
    content = models.TextField(max_length=160)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '{} by {}'.format(self.post.title, str(self.user.username))

here is the views:
class PostDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        comments = Comment.objects.filter(
            post=post, reply=None).order_by('-id')
        total_likes = post.total_likes()
        liked = False
        if post.likes.filter(id=self.request.user.id).exists():
            liked = True

        if self.request.method == 'POST':
            comment_form = CommentForm(self.request.POST or None)
            if comment_form.is_valid():
                content = self.request.POST.get('content')
                #reply_id = self.request.POST.get('comment_id')
                comment_qs = None

                #if reply_id:
                    #comment_qs = Comment.objects.get(id=reply_id)
                comment = Comment.objects.create(
                    post=post, user=request.user, content=content, reply=comment_qs)
                comment.save()
                return HttpResponseRedirect("post_detail.html")
        else:
            comment_form = CommentForm()

        context["total_likes"] = total_likes
        context["liked"] = liked
        context["comments"] = comments
        context["comment_form"] = comment_form
        return context

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    form_class = CommentForm

    def form_valid(self, form):
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        form.instance.user = self.request.user
        form.instance.post = post
        return super().form_valid(form)

    def form_invalid(self, form):
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return reverse('score:post-detail', kwargs=dict(slug=self.kwargs['slug']))


text:
Q: When does one equal two When does 1=2
I once saw a proof that 2=1. Of course there was an error in the proof. (some where in the proof they were dividing by 0 - a/a) Does anybody remember seeing this proof. It was a very simple thing but it has been years and I don't remember how it went.

A: Here is a valid proof that $1=2$ in a particular ring.
First, a ring is a set $R$ together with two binary operations $+$ and $\cdot$ satisfying some very straightforward axioms that follow from our intuition of working with real numbers.  One of these axioms is that the ring has a special element, denoted by the symbol $0$, such that $0+r=r=r+0$ for all $r\in R$.
Not a part of the axioms is another condition that some rings satisfy: the ring has an identity if there is a special element in $R$, denoted by the symbol $1$, such that $r\cdot 1=r=1\cdot r$ for all $r\in R$.
In any ring with an identity, denote by the symbol $2$ the value of $1+1$.
It turns out that the one element set $R=\{\star\}$ is a ring with identity, using the only possible definitions of the binary operations: $\star+\star=\star$ and $\star\cdot \star=\star$.  Notice that in this case, we have $\star=0$, $\star=1$, and $\star=2$.  By the transitivity property of equality, it follows that $0=1=2$.
So to address the question in the title, with these definitions of the symbols $1$ and $2$, it can be shown that $1=2$ if and only if $R=\{\star\}$.
Your question most likely addresses the symbols $1$ and $2$ in the ring of integers, denoted $\mathbb{Z}$.  Since $\mathbb{Z}$ is not 'the same' as the ring $\{\star\}$, it follows that the symbols $1$ and $2$ are different elements in $\mathbb{Z}$.  Hence, as you've noted, any proof that claims they are the same element must be faulty.  There are plenty of such proofs, many of which you can find in the links provided in the comments.

A: Taking the title question literally: Structures in which $1=2$ include the circle group $\mathbb R/\mathbb Z$, the group of rationals modulo integers $\mathbb Q/\mathbb Z$, and the trivial ring $\mathbb Z/\mathbb Z$. However, these structures are not necessarily related to the fake proofs you have in mind.


text:
Q: Python: TypeError: 'float' object has no attribute '__getitem__' I am trying to implement particle filter algorithm in python. I am getting this error:
x_P_update[i] = 0.5*x_P[i] + 25*x_P[i]/(1 + x_P[i]**2) + 8*math.cos(1.2*(t-1)) +     math.sqrt(x_N)*np.random.randn()
TypeError: 'float' object has no attribute '__getitem__'

My code:
import math
import numpy as np
import matplotlib.pyplot as plt

x = 0.1 #initial value
x_N = 1 #process noise covariance in state update
x_R = 1 #noise covariance in measurement
T = 75 #number of iterations
N = 10 #number of particles

V = 2
x_P = [None]*(N)

for i in xrange(0, N):
    x_P[i] = x + math.sqrt(V)*np.random.randn()

z_out = np.array([x**2 / 20 + math.sqrt(x_R) * np.random.randn()])  #the actual output vector for measurement values.
x_out = np.array([x])  #the actual output vector for measurement values.
x_est = np.array([x]); # time by time output of the particle filters estimate
x_est_out = np.array([x_est]) # the vector of particle filter estimates.

x_P_update = [None]*N
z_update = [None]*N
P_w = [None]*N

for t in xrange(1, T+1):
    x = 0.5*x + 25*x/(1 + x**2) + 8*math.cos(1.2*(t-1)) +  math.sqrt(x_N)*np.random.randn()
    z = x**2/20 + math.sqrt(x_R)*np.random.randn()
    for i in xrange(0, N):
        #each particle is updated with process eq
        x_P_update[i] = 0.5*x_P[i] + 25*x_P[i]/(1 + x_P[i]**2) + 8*math.cos(1.2*(t-1)) + math.sqrt(x_N)*np.random.randn()
        #observations are updated for each particle
        z_update[i] = x_P_update[i]**2/20
        #generate weights
        P_w[i] = (1/math.sqrt(2*math.pi*x_R)) * math.exp(-(z - z_update[i])**2/(2*x_R))

    P_w[:] = [ k / sum(P_w) for k in P_w]
#    print(np.where(np.cumsum(P_w, axis=0) >= np.random.rand()))

  #  print(index_tuple[0][1])
#    P_w_array = np.array(list(P_w))
#    indices = [i for i in range(len(P_w)) if np.cumsum(P_w_array) >= np.random.rand()]
    for i in xrange(0, N):
        index_tuple = np.where(np.random.rand() <= np.cumsum(P_w, axis=0))
        m = index_tuple[0][1]
        x_P = x_P_update[m]

    x_est = np.array([np.mean(x_P)])
    x_out = np.array([x_out, x])
    z_out = np.array([z_out, z])
    x_est_out = np.array([x_est_out, x_est])

I am using matlab code from here to learn how to implement this algorithm in python using scipy. http://studentdavestutorials.weebly.com/particle-filter-with-matlab-code.html
I just started learning python and can't get out of this problem, kindly help.

A: I'm not going to go through the video tutorial and fix your algorithm, but I can show you why you're getting this error.
In this line:
x_P = x_P_update[m]

You are assigning an array with a float value, which you then attempt to access as an array in the outer loop. Updating it instead will get rid of your error:
x_P[m] = x_P_update[m]


text:
Q: Ensure that an object is not null How can I make sure that a certain instance of a class will never be null? Someone told me to use Debug.Assert() but by doing so, I would only ensure that the code works in debug mode, whereas I want to ensure the is-never-null condition in release as well.
For example, in the past I wrote code like:
public string MyString
{
get
{
    if(instance1.property1.Equals("bla"))
    {
        return bla;
    }
}
}

But this throws an exception if instance1 is null. I would like to avoid making such mistakes and generating such exceptions in the future.
Thanks,

please see a specific example below that illustrates the problem:
I have a method that authenticates users based on responses from a server. The method is this:
        /// <summary>
    /// attempts authentication for current user
    /// </summary>
    /// <returns></returns>
    public AuthResult CheckUser()
    {
        WebRequest request = WebRequest.Create(GetServerURI);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        string postdata = "data=" + HttpUtility.UrlEncode(SerializeAuth());
        byte[] arr = Utils.AppDefaultEncoding.GetBytes(postdata);
        request.ContentLength = arr.Length;
        request.Timeout = Convert.ToInt32(TimeUtils.GetMiliseconds(10, TimeUtils.TimeSelect.Seconds));

        Stream strToWrite = request.GetRequestStream();
        strToWrite.Write(arr, 0, arr.Length);

        WebResponse response = request.GetResponse();
        using (Stream dataFromResponse = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(dataFromResponse))
            {
                string readObj = reader.ReadToEnd();
                return DeserializeAuth(readObj);
            }
        }
    }

to call this method, i use
_authenticationResult = authObj.CheckUser();

I also have this property, among others
        public ResultType AuthResult
    {
        get
        {
            if (_authenticationResult.auth == "1")
                return ResultType.Success;
            if (_authenticationResult.auth == "0")
                return ResultType.FailAccountExpired;
            if (_authenticationResult.auth == "-1")
                return ResultType.FailWrongUsernameOrPassword;
            if (_authenticationResult.auth == "-2")
                return ResultType.Banned;

            return ResultType.NoAuthDone;
        }
    }

public enum ResultType { Success, FailWrongUsernameOrPassword, FailAccountExpired, NoAuthDone, Banned }

what happened was that _authenticationResult was null once, and the property AuthResult threw a nullref at attempting "null.auth". How can I ensure (perhaps inside the CheckUser() method) that it never returns null.
When i debugged the app it never happened. But in production, when the server timed out sometimes the method returned null.
Thanks,

A: I think you need to understand how instance1, and subsequently property1 are going to be instantiated, and only instantiate them in such a way that they cannot be null.  This is generally done by checking arguments at construction, e.g.:
public instance1(string property1)
{
    if (property1 == null) throw new ArgumentNullException("property1");

    this.property1 = property1;
}

If you create your types in such a way that they cannot exist in an invalid state, you ensure that your dependent code won't fall over on null values.
Otherwise, we'd need to see a fuller example of what you are doing to give you more concrete advice.
The other thing to consider, is what state your class can exist in which is a required state of operation, vs. an optional state of operation. That being, what members are required for your class to operate, and you should endeavour to design your classes such that they always have the required state, e.g.:
public class Person
{
  public Person(string forename, string surname)
  {
    if (forename == null) throw new ArgumentNullException("forename");
    if (surname == null) throw new ArgumentNullException("surname");

    Forename = forename;
    Surname = surname;
  }

  public string Forename { get; private set; }
  public string Surname { get; private set; }
}

In my example type, I'm requiring that my Forename and Surname value have a non-null value. This is enforced through my constructor... my Person type can never be instantiated with null values (although, perhaps empty values are just as bad, so checking IsNullOrWhiteSpace and throwing an appropriate ArgumentException is the route, but lets keep it simple).
If I were to introduce an optional field, I would allow it to mutate the state of my Person instance, e.g., give it a setter:
public class Person
{
  public Person(string forename, string surname)
  {
    if (forename == null) throw new ArgumentNullException("forename");
    if (surname == null) throw new ArgumentNullException("surname");

    Forename = forename;
    Surname = surname;
  }

  public string Forename { get; private set; }
  public string Surname { get; private set; }

  public string Initial { get; set; }
}

My Person type still enforces the required fields for operation, but introduces an optional field. I then need to take this into consideration when performing an operation which uses these members:
public override ToString()
{
  return Forename + (Initial == null ? String.Empty : " " + Initial) + " " + Surname;
}

(Although that is not the greatest example of a ToString).

A: You can use:
if ( instance1 != null && instance1.property1.Equals("bla")){
   // Your code
 }

A: Personally, I would use the ?? operator (assuming property1 is a string)
public string MyString
{
    get { instance1.property1 ?? "Default value"; }
}

A: People generally handle this situation in one of three ways. The worst way (in my opinion) is to be paranoid about every reference you look at, always testing it against null, and then doing ""something"" if you do encounter a null. The problem with such an approach is that you're often  deep in some call tree, and so the "something" you do (like return a """reasonable""" default value) not only is likely to be a layering violation, but also is likely to paper over a problem rather than cause it to be confronted. In these cases it's actually probably better to let a NulLReferenceException be thrown rather than make some half-assed attempt to continue.
The saner thing to do is establish a coding convention where your references are never null, except in a few cases where it is obvious from context that they can be null. Additionally, and wherever possible, one can make one's classes immutable or mostly-immutable so that all the invariants can be done in the constructor and the rest of the code can get on with its life.  For example, I might write:
public class Person {
  private readonly string firstName;
  private readonly string lastName;
  private readonly Nubbin optionalNubbin;
}

...where it is clear from the name that optionalNubbin might be null.
The final and most radical approach is to write code that will not admit a null. You could invent the dual of Nullable<T>, namely:
public struct NonNullable<T> {
  ...
}

The implementation could work in a few different ways (either by using an explicit Value property, or perhaps using operator overloading) but in any case the job of NonNullable is to never let someone set it to null.

A: Since instance1.property1 should never be null, see if there's a way to initialize it properly, then thrown an ArgumentNullException if someone tries to set it to null.
Example:
public string Property1
{
    set
    {
      if(value == null)
      {
        throw new ArgumentNullException();
      }
      instance1.property1 = value;
    }
}

A: you can do something like below.
public string MyString
{
    get
    {
        if(instance!=null && instance1.property1.Equals("bla"))
        {
            return "bla";
        }
        else
        {
            return String.Empty;
        }
    }
}

This will basically check first whether instance is null or not.


text:
Q: Exception while connecting server on IntelliJ while connecting with the server on intellij, after I am done with clean+ install, I get DAOException and NullPointerException.. How can I eliminate this error and successfully connect server
enter image description here
enter image description here


text:
Q: Django check if post value exists in db I'm trying to submit two forms with one submit button. First I want to check if form 1 already exists in the db, if id does then just post the second form using the "ticker" from first form as Foreginkey. But seem to get an error:
'UserTickerForm' object has no attribute 'get'

My code:
    if request.method == 'POST':

        request_form_user_ticker = UserTickerForm(request.POST)
        request_form_trade = TradesForm(request.POST)

        if request_form_user_ticker.is_valid() and request_form_trade.is_valid():
            if not User_Ticker.objects.filter(portfolio=select_portfolio, ticker=request_form_user_ticker.get('ticker')).exists():

                user_ticker_instace = request_form_user_ticker.save(commit=False)
                user_ticker_instace.portfolio = select_portfolio
                user_ticker_instace.save()

                trade_instance = request_form_trade.save(commit=False)
                trade_instance.ticker = request_form_user_ticker.get('ticker')
                trade_instance.save()

            else:
                trade_instance = request_form_trade.save(commit=False)
                trade_instance.ticker = request_form_user_ticker.get('ticker')
                trade_instance.save()

Does anyone know who this is happening and what I can do to fix this?

A: instead of request_form_user_ticker.get('ticker') you should call .get('ticker') on cleaned data so request_form_user_ticker.cleaned_data.get('ticker')


text:
Q: Keeping a (single threaded) server socket listening for clients on unexpected socket closure How should one deal with clients disconnecting unexpectedly. I want to keep the server running/listening unless explicitly stated to close by the client.
For example, my server is listening and then the client is closed which causes the server's method to end - how can I get it to return to the beginning of the method as it were?
    serverSocket = new ServerSocket(port);
    clientSocket = serverSocket.accept();
    out = new PrintWriter(clientSocket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    BasicProtocol bp = new BasicProtocol(password);
    out.println(bp.processInput(""));
    String inputLine;
    while((inputLine = in.readLine()) != null ){
       System.out.println("Client asks: " + inputLine);
       out.println(bp.processInput(inputLine));
    }

As above, if a connection reset error occurs how can it wait to be reconnected to?

A: For instance you can have a while loop at the method with a boolean variable that is changed when the client wants to close. As such:
boolean isRunning = true;
while (isRunning) {
    //Your current method - when client wants to disconnect just set isRunning = false;
}


text:
Q: EF Code First: Changing model without migrations Code-First-Migrations is a excellent technology but for some reasons I can't use
static MyDbContext()
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>());
}

So I have to turn off migrations and delete all relevant records from __MigrationHistory
Database.SetInitializer<MyDbContext>(null);

When I change model I write a sql-script to make relevant changes in database.
My program has special module to execute these scripts. Such way customers can actualize their DBs when I change model. It's just part of update for them.
Does this approach have any pitfalls?


text:
Q: ColdFusion S3 directoryList throws this error "An error occurred when performing a file operation listFiles" If I try to list the files in an S3 directory using the built-in S3 integration in ColdFusion 9, I get an exception when any of the files contains a % (percent) character. The full error message looks like this:

An error occurred when performing a file operation listFiles on file
  /activities/18057/files.
The cause of this exception was:
  org.apache.commons.vfs.FileSystemException: Unknown message with code
  "Invalid URI escape sequence "%ui"."..

I think this is a ColdFusion bug caused by overzealous character escaping, but can anyone with S3 integration try it themselves to confirm? I'm literally just doing this:
<cfset var files = directoryList("s3://my.bucket.path/somefolder/")/>

It works find for "normal" files, but fails as soon as one of the files has a % in its filename.

A: This would appear to be a "bug" in Adobe CF9 (ACF9). If it's not a bug, it's certainly odd behavior as I tried the code in Railo 3.3.3.0001 (current release) and it works perfectly.
I got the same error from ACF9 as you. In addition, ACF10 has the same error. I also tried in OpenBD but was not able to read the desired folder in my bucket (it read the main bucket, its files and listed the folder but was not able to get inside the folder). However, I've not used OpenBD a lot so this was probably more my error than anything else.


text:
Q: how to execute native mongo methods in meteor app environment? Meteor supports only few methods on mongo collections such as find, findOne, insert, update, upsert, remove, allow, deny
My question is, how do I perform all the others? I want to use aggregate on server side, like this:
db.eshops.aggregate([
  {
    $unwind: '$unpairedCategories'
  }, {
    $group: {
      _id: '$_id',
      'sum': {
        $sum: 1
      }
    }
  }, {
    $group: {
      _id: null,
      total_sum: {
        '$sum': '$sum'
      }
    }
  }
]);

should I include mongodb driver for nodejs separately from meteor? Or what is the meteor way to run all the other mongo collection methods?

A: One of the seven principles of Meteor is database everywhere, i.e. you should be able to perform all the allowed operations both on client and server side (assuming several differences, such as allow deny rules for client). I guess this is why you can't have all mongo methods: they are not feasible on minimongo, the client side version of your mongo collection.
However, if you are ready to give up the reactivity, you can create a pipe to handle the aggregate commands, by adding this to your server startup code (code taken from here):
wrapAsync = (Meteor.wrapAsync)? Meteor.wrapAsync : Meteor._wrapAsync;
Mongo.Collection.prototype.aggregate = function(pipelines) {
  var coll;
  if (this.rawCollection) {
    // >= Meteor 1.0.4
    coll = this.rawCollection();
  } else {
    // < Meteor 1.0.4
    coll = this._getCollection();
  }
  return wrapAsync(coll.aggregate.bind(coll))(pipelines);

You have two possible alternatives/workaround if you want to keep the reactivity.

*

*create extra fields using collection hooks. You basically include the computed fields in the collection. This is a scalable solution, and it does not requires to add an extra load to the server

*You use the cursor.Observe() feature and you make a mix of clever filtering and custom JS methods (e.g. sum) to achieve similar results to what you need from the aggregate method. Note that you keep the reactivity but each server (if you plan to scale on several) needs to Observe() the collections. Check this example: https://stackoverflow.com/a/30813050/3793161