Search Results

Search found 85 results on 4 pages for 'slicing'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Is this an F# quotations bug?

    - by ControlFlow
    [<ReflectedDefinition>] let rec x = (fun() -> x + "abc") () The sample code with the recursive value above produces the following F# compiler error: error FS0432: [<ReflectedDefinition>] terms cannot contain uses of the prefix splice operator '%' I can't see any slicing operator usage in the code above, looks like a bug... :) Looks like this is the problem with the quotation via ReflectedDefinitionAttribute only, normal quotation works well: let quotation = <@ let rec x = (fun() -> x + "abc") () in x @> produces expected result with the hidden Lazy.create and Lazy.force usages: val quotation : Quotations.Expr<string> = LetRecursive ([(x, Lambda (unitVar, Application (Lambda (unitVar0, Call (None, String op_Addition[String,String,String](String, String), [Call (None, String Force[String](Lazy`1[System.String]), [x]), Value ("abc")])), Value (<null>)))), (x, Call (None, Lazy`1[String] Create[String](FSharpFunc`2[Unit,String]), [x])), (x, Call (None, String Force[String](Lazy`1[String]), [x]))], x) So the question is: is this an F# compiler bug or not?

    Read the article

  • how to get namespace prefixes from XML document, using MSXML ?

    - by KaluSingh Gabbar
    For example, In this document < ?xml version="1.0" ? > < SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="http://opcfoundation.org/webservices/XMLDA/1.0/" xmlns:ns2="Service"> < SOAP-ENV:Body id="_0" > if I need to select the element "Body", I need to know the prefix "SOAP-ENV". How can I get that? getting a root element and slicing the colon (:) off seems a dirty idea to me, I am sure there should be a neat way to do that. Google does not help (may be I am not searching for the right thing).

    Read the article

  • immutable strings vs std::string

    - by Caspin
    I've recent been reading about immutable strings, here and here as well some stuff about why D chose immutable strings. There seem to be many advantages. trivially thread safe more secure more memory efficient in most use cases. cheap substrings (tokenizing and slicing) Not to mention most new languages have immutable strings, D2.0, Java, C#, Python, Ruby, etc. Would C++ benefit from immutable strings? Is it possible to implement an immutable string class in c++ (or c++0x) that would have all of these advantages?

    Read the article

  • What is the JVM Scheduling algorithm ?

    - by IHawk
    Hello ! I am really curious about how does the JVM work with threads ! In my searches in internet, I found some material about RTSJ, but I don't know if it's the right directions for my answers. I also found this topic in sun's forums, http://forums.sun.com/thread.jspa?forumID=513&threadID=472453, but that's not satisfatory. Can someone give me some directions, material, articles or suggestion about the JVM scheduling algorithm ? I am also looking for information about the default configurations of Java threads in the scheduler, like 'how long does it take for every thread' in case of time-slicing. And this stuff. I would appreciate any help ! Thank you !

    Read the article

  • idiomatic way to take groups of n items from a list in Python?

    - by Wang
    Given a list A = [1 2 3 4 5 6] Is there any idiomatic (Pythonic) way to iterate over it as though it were B = [(1, 2) (3, 4) (5, 6)] other than indexing? That feels like a holdover from C: for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]: I can't help but feel there should be some clever hack using itertools or slicing or something. (Of course, two at a time is just an example; I'd like a solution that works for any n.) Edit: related http://stackoverflow.com/questions/1162592/iterate-over-a-string-2-or-n-characters-at-a-time-in-python but even the cleanest solution (accepted, using zip) doesn't generalize well to higher n without a list comprehension and *-notation.

    Read the article

  • How to translate such AS3 class into C#?

    - by Ole Jak
    So I try to create opensource C# project for slicing FLVs I began with translating of existing project called flvslicer Can any one please help me with translating one of their classes package org.bytearray.video.events { import flash.events.Event; import flash.utils.ByteArray; public final class MergedEvent extends Event { public var time:Number; public var stream:ByteArray; public static const COMPLETE:String = "mergeComplete"; public function MergedEvent(type:String, stream:ByteArray, duration:Number) { super(type, false, false); // base this.stream = stream; this.time = duration; } } }

    Read the article

  • Best way to search for a saturation value in a sorted list

    - by AB Kolan
    A question from Math Battle. This particular question was also asked to me in one of my job interviews. " A monkey has two coconuts. It is fooling around by throwing coconut down from the balconies of M-storey building. The monkey wants to know the lowest floor when coconut is broken. What is the minimal number of attempts needed to establish that fact? " Conditions: if a coconut is broken, you cannot reuse the same. You are left with only with the other coconut Possible approaches/strategies I can think of are Binary break ups & once you find the floor on which the coconut breaks use upcounting from the last found Binary break up lower index. Window/Slices of smaller sets of floors & use binary break up within the Window/Slice (but on the down side this would require a Slicing algorithm of it's own.) Wondering if there are any other way to do this.

    Read the article

  • Splitting string to integer from single-line user input?

    - by pootzko
    I just started learning some ruby, and I want to do something like this: print "Insert two numbers: " a, b = gets.split(" ") but I want to make a and b to be integers at the same time (in the same line).. If I add .to_i to the second line (before or after split(" ")), it doesn't work... so, how should I approach this? mapping, splitting, slicing? ok, I know I could use scanf, but other than scanf, how would I do this? sorry for such a noobish question, but I just couldn't find a good enough answer only googling...

    Read the article

  • Threading and cores

    - by Matt
    If I have X cores on my machine and I start X threads. Let's assume for the sake of argument that each thread is completely separated in terms of the memory, hdd, etc it uses. Is the OS going to know to send each thread to a core or do more time slicing on one core for multiple threads. What the question boils down to, is if I have X cores and my program must do independent calculations, should I start X threads, will they each get piped to a core, or is the presumption that because I have X cores I can start X threads completely wrong? I'm thinking it is. This is with C# --

    Read the article

  • Ruby getting the diagonal elements in a 2d Array

    - by Calm Storm
    Hi, I was trying some problems with my 2D ruby array and my LOC reduces a lot when I do array slicing. So for example, require "test/unit" class LibraryTest < Test::Unit::TestCase def test_box array = [[1,2,3,4],[3,4,5,6], [5,6,7,8], [2,3,4,5]] puts array[1][2..3] # 5, 6 puts array[1..2][1] # 5, 6, 7, 8 end end I want to know if there is a way to get a diagonal slice? Lets say I want to start at [0,0] and want a diagonal slice of 3. Then I would get elements from [0,0], [1,1], [2,2] and I will get an array like [1,4,7] for example above. Is there any magic one-liner ruby code that can achieve this? 3.times do {some magic stuff?}

    Read the article

  • What's the best way to return something like a collection of `std::auto_ptr`s in C++03?

    - by Billy ONeal
    std::auto_ptr is not allowed to be stored in an STL container, such as std::vector. However, occasionally there are cases where I need to return a collection of polymorphic objects, and therefore I can't return a vector of objects (due to the slicing problem). I can use std::tr1::shared_ptr and stick those in the vector, but then I have to pay a high price of maintaining separate reference counts, and object that owns the actual memory (the container) no longer logically "owns" the objects because they can be copied out of it without regard to ownership. C++0x offers a perfect solution to this problem in the form of std::vector<std::unique_ptr<t>>, but I don't have access to C++0x. Some other notes: I don't have access to C++0x, but I do have TR1 available. I would like to avoid use of Boost (though it is available if there is no other option) I am aware of boost::ptr_container containers (i.e. boost::ptr_vector), but I would like to avoid this because it breaks the debugger (innards are stored in void *s which means it's difficult to view the object actually stored inside the container in the debugger)

    Read the article

  • Building ffmpeg with an executable output

    - by Kevin Galligan
    I generally don't like to ask such "you figure it out for me" questions, but I suspect this one will be really simple for a C++ guru. I want to build ffmpeg for Android, and I'd like it to output an executable rather than a set of libraries. We've been using the guardian project's build: https://github.com/guardianproject/android-ffmpeg It does produce what we want, but I've found tweaking it for different architectures to be, at best, unpleasant. I've gotten this version to build: https://github.com/appunite/AndroidFFmpeg It does a nice job of slicing and dicing different architectures, but produces a jni version. There is a long story as to why I want the exe, but I'll skip it for now. Is there a flag that needs to be flipped? Some path or other setting? I am at this point fully baffled. Thanks in advance.

    Read the article

  • Multiplying numbers on horizontal, vertial, and diagonal lines

    - by untwisted
    I'm currently working on a project Euler problem (www.projecteuler.net) for fun but have hit a stumbling block. One of the problem provides a 20x20 grid of numbers and asks for the greatest product of 4 numbers on a straight line. This line can be either horizontal, vertical, or diagonal. Using a procedural language I'd have no problem solving this, but part of my motivation for doing these problems in the first place is to gain more experience and learn more Haskell. As of right now I'm reading in the grid and converting it to a list of list of ints, eg -- [[Int]]. This makes the horizontal multiplication trivial, and by transposing this grid the vertical also becomes trivial. The diagonal is what is giving me trouble. I've thought of a few ways where I could use explicit array slicing or indexing, to get a solution, but it seems overly complicated and hackey. I believe there is probably an elegant, functional solution here, and I'd love to hear what others can come up with.

    Read the article

  • ArchBeat Facebook Friday: Top 10 Posts - August 15-21, 2014

    - by Bob Rhubart-Oracle
    As hot as molten rock? Not quite. But among the 5,313 fans of the OTN ArchBeat Facebook Page these Top 10 items were the hottest over the past seven days, August 15-21, 2014. Oracle BPM 12c Gateways (Part 1 of 5): Exclusive Gateway | Antonis Antoniou Oracle ACE Associate Antonis Antoniou begins a five-part series with a look at In the gateway control flow components in Oracle BPM and how they can be used to process flow. Slicing the EDG: Different SOA Domain Configurations | Antony Reynolda Antony Reynolds introduces three different configurations for a SOA environment and identifies some of the advantages for each. How to introduce DevOps into a moribund corporate culture | ZDNet Confused about DevOPs? This post from ZDNet's Joe McKendrick -- which includes insight from Phil Whelan -- just might clear some of the fog. Oracle Identity Manager Role Management With API | Mustafa Kaya Mustafa Kaya shares some examples of role management using the Oracle Identity Management API. Podcast: Redefining Information Management Architecture Oracle Enterprise Architect Andrew Bond joins Oracle ACE Directors Mark Rittman and Stewart Bryson for a conversation about their collaboration on a new Oracle Information Management Reference Architecture. WebCenter Sites Demo Integration with Endeca Guided Search | Micheal Sullivan A-Team solution architect Michael Sullivan shares the details on a demo that illustrates the viability of integrating WebCenter Sites with Oracle Endeca. Wearables in the world of enterprise applications? Yep. Oh yeah, wearables are a THING. Here's a look at how the Oracle Applications User Experience team has been researching wearables for inclusion in your future enterprise applications. Getting Started With The Coherence Memcached Adaptor | David Felcey Let David Felcey show you how to configure the Coherence Memcached Adaptor, and take advantage of his simple PHP example that demonstrates how Memecached clients can connect to a Coherence cluster. OTN Architect Community Newsletter - August Edition A month's worth of hot stuff, all in one spot. Featuring articles on Java, Coherence, WebLogic, Mobile and much more. 8,853 Conversations About Oracle WebLogic Do you have a question about WebLogic? Do you have an answer to a question about WebLogic? You need to be here.

    Read the article

  • Big Data – Basics of Big Data Analytics – Day 18 of 21

    - by Pinal Dave
    In yesterday’s blog post we learned the importance of the various components in Big Data Story. In this article we will understand what are the various analytics tasks we try to achieve with the Big Data and the list of the important tools in Big Data Story. When you have plenty of the data around you what is the first thing which comes to your mind? “What do all these data means?” Exactly – the same thought comes to my mind as well. I always wanted to know what all the data means and what meaningful information I can receive out of it. Most of the Big Data projects are built to retrieve various intelligence all this data contains within it. Let us take example of Facebook. When I look at my friends list of Facebook, I always want to ask many questions such as - On which date my maximum friends have a birthday? What is the most favorite film of my most of the friends so I can talk about it and engage them? What is the most liked placed to travel my friends? Which is the most disliked cousin for my friends in India and USA so when they travel, I do not take them there. There are many more questions I can think of. This illustrates that how important it is to have analysis of Big Data. Here are few of the kind of analysis listed which you can use with Big Data. Slicing and Dicing: This means breaking down your data into smaller set and understanding them one set at a time. This also helps to present various information in a variety of different user digestible ways. For example if you have data related to movies, you can use different slide and dice data in various formats like actors, movie length etc. Real Time Monitoring: This is very crucial in social media when there are any events happening and you wanted to measure the impact at the time when the event is happening. For example, if you are using twitter when there is a football match, you can watch what fans are talking about football match on twitter when the event is happening. Anomaly Predication and Modeling: If the business is running normal it is alright but if there are signs of trouble, everyone wants to know them early on the hand. Big Data analysis of various patterns can be very much helpful to predict future. Though it may not be always accurate but certain hints and signals can be very helpful. For example, lots of data can help conclude that if there is lots of rain it can increase the sell of umbrella. Text and Unstructured Data Analysis: unstructured data are now getting norm in the new world and they are a big part of the Big Data revolution. It is very important that we Extract, Transform and Load the unstructured data and make meaningful data out of it. For example, analysis of lots of images, one can predict that people like to use certain colors in certain months in their cloths. Big Data Analytics Solutions There are many different Big Data Analystics Solutions out in the market. It is impossible to list all of them so I will list a few of them over here. Tableau – This has to be one of the most popular visualization tools out in the big data market. SAS – A high performance analytics and infrastructure company IBM and Oracle – They have a range of tools for Big Data Analysis Tomorrow In tomorrow’s blog post we will discuss about very important components of the Big Data Ecosystem – Data Scientist. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: Big Data, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

    Read the article

  • Best Practices - Core allocation

    - by jsavit
    This post is one of a series of "best practices" notes for Oracle VM Server for SPARC (also called Logical Domains) Introduction SPARC T-series servers currently have up to 4 CPU sockets, each of which has up to 8 or (on SPARC T3) 16 CPU cores, while each CPU core has 8 threads, for a maximum of 512 dispatchable CPUs. The defining feature of Oracle VM Server for SPARC is that each domain is assigned CPU threads or cores for its exclusive use. This avoids the overhead of software-based time-slicing and emulation (or binary rewriting) of system state-changing privileged instructions used in traditional hypervisors. To create a domain, administrators specify either the number of CPU threads or cores that the domain will own, as well as its memory and I/O resources. When CPU resources are assigned at the individual thread level, the logical domains constraint manager attempts to assign threads from the same cores to a domain, and avoid "split core" situations where the same CPU core is used by multiple domains. Sometimes this is unavoidable, especially when domains are allocated and deallocated CPUs in small increments. Why split cores can matter Split core allocations can silenty reduce performance because multiple domains with different address spaces and memory contents are sharing the core's Level 1 cache (L1$). This is called false cache sharing since even identical memory addresses from different domains must point to different locations in RAM. The effect of this is increased contention for the cache, and higher memory latency for each domain using that core. The degree of performance impact can be widely variable. For applications with very small memory working sets, and with I/O bound or low-CPU utilization workloads, it may not matter at all: all machines wait for work at the same speed. If the domains have substantial workloads, or are critical to performance then this can have an important impact: This blog entry was inspired by a customer issue in which one CPU core was split among 3 domains, one of which was the control and service domain. The reported problem was increased I/O latency in guest domains, but the root cause might be higher latency servicing the I/O requests due to the control domain being slowed down. What to do about it Split core situations are easily avoided. In most cases the logical domain constraint manager will avoid it without any administrative action, but it can be entirely prevented by doing one of the several actions: Assign virtual CPUs in multiples of 8 - the number of threads per core. For example: ldm set-vcpu 8 mydomain or ldm add-vcpu 24 mydomain. Each domain will then be allocated on a core boundary. Use the whole core constraint when assigning CPU resources. This allocates CPUs in increments of entire cores instead of virtual CPU threads. The equivalent of the above commands would be ldm set-core 1 mydomain or ldm add-core 3 mydomain. Older syntax does the same thing by adding the -c flag to the add-vcpu, rm-vcpu and set-vcpu commands, but the new syntax is recommended. When whole core allocation is used an attempt to add cores to a domain fails if there aren't enough completely empty cores to satisfy the request. See https://blogs.oracle.com/sharakan/entry/oracle_vm_server_for_sparc4 for an excellent article on this topic by Eric Sharakan. Don't obsess: - if the workloads have minimal CPU requirements and don't need anywhere near a full CPU core, then don't worry about it. If you have low utilization workloads being consolidated from older machines onto a current T-series, then there's no need to worry about this or to assign an entire core to domains that will never use that much capacity. In any case, make sure the most important domains have their own CPU cores, in particular the control domain and any I/O or service domain, and of course any important guests. Summary Split core CPU allocation to domains can potentially have an impact on performance, but the logical domains manager tends to prevent this situation, and it can be completely and simply avoided by allocating virtual CPUs on core boundaries.

    Read the article

  • Blink-Data vs Instinct?

    - by Samantha.Y. Ma
    In his landmark bestseller Blink, well-known author and journalist Malcolm Gladwell explores how human beings everyday make seemingly instantaneous choices --in the blink of an eye--and how we “think without thinking.”  These situations actually aren’t as simple as they seem, he postulates; and throughout the book, Gladwell seeks answers to questions such as: 1.    What makes some people good at thinking on their feet and making quick spontaneous decisions?2.    Why do some people follow their instincts and win, while others consistently seem to stumble into error?3.    Why are some of the best decisions often those that are difficult to explain to others?In Blink, Gladwell introduces us to the psychologist who has learned to predict whether a marriage will last, based on a few minutes of observing a couple; the tennis coach who knows when a player will double-fault before the racket even makes contact with the ball; the antiquities experts who recognize a fake at a glance. Ultimately, Blink reveals that great decision makers aren't those who spend the most time deliberating or analyzing information, but those who focus on key factors among an overwhelming number of variables-- i.e., those who have perfected the art of "thin-slicing.” In Data vs. Instinct: Perfecting Global Sales Performance, a new report sponsored by Oracle, the Economist Intelligence Unit (EIU) explores the roles data and instinct play in decision-making by sales managers and discusses how sales executives can increase sales performance through more effective  territory planning and incentive/compensation strategies.If you are a sales executive, ask yourself this:  “Do you rely on knowledge (data) when you plan out your sales strategy?  If you rely on data, how do you ensure that your data sources are reliable, up-to-date, and complete?  With the emergence of social media and the proliferation of both structured and unstructured data, how do you know that you are applying your information/data correctly and in-context?  Three key findings in the report are:•    Six out of ten executives say they rely more on data than instinct to drive decisions. •    Nearly one half (48 percent) of incentive compensation plans do not achieve the desired results. •    Senior sales executives rely more on current and historical data than on forecast data. Strikingly similar to what Gladwell concludes in Blink, the report’s authors succinctly sum up their findings: "The best outcome is a combination of timely information, insightful predictions, and support data."Applying this insight is crucial to creating a sound sales plan that drives alignment and results.  In the area of sales performance management, “territory programs and incentive compensation continue to present particularly complex challenges in an increasingly globalized market," say the report’s authors. "It behooves companies to get a better handle on translating that data into actionable and effective plans." To help solve this challenge, CRM Oracle Fusion integrates forecasting, quotas, compensation, and territories into a single system.   For example, Oracle Fusion CRM provides a natural integration between territories, which define the sales targets (e.g., collection of accounts) for the sales force, and quotas, which quantify the sales targets. In fact, territory hierarchy is a core analytic dimension to slice and dice sales results, using sales analytics and alerts to help you identify where problems are occurring. This makes territoriesStart tapping into both data and instinct effectively today with Oracle Fusion CRM.   Here is a short video to provide you with a snapshot of how it can help you optimize your sales performance.  

    Read the article

  • Converting string to datetime object in python

    - by Gussi
    Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object? After doing some reading I feel like this should work, but it doesn't... >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50 +0000' >>> fmt = '%a, %d %b %Y %H:%M:%S %z' >>> datetime.strptime(str, fmt) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/_strptime.py", line 317, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z' It should be noted that this works without a problem >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50' >>> fmt = '%a, %d %b %Y %H:%M:%S' >>> datetime.strptime(str, fmt) datetime.datetime(2010, 4, 9, 14, 10, 50) But I'm stuck with "Fri, 09 Apr 2010 14:10:50 +0000", I would prefer to convert exactly that without changing (or slicing) that string in any way.

    Read the article

  • How do I define a Calculated Measure in MDX based on a Dimension Attribute?

    - by ShaneD
    I would like to create a calculated measure that sums up only a specific subset of records in my fact table based on a dimension attribute. Given: Dimension Date LedgerLineItem {Charge, Payment, Write-Off, Copay, Credit} Measures LedgerAmount Relationships * LedgerLineItem is a degenerate dimension of FactLedger If I break down LedgerAmount by LedgerLineItem.Type I can easily see how much is charged, paid, credit, etc, but when I do not break it down by LedgerLineItem.Type I cannot easily add the credit, paid, credit, etc into a pivot table. I would like to create separate calculated measures that sum only specific type (or multiple types) of ledger facts. An example of the desired output would be: | Year | Charged | Total Paid | Amount - Ledger | | 2008 | $1000 | $600 | -$400 | | 2009 | $2000 | $1500 | -$500 | | Total | $3000 | $2100 | -$900 | I have tried to create the calculated measure a couple of ways and each one works in some circumstances but not in others. Now before anyone says do this in ETL, I have already done it in ETL and it works just fine. What I am trying to do as part of learning to understand MDX better is to figure out how to duplicate what I have done in the ETL in MDX as so far I am unable to do that. Here are two attempts I have made and the problems with them. This works only when ledger type is in the pivot table. It returns the correct amount of the ledger entries (although in this case it is identical to [amount - ledger] but when I try to remove type and just get the sum of all ledger entries it returns unknown. CASE WHEN ([Ledger].[Type].currentMember = [Ledger].[Type].&[Credit]) OR ([Ledger].[Type].currentMember = [Ledger].[Type].&[Paid]) OR ([Ledger].[Type].currentMember = [Ledger].[Type].&[Held Money: Copay]) THEN [Measures].[Amount - ledger] ELSE 0 END This works only when ledger type is not in the pivot table. It always returns the total payment amount, which is incorrect when I am slicing by type as I would only expect to see the credit portion under credit, the paid portion, under paid, $0 under charge, etc. sum({([Ledger].[Type].&[Credit]), ([Ledger].[Type].&[Paid]), ([Ledger].[Type].&[Held Money: Copay])}, [Measures].[Amount - ledger]) Is there any way to make this return the correct numbers regardless of whether Ledger.Type is included in my pivot table or not?

    Read the article

  • Few Basic Questions in Overriding

    - by Dahlia
    I have few problems with my basic and would be thankful if someone can clear this. What does it mean when I say base *b = new derived; Why would one go for this? We very well separately can create objects for class base and class derived and then call the functions accordingly. I know that this base *b = new derived; is called as Object Slicing but why and when would one go for this? I know why it is not advisable to convert the base class object to derived class object (because base class is not aware of the derived class members and methods). I even read in other StackOverflow threads that if this is gonna be the case then we have to change/re-visit our design. I understand all that, however, I am just curious, Is there any way to do this? class base { public: void f(){cout << "In Base";} }; class derived:public base { public: void f(){cout << "In Derived";} }; int _tmain(int argc, _TCHAR* argv[]) { base b1, b2; derived d1, d2; b2 = d1; d2 = reinterpret_cast<derived*>(b1); //gives error C2440 b1.f(); // Prints In Base d1.f(); // Prints In Derived b2.f(); // Prints In Base d1.base::f(); //Prints In Base d2.f(); getch(); return 0; } In case of my above example, is there any way I could call the base class f() using derived class object? I used d1.base()::f() I just want to know if there any way without using scope resolution operator? Thanks a lot for your time in helping me out!

    Read the article

  • Pairs from single list

    - by Apalala
    Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google: pairs = zip(t[::2], t[1::2]) I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests: import time from itertools import islice, izip def pairs_1(t): return zip(t[::2], t[1::2]) def pairs_2(t): return izip(t[::2], t[1::2]) def pairs_3(t): return izip(islice(t,None,None,2), islice(t,1,None,2)) A = range(10000) B = xrange(len(A)) def pairs_4(t): # ignore value of t! t = B return izip(islice(t,None,None,2), islice(t,1,None,2)) for f in pairs_1, pairs_2, pairs_3, pairs_4: # time the pairing s = time.time() for i in range(1000): p = f(A) t1 = time.time() - s # time using the pairs s = time.time() for i in range(1000): p = f(A) for a, b in p: pass t2 = time.time() - s print t1, t2, t2-t1 These were the results on my computer: 1.48668909073 2.63187503815 1.14518594742 0.105381965637 1.35109519958 1.24571323395 0.00257992744446 1.46182489395 1.45924496651 0.00251388549805 1.70076990128 1.69825601578 If I'm interpreting them correctly, that should mean that the implementation of lists, list indexing, and list slicing in Python is very efficient. It's a result both comforting and unexpected. Is there another, "better" way of traversing a list in pairs? Note that if the list has an odd number of elements then the last one will not be in any of the pairs. Which would be the right way to ensure that all elements are included? I added these two suggestions from the answers to the tests: def pairwise(t): it = iter(t) return izip(it, it) def chunkwise(t, size=2): it = iter(t) return izip(*[it]*size) These are the results: 0.00159502029419 1.25745987892 1.25586485863 0.00222492218018 1.23795199394 1.23572707176 Results so far Most pythonic and very efficient: pairs = izip(t[::2], t[1::2]) Most efficient and very pythonic: pairs = izip(*[iter(t)]*2) It took me a moment to grok that the first answer uses two iterators while the second uses a single one. To deal with sequences with an odd number of elements, the suggestion has been to augment the original sequence adding one element (None) that gets paired with the previous last element, something that can be achieved with itertools.izip_longest().

    Read the article

  • How do you use stl's functions like for_each?

    - by thomas-gies
    I started using stl containers because they came in very handy when I needed functionality of a list, set and map and had nothing else available in my programming environment. I did not care much about the ideas behind it. STL documentations were only interesting up to the point where it came to functions, etc. Then I skipped reading and just used the containers. But yesterday, still being relaxed from my holidays, I just gave it a try and wanted to go a bit more the stl way. So I used the transform function (can I have a little bit of applause for me, thank you). From an academic point of view it really looked interesting and it worked. But the thing that boroughs me is that if you intensify the use of those functions, you need 10ks of helper classes for mostly everything you want to do in your code. The hole logic of the program is sliced in tiny pieces. This slicing is not the result of god coding habits. It's just a technical need. Something, that makes my life probably harder not easier. And I learned the hard way, that you should always choose the simplest approach that solves the problem at hand. And I can't see what, for example, the for_each function is doing for me that justifies the use of a helper class over several simple lines of code that sit inside a normal loop so that everybody can see what is going on. I would like to know, what you are thinking about my concerns? Did you see it like I do when you started working this way and have changed your mind when you got used to it? Are there benefits that I overlooked? Or do you just ignore this stuff as I did (and will go an doing it, probably). Thanks. PS: I know that there is a real for_each loop in boost. But I ignore it here since it is just a convenient way for my usual loops with iterators I guess.

    Read the article

  • string comparision and counting the key in target [closed]

    - by mesun
    Suppose we want to count the number of times that a key string appears in a target string. We are going to create two different functions to accomplish this task: one iterative, and one recursive. For both functions, you can rely on Python's find function - you should read up on its specifications to see how to provide optional arguments to start the search for a match at a location other than the beginning of the string. For example, find("atgacatgcacaagtatgcat","atgc") #returns the value 5, while find("atgacatgcacaagtatgcat","atgc",6) #returns the value 15, meaning that by starting the search at index 6, #the next match is found at location 15. For the recursive version, you will want to think about how to use your function on a smaller version of the same problem (e.g., on a smaller target string) and then how to combine the result of that computation to solve the original problem. For example, given you can find the first instance of a key string in a target string, how would you combine that result with invocation of the same function on a smaller target string? You may find the string slicing operation useful in getting substrings of string.

    Read the article

  • Python lists/arrays: disable negative indexing wrap-around

    - by wim
    While I find the negative number wraparound (i.e. A[-2] indexing the second-to-last element) extremely useful in many cases, there are often use cases I come across where it is more of an annoyance than helpful, and I find myself wishing for an alternate syntax to use when I would rather disable that particular behaviour. Here is a canned 2D example below, but I have had the same peeve a few times with other data structures and in other numbers of dimensions. import numpy as np A = np.random.randint(0, 2, (5, 10)) def foo(i, j, r=2): '''sum of neighbours within r steps of A[i,j]''' return A[i-r:i+r+1, j-r:j+r+1].sum() In the slice above I would rather that any negative number to the slice would be treated the same as None is, rather than wrapping to the other end of the array. Because of the wrapping, the otherwise nice implementation above gives incorrect results at boundary conditions and requires some sort of patch like: def ugly_foo(i, j, r=2): def thing(n): return None if n < 0 else n return A[thing(i-r):i+r+1, thing(j-r):j+r+1].sum() I have also tried zero-padding the array or list, but it is still inelegant (requires adjusting the lookup locations indices accordingly) and inefficient (requires copying the array). Am I missing some standard trick or elegant solution for slicing like this? I noticed that python and numpy already handle the case where you specify too large a number nicely - that is, if the index is greater than the shape of the array it behaves the same as if it were None.

    Read the article

  • Using "from __future__ import division" in my program, but it isn't loaded with my program

    - by Sara Fauzia
    I wrote the following program in Python 2 to do Newton's method computations for my math problem set, and while it works perfectly, for reasons unbeknownst to me, when I initially load it in ipython with %run -i NewtonsMethodMultivariate.py, the Python 3 division is not imported. I know this because after I load my Python program, entering x**(3/4) gives "1". After manually importing the new division, then x**(3/4) remains x**(3/4), as expected. Why is this? # coding: utf-8 from __future__ import division from sympy import symbols, Matrix, zeros x, y = symbols('x y') X = Matrix([[x],[y]]) tol = 1e-3 def roots(h,a): def F(s): return h.subs({x: s[0,0], y: s[1,0]}) def D(s): return h.jacobian(X).subs({x: s[0,0], y: s[1,0]}) if F(a) == zeros(2)[:,0]: return a else: while (F(a)).norm() > tol: a = a - ((D(a))**(-1))*F(a) print a.evalf(10) I would use Python 3 to avoid this issue, but my Linux distribution only ships SymPy for Python 2. Thanks to the help anyone can provide. Also, in case anyone was wondering, I haven't yet generalized this script for nxn Jacobians, and only had to deal with 2x2 in my problem set. Additionally, I'm slicing the 2x2 zero matrix instead of using the command zeros(2,1) because SymPy 0.7.1, installed on my machine, complains that "zeros() takes exactly one argument", though the wiki suggests otherwise. Maybe this command is only for the git version.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >