text:
Q: Boss doesn't believe my time estimate... advice/backup? I'm working at a startup software company -- 3 developers, less than 15 employees including the CEO. We deal exclusively with Windows Mobile, the .NET CF, and passing the information gathered from our handheld application to and from our website. My director and I just had a meeting over an urgent project that hasn't begun yet, but it should probably get on a roll soon if we are to meet delivery deadlines for a prospective but very powerful and influential client.
He proceeded to explain the project to me as follows:

*

*The new project will consist primarily of a .NET CF app that allows the client to conduct multiple soil samples over the course of a single session.

*The area being sampled by the user should be shown on a map of appropriate size and scale.

*The map should be dynamically split into grid squares of a size set by the user (in acres).

*On each grid square, the user will have the ability to take notes and mark individual points via real-time GPS from the on-board receiver.

*In addition, functionality should exist to help point the user to any grid square given their current position.

*All information collected should be easily retrieved and read in a very user-friendly manner on the customer's handheld device -- a device which we provide -- at any time.

*All information collected should be easily sent -- through ActiveSync, wirelessly, or what-have-you -- to our website where it should be viewable/editable in an interface similar to that of the handheld device.

With that description in mind I thought things over (albeit rather quickly). With our current staff size, limited budget, and limited resources, I projected that such an endeavor would take roughly 9 to 18 months. Forgive me if I'm off in left field, I'm a recent CS grad and pretty new to the "real" world. However, the project is currently only realized in my director's head, with no design documentation or specs. My question here is, how far off am I, really? Once again, my director -- who has no background in software or IT whatsoever, but is a subject matter expert insofar as soil sampling goes -- put the project at about a 3-month duration.
Keep in mind that we're currently using an unsupported SDK for the rest of our GPS and GIS needs, and ESRI products are almost too far out of range for us. Current functionality in our other apps goes give us a leg up, with the ability already in place for us to draw areas, polylines, and plot points on a map.
I'm just kind of confused/afraid here, wondering if I'm completely wrong or if I'm right but just without confidence. Any and all advice is appreciated. Thanks!

A: Break down the project into as many detailed tasks as you can.
Then estimate each task separately. Sum them up and give a time budget (usually in man.month units = the amount of work that 1 man can accomplish in one month).
In your estimate, include documentation, integration and testing.
Also allow for a buffer to cover holidays, support on other project, etc.
Finally, divide the total estimate by the number of resources and you'll end up with a decent ETA (estimated time of arrival).
You can compare your result with your co-workers and average/re-assess if needed.

A: What your boss has is an idea. What he needs is a complete analysis of the project. What are the problems that are going to be solved, what is the feature set for the application. You (and the other developers) really need to sit down with him and discuss, at great length, just what he has in mind. A good rule of thumb is that for every hour of keyboard time, it should have been preceded by at least 10 hours of discussion. Managers are like that - they do a quick two minute explanation of their idea, then want an exact estimate right then - like that's even possible (NOT!).
As the second comment to your original post suggests, you need to perform a complete systems analysis of the project from start to finish. Make it as detailed as the boss will let you - and push for a deep level of detail - then start arranging the pieces and assigning estimates to them. Add a "Scotty Factor" of at least 1.5 to the total and you will have a rough idea of how long it will take under ideal circumstances.
There will always be things you will not foresee even if feature creep and requirements changes don't add their burden of extended time.
The key here is detail - the boss needs to understand that while he has the big picture in mind, it's the details that make the project. And if the details aren't laid out in plain sight for all to see, pick at, rearrange, modify, etc. then there will be no project to deliver. You will have to do battle with the boss - managers absolutely hate details - they like to wave their hands, say "take care of it" and expect miracles to happen. It's called the "Hero" syndrome - some poor fool steps in, does 16 hours days for months on end and delivers a bastardized version of the project that barely functions and the boss says "see, it can be done".
Count on it - and feel free to show this to the boss - I've been doing software design for over 31 years now and I have yet to come across a project that doesn't operate under the above guidelines - at least one that succeeded!

A: There's probably a mis-communication.
Maybe he misunderstands what his requirements are.  Maybe you misunderstand what his requirements are.  Don't argue over positions: instead of proving yourself right, try to understand him better.
Agile exists to help with problems like this.

A: The situation described is very common especially on software development definition and planning stage and it is incredibly important to learn how to handle it. When making new things, frequently it's not only the solution that is fuzzy, but the problem statement itself lacks clarity and requires re-definition.
Essentially the scenario implies at least one of the three things:

*

*Your boss doesn't know what he is talking about nor has realistic expectations.

*You don't know what you're taking about or not smart enough or just plain lazy.

*You and your boss have wildly different idea of what the problem is or what the solution is going to be or probably both.
It's not difficult to see how the first two implications are really offensive. It's very easy to naturally digress into situation when you might take the position implying that your boss is a loony incompetent dreamer and simultaneously for your boss to adopt the view involving you being both slothful and incompetent techie who's unaware of business realities.
Hence the only sane way out that will help you maintain good relationship and make some progress on the work that keeps the company going seems to be the third option. Normally one of you would say: "Right, such a big discrepancy in the figures can mean only one thing: we understand the problem or the solution rather differently, lets talk through the problem and the solution again, now in much greater detail, until we see where these differences are and manage to get to a common understanding".
Eventually it might turn out that both the understanding of the problem and the proposed solution were incorrect. It might turn out that you need to work to a target, meet a deadline to cash the sale; maybe with a simple solution which is just 60% there and then further expand it to 80% in version two, instead of honouring the initial 100% scope and including less valuable but dev time hungry features that can be easily sacrificed.
In a small start-up no one can be defensive; it's hard enough to bring the new work in and everyone needs to be very resourceful about solving problems given the circumstances. Thus you and the boss need to equally persist in trying to re-formulate the problem and looking for a realistic solution until you agree on a single sensible way to go about the project.

A: If your estimate is 9 to 18 months, it will end up being closer to 24 to 36 months.  It's the nature of development in every business environment I've worked in.  There will be inevitable spec changes and scope creep along the way.  Needed information and resources will be delayed.  The unforeseen will be seen.  Maybe I'm just jaded by every single project I have worked on thus far in my career.  =)
From the description of the project, I don't believe 3 developers could complete all that in three months under the most ideal of circumstances, much less in the "real world".  Especially when you add that while you're developing, part of your time will get pulled into other things:  meetings, support of existing production apps, customer support, ad hoc reporting, etc, etc....

A: It always helps to have something tangible (that they can look at) to present to management. I recommend a spreadsheet (or an MS Project export) with every task you can think of that will go into this project broken out into chunks that, when totaled up, yield an acceptable estimate.
They should be able to look at your document and see that, hey(!), it's going to take a month to develop a prototype of this component, 3 months to test, and so on.
Also helpful is to provide best, expected, and worst case estimates.

A: It's unlikely any of us here has enough information to make a more accurate guess than you.  That said, I don't think you're in left field.  It may be that your team could do a lousy job in three months, assuming everything goes perfectly.  It may be that even in the best of all possible worlds, you still couldn't get it done in three months.
Ask your director what his/her rationale is for the estimate.  You may discover something you weren't considering, or you may be able to add things he/she wasn't considering.
Tell him that you're sticking by your estimate, but try explaining it this way.  There's a large amount of uncertainty right now, and your estimate is 12 months -25% or +50%.  As things become clearer, the estimate may change and the margin of error will shrink.  If it's politically helpful, you can expand the margin and tell your boss it's 12 months -75% or +150%.  Then the 3 months is in there, but so is 2.5 years.
If you get overruled, do your best anyway, and it will be a learning experience (hopefully not too painful) one way or the other.

A: I would eyeball that at a year.
Location-aware applications are cutting-edge development. All the risks of standing on that edge apply here.
You're looking at at least two distinct applications, probably three, and some background jobs cleaning up data and doing additional analysis and reporting.
What I would do is ask for a month to develop a prototype. Preferably on live hardware, but at least in a simulator. You have a lot of technology decisions to make.
Once you have your prototype, you can start iterating to develop features and bi-weekly demos. It will probably be months before you can produce a reliable estimate.

A: Most likely neither your boss nor you have a complete idea about the proposed app, as it is just an idea on a napkin.
Rather then arguing about the estimates perhaps you should do a few spikes, just to test your estimates, is that an option?
As Dustin said this sure looks like a text book example of an agile process. In order to minimize the risk on this project you might choose to deploy a version each month or so. If the customer is happy about the product, well that is perfect, but if he cancells the project during the development your company have only lost X month of work, rathen then the full 18 months.

A:
With that description in mind I thought things over (albeit rather
  quickly). With our current staff size, limited budget, and limited
  resources, I projected that such an endeavor would take roughly 9 to
  18 months.

Giving an off-the-cuff estimate like that is a really bad idea, because usually they are wrong. There are a number of tips given in The Pragmatic Programmer.
I think the most relevant to you is their suggestion for what to say when you are asked for an estimate. The only response is "I'll get back to you." You need to spend some time thinking about the requirements, understanding exactly what you need to do and what might already be done, building a model (either on paper or in your head) of the final system, relating the work that you need to do to similar projects you've done in the past, analyzing the resource availability, and so on.
Slow down, take your time, and be diligent. Never made off-the-cuff estimates to anyone.
If you have the opportunity, you could also take a look at parametric methods of estimation, such as COCOMO or SLIM (the Putnam Model). These take historical databases, but with the right base information and fairly accurate parameters, they generally give good estimates. Another option would be to consult the rest of the team and carry out some form of Wideband Delphi estimation.

Forgive me if I'm off in left field, I'm a recent CS grad and pretty
  new to the "real" world.

Estimation takes plenty of time. The best way to improve your estimates is to keep a log for every project. At the start of the log, record your estimates about the project size, scope, and required effort. Throughout the project, keep track of what happens. At the end, record the final size, scope, and effort. With sufficient time and practice, you can get better at estimation.
Also, no amount of courses or reading will help you get better at estimation. I've read about the PSP and the PROBE methodology, I've taken a number of courses on process management and project management. I've studied software engineering economics. I've even read Steve McConnell's book on software estimation. I've learned plenty of good techniques and strategies, but nothing has made me better than estimation then performing estimation, making mistakes, and learning from them.
Because estimation takes practice, I'm surprised that they are having you estimate such large-scale tasks. You probably have little-to-no experience working at the project level, so I'm not sure how you can be expected to estimate on your own. If I was your manager or lead, I would have you involved with estimation, but not estimating the entire project.

However, the project is currently only realized in my director's head,
  with no design documentation or specs.

This is problematic. Estimations come directly from the understanding of the project. You need some kind of requirements, specification, or end goals in order to even begin to estimate. You also can't estimate off of what is in someone else's head. I, personally, don't estimate unless everything is written down. My estimates correspond to what has been documented, and if what's document changes, then my estimate is also going to change.
Having a paper trail is always a good idea, too. It helps to ensure that the right people are always accountable. That could be in any decision, from an estimate to a project postmortem.

My question here is, how far off am I, really? Once again, my director
  -- who has no background in software or IT whatsoever, but is a
  subject matter expert insofar as soil sampling goes -- put the project
  at about a 3-month duration.

As a software developer, you are probably a better estimator than someone with no software experience is, at least of software development tasks. I forget the quote, but I think it was said by Barry Boehm or maybe Watts Humphrey, but it was something along the lines of the best estimators of engineering tasks are the engineers themselves. When planning an engineering task, the engineers are the ones who need to be involved at every step.

A: You may want to approach this backwards:

*

*Find out the realistic deadline (e.g., is it OK to deliver this in 5-6 months?). All the #s in this example are somewhat relative to this #.

*Set milestones for tasks that need to be achieved based on that deadline. E.g. 1 month for req gathering and building up skills/experience on SDKs/hardware/etc.... 2 months for active development. 2 months for testing. 1 month for unforeseen crap resulting from complexity of all this.
This is a good granularity for first pass, but then you need tor efined with sub-tasks to something with 2-3 days granularity as far as the plan, and preferably time-meshed, e.g. you should have some initial coding tasks allocated to first month.

*Then, cull the requirements or feature set if you see that you are missing the milestones. Please note that you need this "coding tasks at the beginning" I listed before, as it will allow you to determine the correctness of your pace and estimates for coding well before 3 months pass.
Basically, I'm running this (somewhat contrary to usual project management approach) from the "MUST DELIVER BY" standpoint that you seem to have stressed in your post. E.g. Not delivering by hard deadline is NOT an option.

A: You are right to feel confused and afraid. Before you start, remember that there is always the option of finding another job. With that said:
Your boss' eagerness for an early delivery date is merely a reflection of the business' need. If he can't promise the customer the product early next year, then he knows that you won't win the contract, or make the sale, or whatever. The reality of that situation concerns you too - if your employer doesn't win new business then it won't be long before you need to find a new job anyway. So, the first lesson is that your boss is expressing a real need, and that is your need as well as his.
All projects in this situation go something like this: The winning supplier is the one who accepts the craziest timescales and offers the lowest staffing estimates. Three months later, when the customer is expecting their shiny new software to be delivered in a shrink-wrapped box, the vendor if they are lucky will be able to say,

"well, we've run into some
  problems so it's not ready, but here's
  something that does 50% of what you
  asked for. Sorry about the bugs and
  quirks - we're working on them, and we'll have it all sorted in another couple of months!"

If that 50% functionality is enough to let the customer limp through the next 3 months, maybe training their staff on the partial solution, then they'll probably hold off on suing  for a bit. If you can then give them a version that fixes up the core 50% and adds another 30% of new functionality, then they're 80% of the way to getting what they want. Yes, you're already three months late, but if they switch to another vendor it'll be at least 6 months before they get anything. Surely you'll be able to polish off the last 20% of the project in another 3 months?...
...and so on.
This is what will really happen!!
If your manager doesn't admit that then either he's a fool, or (more likely) he's in regular contact with the customer and needs to maintain the feeling of unrealistic optimism needed to convince them to sign the contract.
You can't afford to be optimistic. Plan for the project to be delivered in stages. Start identifying right now which 50% of the functionality is crucial for the customer in those first 3 months. Start pencilling out the 10% of the functionality that will never be delivered. Try to get the customer involved in this process as much as possible - this will help you to manage their expectations, so they aren't totally shocked when reality doesn't quite match up to their hopes and dreams.
And good luck!

A: Even though it is obsolete now, I like using Excel for estimates, as explained here.
http://www.joelonsoftware.com/articles/fog0000000245.html
You take each major task, break it down until you can give an estimate, then estimate it.  By doing this, it forces you to design the application, and the powers-that-be can see what is involved, as there may be many parts that they didn't realize were involved.
You can then track how long it actually took and see why your original estimate is off.
So for the first point, how will the soil samples be collected? Will they be stored in a database or xml file or what?  You can then design out how the UI works, and then give an estimate.  If they want multi-lingual support have that as a separate subtask and tack on a few more hours.
The initial stab may need to be reworked a couple of times, but you should be able to do this in about 1 or 2 days, and get a rough idea as to how long it will take, and then you can show them the data.
Now, if there is some tasks that will take too long because of an unsupported SDK or lack of training, then they can decide to perhaps get a better SDK or hire a contractor, when that part is needed, to develop the part that the developers can't do.
But, this way it gives them a way to determine their budget and timelines.

A: I once wrote a program that does 70% of what you're talking about (it even was for soil samples), as well as a bunch of other stuff (it was a soil sampling robot, so there were robot controls) in about 6 months as the only developer.  The UI wasn't on the mobile device, but was a control program on a laptop... perhaps not dissimilar from your website?  I also split the design and construction of the robot's electronics with another engineer during that time.
If you have a team of 3 knowledgeable developers who are familiar with the hardware, OS, language, and problem domain, I would think 3-4 months would be a reasonable estimate.


text:
Q: What is the correct way how to use database PG POOL I am using node Postgress and I would like to use connection pooling with it. I have simple repository like this:
Init
    const pool = new Pool({
        connectionString: process.env.DATABASE_URL,
    })

    await pool.connect()

Example SELECT code..
export default (
    {
        pgPool,
    }: Object
) => {
    return {
        getExampleData: async (uid: string) => {
            const result = await pgPool.query('SELECT data FROM public.results_table WHERE uid = $1::text;', [uid])
            return result.rows
        },
    }
}

My problem is, that under pressure (a lot of requests) I am getting the following error:

error: remaining connection slots are reserved for non-replication
  superuser connections

I am not sure, if I am using pool correctly.

A: Part of our pgpool.conf:
# - Pool size -

num_init_children = 100
                                   # Number of pools
                                   # (change requires restart)
max_pool = 3
                                   # (change requires restart)

# - Life time -

child_life_time = 120
                                   # Pool exits after being idle for this many seconds
child_max_connections = 0
                                   # Pool exits after receiving that many connections
                                   # 0 means no exit
connection_life_time = 90
                                   # Connection to backend closes after being idle for this many seconds
                                   # 0 means no close
client_idle_limit = 0
                                   # Client is disconnected after being idle for that many seconds
                                   # (even inside an explicit transactions!)
                                   # 0 means no disconnection

The following question/answers also should help you:
Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

Trust this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I hide a footer group in react table? I can't find any documentation on how to hide/show specific footergroups in React Table v7.
 <StyledFooter>
            {footerGroups.map((footerGroup: any) => {
              return (
                <tr {...footerGroup.getFooterGroupProps()}>
                  {footerGroup.headers.map((column: any, index: any) => (
                    <Fragment>
                      {/* Filter out empty renderer Footers */}
                      {column.Footer && (
                        <StyledTd>
                            {column.render('Footer')}
                        </StyledTd>
                      )}
                    </Fragment>
                  ))}
                </tr>
              );
            })}
          </StyledFooter>


text:
Q: WordNet in Portuguese I'm doing a java project where I have to find synonyms of some words. I know WordNet is widely spread, however it is not available in 'portuguese' (the language I'm currently using). Is there something similar to WordNet for the portuguese language?
Thank You.

A: I found this on the Wordnet website. I hope it helps.

Wordnet.PT is a linguistic knowledge
  database for Portuguese, developed at
  the Centre of Linguistics of the
  University of Lisbon
The database, which can be used in
  several domains in Computational
  Linguistics and Language Engineering,
  such as machine translation, search
  engines, information extraction,
  applications for teaching Portuguese,
  among others, is organized according
  to the general EuroWordNet framework,
  a multilingual database integrating
  wordnets for several European
  languages.
Wordnets are lexical-conceptual
  networks organized around a set of
  relations which have been shown by
  research to correspond to the mental
  organization of lexical meaning.

http://www.clul.ul.pt/clg/eng/wordnetpt/index.html

A: Now you can checkout and download OpenWN-PT, the download is in the page http://www.globalwordnet.org/gwa/wordnet_table.html and you can play with it online at
http://casta-net.jp/~kuribayashi/multi/.  Please play with it and help us improve it.
[editing as the code is now in GitHub https://github.com/own-pt and the browsing interface is in http://wnpt.brlcloud.com/wn/]

A: I found this: http://multiwordnet.fbk.eu/english/home.php
Also: http://www.clul.ul.pt/clg/eng/wordnetpt/index.html


text:
Q: Why componentDidUpdate is executing repeatedly I am trying to display user notes on submit. On componentDidMount I am sending a GET request to the server to initially display data. When a user submits a new comment, on componentDidUpdate  I'm checking prevState. If there is any difference found it should load new data from the server.
But inside componentDidUpdate continuous request is sending to the server.
What I have done so far
componentDidUpdate(prevProps, prevState){
    if(prevState.status !== this.props.userDisplayNotes.status){

            // This is GET request to display the data from the server

            this.props.displayUserNotes(this.props.user_id)

    }
}

// Here I'm displaying data on initial rendering with GET request

componentDidMount(){
    this.props.displayUserNotes(this.props.user_id)
}

// This is form submit handler

handleSubmit = (e) => {
    e.preventDefault();
    this.props.saveUserNote(this.props.user_id, this.state.userNote)

}

Upon successful submission of comment I'm getting a response from server like {"status":"success"}
For state management I'm using Redux.
But inside componentDidUpdate it is sending continuous request to server causing application crashed. Can someone please explain me what I'm doing wrong here?

A: You can compare previous Props with new one it will fix your problem
componentDidUpdate(prevProps, prevState){
if(prevProps.userDisplayNotes.status !== this.props.userDisplayNotes.status){
        this.props.displayUserNotes(this.props.user_id)
  }
}


text:
Q: Find the set of solutions to a infinite polynomial I was trying to solve $e^x = x$ and after expanding:
$1+x^2/2!+x^3/3!+x^4/4! ... = 0$ I don't know what to do. Right now I am interested in 2 things: Is there a way to find a closed form for the 0's for the infinite expression, maybe even factor it? (Clearly not in the reals) and second: Within the reals is there a general solution for $e^{a+x} = bx$. I am not looking for any approximations because anyone can do that.Thanks in advance.

A: I guess you are looking for the real solutions.
By the expansion, for $x\geq 0$,
$$e^x-x=1+x^2/2!+x^3/3!+x^4/4!+\dots\geq 1$$
Moreover for $x<0$, $0<e^x=x<0$, so there are no real solutions.
P.S. Over $\mathbb{C}$, the solutions of $\exp(z)=z$ are infinite and they are related with the Lambert W functions (no closed form unfortunately).
See the green dots in this picture taken from  an interesting paper by Stanislav Sykora.


text:
Q: BIRT ODA Plugin Accessing Data Set Filter I have a custom BIRT data source that uses the BIRT Open Data Access (ODA) API similar to the example described in chapter 20 of the book "Integrating and Extending BIRT". However, I've been unable to find any way to pass data set filters to my custom data source.
When I go to run a query in BIRT, it seems to be using the following sequence of events:

*

*BIRT requests all data from my plugin.

*BIRT then applies the filters to the resultset.

So if a user wants to generate a report on April 2013 sales, the BIRT data source plugin is pulling all sales data from the server to the client and then applying the filter to limit to April 2013.
I searched on this issue and came across a similar thread in the BIRT forums from 2009, in that thread, Lina Chan stated that:

I'm afraid the "Filters" defined in BIRT Data Set Editor is something
  defined purely in the BIRT host, and are not visible to an ODA data
  provider. In other words, the BIRT filters' processing is handled by the
  BIRT data engine, and are not pushed down to an ODA runtime driver.

Based on that answer, I'm assuming that it is not possible to do this as of the BIRT version in 2009. Is that answer still correct with today's BIRT version?
Or is there another workaround? It seems odd that BIRT would build such a pluggable interface for data sources, but provide no mechanism to filter the data coming back from the data source.


text:
Q: @EnableBatchProcessing breaks MockMvc tests I'm running a very simple and lightweight test suite with Maven, using MockMvc to test my controllers. I have basic authentication configured, and everything works perfectly.
However, as soon as I put the annotation @EnableBatchProcessing to one of my classes, the tests all fail with a 401 Unauthorized. Just one simple annotation and everything breaks.
Why would a batch processing annotation affect testing in such a way?

A: Turns out the Spring Batch config was off. The problem was essentially the same as here.
I wanted to use an in-memory map for the batch details, but even though it worked, it wreaked havoc when running the tests.
When I worked the configuration down to the following, the tests worked perfectly.
@Configuration
@EnableBatchProcessing
public class ExcelBatchConfig extends DefaultBatchConfigurer {

    /**
     * If we don't provide a datasource, an in-memory map will be used.
     */
    @Override
    @Autowired
    public void setDataSource(DataSource dataSource) {
    }
}


text:
Q: send json object using http post method for android application This is my web service Login url :- http://www.cricutchecklist.com/iphone/login.php
i have to pass username and password.
do you  have android correct code for sending this two parameter perfectly?
username- chandreshkanetiya
password- 9375051117

php webservice parameter is username and password.
My code always returned me :- {"response" : {"success":false,"error":{"code":2,"description":"Incorrect script parameters"}}} if i pass correct username and password.
i am expecting this:-- {"response" : {"success":true,"error":{"code":2,"description":"Incorrect script parameters"}}}
if you solve this problem let me know.
thank you.


text:
Q: Assigning picture to list of objects I am trying to make a program that generates a list of objects and then assign a "portrait" for each object.
Now here is my code so far:
import random
from Tkinter import *
import ttk
from characters import *
from PIL import Image, ImageTk

characters_creation()

eyeslist = ["faces/eyes1.gif", "faces/eyes2.gif", "faces/eyes3.gif",
"faces/eyes4.gif", "faces/eyes5.gif", "faces/eyes6.gif",
"faces/eyes7.gif", "faces/eyes8.gif", "faces/eyes9.gif",
"faces/eyes10.gif", "faces/eyes11.gif"]

eblist = ["faces/eb1.gif", "faces/eb2.gif", "faces/eb3.gif",
"faces/eb4.gif", "faces/eb5.gif"]

noselist = ["faces/nose1.gif", "faces/nose2.gif", "faces/nose3.gif",
"faces/nose4.gif", "faces/nose5.gif", "faces/nose6.gif",
"faces/nose7.gif"]

mouthlist = ["faces/mouth1.gif", "faces/mouth2.gif", "faces/mouth3.gif",
"faces/mouth4.gif", "faces/mouth5.gif", "faces/mouth6.gif",
"faces/mouth7.gif", "faces/mouth8.gif", "faces/mouth9.gif",
"faces/mouth10.gif", "faces/mouth11.gif"]

fhlist = ["faces/fh1.gif", "faces/fh2.gif", "faces/fh3.gif",
"faces/fh4.gif", "faces/fh5.gif", "faces/fh6.gif",
"faces/fh7.gif", "faces/fh8.gif", "faces/fh9.gif",
"faces/fh10.gif"]

mhlist = ["faces/mh1.gif", "faces/mh2.gif", "faces/mh3.gif",
"faces/mh4.gif", "faces/mh5.gif", "faces/mh6.gif",
"faces/mh7.gif", "faces/mh8.gif", "faces/mh9.gif",
"faces/mh10.gif"]

root = Tk()

def RGBAImage(path):
    return Image.open(path).convert("RGBA")

for character in characters:

    face = RGBAImage("faces/face.gif")
    eb = RGBAImage(random.choice(eblist))
    eyes = RGBAImage(random.choice(eyeslist))
    nose = RGBAImage(random.choice(noselist))
    mouth = RGBAImage(random.choice(mouthlist))

    if character.sexe == "Female":
        hair = RGBAImage(random.choice(fhlist))
    else:
        hair = RGBAImage(random.choice(mhlist))

    face.paste(eyes, (0,0), eyes)
    face.paste(eb, (0,0), eb)
    face.paste(nose, (0,0), nose)
    face.paste(mouth, (0,0), mouth)
    face.paste(hair, (0,0), hair)

    facepic = ImageTk.PhotoImage(face)
    character.portrait.append(facepic)

for character in characters:

    cportrait = Label(image=character.portrait)
    cportrait.pack()

root.mainloop()

So every portrait is made of different elements (eyes, nose etc...)
When I run this code I get this error message:
Traceback (most recent call last):   File
"C:\Users\Patrick\Pictures\Kerrell\Kerrell Python\faces_generator.py",
line 67, in <module>
    cportrait = Label(image=character.portrait)   File "C:\Python27\lib\lib-tk\Tkinter.py", line 2591, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)   File "C:\Python27\lib\lib-tk\Tkinter.py", line 2090, in __init__
    (widgetName, self._w) + extra + self._options(cnf)) TclError: image "[<PIL.ImageTk.PhotoImage instance at 0x027E6080>]" doesn't
exist

What I don't understand is that if I run a print function to check there is something in my character portrait list...

A: character.portrait.append(facepic)
#...
cportrait = Label(image=character.portrait)

Going by append, I'm guessing portrait is a list. You can't give a list to the image attribute of a Label.
Either change portrait so it isn't a list:
character.portrait = facepic

Or choose from the portrait list which image the label should have:
cportrait = Label(image=character.portrait[0]) #or whatever index

Or display all of them:
for character in characters:
    for img in character.portrait:
        Label(image=img).pack()


text:
Q: Debezium connector for Redshift based on the existing postgresql one I have been successfully used the Postgresql Debezium plugin for Kafka connect. This connector hooks up directly to the relational database's Write Ahead Log(WAL) which vastly improves performance, compared to the normal JDBC connector, which continuously polls the database via an sql query.
Is something similar possible with Redshift as the source, instead of Postgresql? I know there are major differences between Redshift and Postgresql, in that Redshift is columnar based, cluster-based, doesn't have secondary indexes, and it has different use cases. I could not find definitive information if Redshift has anything similar with a write ahead log or it uses a completely different approach.
Is there a write-ahead-log based approach to stream data changes from a redshift table directly into kafka, via debezium or some other way, or its not technically possible? If not, what about some alternative which achieves the same thing?

A: To answer your question in one line - No, it's not supported, and Im sure that AWS(or any modern DW) will never even think of enabling this feature.
Here are two strong reasons from my point of view:

*

*RedShift itself getting the data from a different database(like your Postgres) and the main purpose is Read not write(so less concurrent writes).

*For analytical purposes we bring all the data into a DW. From there it'll go to BI tool or any ML related works. But I never have seen any place where DW data will go to another database in Real or near realtime.

(You might already know this option)If you still need to do this, then you are getting the data from some sources, right? use that same source to send the data where you want to use from RedShift CDC.


text:
Q: Not able to display label message on success/failure of AjaxFileUpload in ASP.NET I want to upload a file using AjaxFileUpload control. This works fine.The problem is i am not able to display the success/failure message on Label of file uploaded.
.aspx code..
<form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>
                <asp:Label runat="server" ID="myThrobber" Style="display: none;"></asp:Label>
                <asp:AjaxFileUpload ID="AjaxFileUpload1"
                    runat="server"
                    OnUploadComplete="AjaxFileUpload1_UploadComplete"
                    OnClientUploadError="uploadError"
                    OnClientUploadComplete="uploadComplete"
                    ThrobberID="myThrobber"
                    MaximumNumberOfFiles="1"
                    AllowedFileTypes=""
                    class="name_text1"
                    Width="200px" />
                <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                <asp:Button ID="BtnClose" runat="server" Text="Close"
                   onclick="BtnClose_Click" OnClientClick="Closepopup()"/>

                <asp:Label ID="Label2" runat="server" Text=""></asp:Label>

            </ContentTemplate>
        </asp:UpdatePanel>

    </form>

i want to display text on Label2 that file uploaded or not.
my .cs code:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
 string message = "Storege Space is Exceeding its Limit";
                    Label2.Text = message;
}

How to display message on Label ? Any Suggesstion? Help appreciated

A: It might be problem due to update panel,
You have put the AjaxFileUpload inside the update panel,
so update panel controls not update all controls when ever your label fill with text in AjaxFileUpload1_UploadComplete event.
So please try after remove update panel or set the property UpdateMode="Conditional" of update panel.
Hope this will helpful to solve out your problem.

A: The latest version of the ajax file upload comes with an update progress.So if you use it, you don't have to put a label to display the failure/success text.
For more information and demo see this page : http://stephenwalther.com/archive/2012/05/01/ajax-control-toolkit-may-2012-release.aspx

A: function ReBindMaterialsGrid() {
    if (rebindTimer == null) {
        SetRebindTimeout();
    } else {
        clearTimeout(rebindTimer);
        SetRebindTimeout();
    }
}
function SetRebindTimeout() {
    rebindTimer = setTimeout(
        'var btn = document.getElementById("MainContent_AdminTabs_TabContainerMain_TabPanelMaterials_Materials_btnReBindGrid");' +
        'btn.click();', 8888);
}

                                                       <asp:UpdatePanel ID="UpdatePanelUpload" runat="server">
                                                        <ContentTemplate>
                                                            <asp:Label runat="server" ID="lblThrobber" Style="display: none;">

                                                            </asp:Label>
                                                            <asp:HiddenField ID="hdStitchAssetPathUpload" Value='<%# Eval("StitchAssetPath") %>'
                                                                runat="server" />
                                                            <asp:AjaxFileUpload ID="AjaxFileUploadPlank" ThrobberID="lblThrobber" runat="server"
                                                                OnUploadComplete="AjaxFileUploadPlank_UploadComplete" OnClientUploadComplete="ReBindMaterialsGrid" />
                                                        </ContentTemplate>
                                                    </asp:UpdatePanel>


text:
Q: Asp.net need Simultaneous display in Second Text Box I have two text boxes I need a functionality like If I am typing in 1st text box The text should be getting displayed in 2nd text Box with some other font. This is a web Application. And so Text Box doesn't have OnKeyDown event? Do you suggest any way to implement this?
Note: I don't want to implement this with Javascript.

A: Solution using an asp:UpdatePanel
With this approach, you don't need to write a single line of JavaScript by yourself; everything is handled by the control.
Page.aspx:
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:TextBox runat="server" ID="text1" OnTextChanged="text1_TextChanged"></asp:TextBox>
        <asp:TextBox runat="server" ID="text2" class="special"></asp:TextBox>
    </ContentTemplate>
</asp:UpdatePanel>

Event handler for the TextChanged event, Page.aspx.cs:
protected void text1_TextChanged(object sender, EventArgs e) {
    text2.Text = text1.Text;
}

Solution using ASP.NET and jQuery
Page.aspx:
<script type="text/javascript">
    //As soon as the DOM is ready, execute the anonymous function
    $(function () {
        var textBox1 = $("#<%= text1.ClientID %>");
        var textBox2 = $("#<%= text2.ClientID %>");
        textBox1.keyup(function () {
            textBox2.val(textBox1.val());
        });
    });
</script>

<asp:TextBox runat="server" ID="text1"></asp:TextBox>
<asp:TextBox runat="server" ID="text2" class="special"></asp:TextBox>

CSS for both approaches:
 .special { font-family: YourFontFamilyOfChoice; }

Test Results
I've tested both solutions locally with Firefox 3.6, Opera 10.6, and Internet Explorer 8; both work like a charm.

A: Use jQuery (JavaScript) combined with CSS. This solution will not trigger a post-back: Your users will see stuff happen as they type.

CSS:
.normalFont { font-family: Arial; }
.alternateFont { font-family: Verdana; }

HTML:
<input ... class="normalFont" />
<input ... class="alternateFont" />

JavaScript (jQuery):
// When the DOM is ready, execute anonymous function
$(function ()
{
    // store a reference for the input with the "alternateFont" class
    var alternateFontInput = $("input.alternateFont")[0];

    // execute anonymous function on key-up event on the input with
    // the "normalFont" class
    $("input.normalFont").keyup(function ()
    {
        // set the value of the input with the "alternateFont" class to
        // the value of the input with the "normalFont" class (this)
        alternateFontInput.value = this.value;
    });
});


text:
Q: Rearrange Array Result of MySQLi Query I have a MySQLi query that fetches data from my database in json format. Now I want to rearrange the result to form a new array using PHP.
$conn = new mysqli("localhost", "root", "", "angular");

$out = array();

$sql = "SELECT * FROM members";
$query = $conn->query($sql);

while($row=$query->fetch_array()){
    $out[] = $row;
}

echo json_encode($out);

The result of this query is something like this:
[
  {
    "0": "1",
    "1": "Neovic",
    "2": "Devierte",
    "3": "Silay City",
    "memid": "1",
    "firstname": "Neovic",
    "lastname": "Devierte",
    "address": "Silay City"
  },
  {
    "0": "2",
    "1": "Julyn",
    "2": "Divinagracia",
    "3": "E.B. Magalona",
    "memid": "2",
    "firstname": "Julyn",
    "lastname": "Divinagracia",
    "address": "E.B. Magalona"
  },
  {
    "0": "3",
    "1": "Gemalyn",
    "2": "Cepe",
    "3": "Bohol",
    "memid": "3",
    "firstname": "Gemalyn",
    "lastname": "Cepe",
    "address": "Bohol"
  },
  {
    "0": "4",
    "1": "Tintin ",
    "2": "Demapanag",
    "3": "Talisy City",
    "memid": "4",
    "firstname": "Tintin ",
    "lastname": "Demapanag",
    "address": "Talisy City"
  },
  {
    "0": "5",
    "1": "Tintin ",
    "2": "Devierte",
    "3": "Silay City",
    "memid": "5",
    "firstname": "Tintin ",
    "lastname": "Devierte",
    "address": "Silay City"
  }
]

Now I want a result with something like this:
[
    firstname: {"Neovic", "Julyn", "Gemalyn", "Tintin", "Tintin"},
    lastname: {"Devierte", "Divinagracia", "Cepe", "Demapanag", "Devierte"}
]

Can this be achieve in PHP? any help is appreciated.

A: You could store your data in separate arrays :
<?php
$firsts = [] ;
$lasts = [] ;
while ($row = $query->fetch_array()) {
    $firsts[] = $row['firstname'] ;
    $lasts[] = $row['lastname'] ;
}
$out = ['firstname' => $firsts, 'lastname' => $lasts] ;
?>

A: 1.Since you didn't needed all data so do query like this:-
$sql = "SELECT firstname,lastname FROM members";

2.Change while loop code like below and you are done:-
while($row=$query->fetch_array()){
    $out['firstname'][] = $row['firstname'];
    $out['lastname'][] = $row['lastname'];
}

So complete code need to be:-
$conn = new mysqli("localhost", "root", "", "angular");

$out = array();

$sql = "SELECT firstname,lastname FROM members";
$query = $conn->query($sql);

while($row=$query->fetch_array()){
    $out['firstname'][] = $row['firstname'];
    $out['lastname'][] = $row['lastname'];
}

echo json_encode($out);

A: <?php

$i=0;
while ($row = $query->fetch_array())
{
    $user[$i]['first_name'] = $row['firstname'] ;
    $user[$i]['last_name'] = $row['lastname'] ;
   $i++;

 }
json_encode($user);
?>


text:
Q: Hide button function if statement issue - Swift I have a function to hide a slider if another button is pressed. I currently have:
@IBOutlet weak var sliderHide: UISlider!

@IBAction func sliderHide(sender: UISlider) {
    if (buttonPlay.selected) {
        sliderHide.hidden = false
    }
    else if (!buttonPlay.selected) {
        sliderHide.hidden = true
    }
}

The build is running but the slider only hides if itself is selected. It does nothing if the button is selected.

A: Use == not = when comparing,= is an assignment operator.
Moreover, if buttonImage is not a variable representing the control state of a button, but the button itself you want to do:
if buttonImage.selected == false {

}

However, you should use an @IBAction for the button if you want to run a function when it is pressed.
Please consider using an @IBAction for this kind of thing unless your button is programmatically created. You can read more about it here:
http://rshankar.com/different-ways-to-connect-ibaction-to-uibutton/
I

A: I think you want
add an Outlet to the slider like the picture and then wherever you play the sound, make the sliderYouMightHide.hidden = false and wherever the sound stops make the sliderYouMightHide.hidden = true. You might also want to make it hidden in viewDidLoad


text:
Q: UWP - can't interact with localhost IBM Sametime I have a UWP application that should interact with local Sametime client through REST API that is hosted on localhost by I faced with the issue - that's restricted to call localhost from UWP app.
There are a few of solutions:

*

*Create a proxy(e.g. WCF) that will interact with localhost.

*Execute "CheckNetIsolation.exe LoopbackExempt -a -p=SIDHERE" in cmd on each client machine.
But I need a solution that will allow me to use just only a single package file to deploy my application. So may be there is any more elegant solution to solve my problem?
Thanks!


text:
Q: Bash Autocomplete Ubuntu list all rather than cycle On a fresh Ubuntu 12.04 install, my terminal tab-complete settings are configured such that the options are cycled through upon the second tab rather than what I am used to (listing all options and only completing what can be determined)
For example, in a directory containing listPixels.html and listPublishers.html, I want the a tab complete from
l

to simply complete
listP

and then a second tab should list all possible matches rather than cycling through listPixels.html and listPublishers.html on each subsequent tab.

A: You have menu-complete turned on. Simply rebind Tab to complete.
bind '"\C-i":complete'

A: I believe that's a setting in your .inputrc.
Use the line:
set show-all-if-ambiguous On


text:
Q: Show in the email from which page the form was submitted I have a html form on every page and I need to be able to show in the receiver email from which page the visitor submitted the form. How can I achieve this in PHP? I have tried using $_SERVER['REQUEST_URI'] whatsoever, but it just simply doesn't output anything. I'm using Wordpress.
<?php
  global $post;
  $post_slug=$post->post_name;
  $name = $_POST['firstname'];
  $email = $_POST['email'];
  $message="$name.$email";
    mail('example@gmail.com', "Hello", "$name \n $email \n $_SERVER['REQUEST_URI']");
    echo "works";
?>

A: Your code is fine except, you should enclose array variables inside strings with curled braces {}:
mail('example@gmail.com', "Hello", "$name \n $email \n {$_SERVER['REQUEST_URI']}");

If you check the official php documentation on: http://php.net/manual/en/language.types.string.php#language.types.string.parsing you can see in section "Complex (curly) syntax":
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";

A: you can get the actual url with :
$actual_link = "http(s)://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

A: You can try something this . Pass the title of your page ( or the permalink ) to a hidden html input and  take the values as :
 $titlePage = get_the_title($post->ID);

 <input type="hidden" value="<?php echo $titlePage; ?>" name="pagetitle">

Then in your  email code :
 $pagetitle = $_POST['pagetitle'];

Now you have your parameter, use it in your email like you want.


text:
Q: AttributeError: 'DataFrame' object has no attribute 'set_value' I'm using flask and getting error at set_values. I'm reading the input from html and passing it to the code
@app.route('/home', methods=['POST'])
def first():
    source = request.files['first']
    destination = request.files['second']
    df = pd.read_csv(source)
    df1 = pd.read_csv(destination)
    val1 = int(request.form['val1'])
    val2 = int(request.form['val2'])
    val3 = int(request.form['val3'])
    target = request.form['str']
    df2 = df[df.columns[val2]]
    count = 0
    for j in df[df.columns[val1]]:
        x = df1.loc[df1[df1.columns[val3]] == j].index.values
        for i in x:
            df1.set_value(i, target, df2[count])
        count = count + 1
    df1.to_csv('result.csv', index=False)

A: Check your pandas version.
df.set_value() is deprecated since pandas version 0.21.0
Instead use df.at
import pandas as pd

df = pd.DataFrame({"A":[1, 5, 3, 4, 2],
                   "B":[3, 2, 4, 3, 4],
                   "C":[2, 2, 7, 3, 4],
                   "D":[4, 3, 6, 12, 7]})

df.at[2,'B']=100

   A    B  C   D
0  1    3  2   4
1  5    2  2   3
2  3  100  7   6
3  4    3  3  12
4  2    4  4   7


text:
Q: Materialize css 1.0 nested dropdown I have found a nested dropdown example for Materialize 0.98 but it's not working for Materialize 1.00. How would I port it over?
Working example with v0.98 -
https://gist.github.com/the0neyouseek/f1a92b9b8f8962a372c23ef415c63144
I tried to follow the upgrade guide but couldn't get it to work.
Dropdown
Removed gutter option
Removed stopPropagation option
Call plugin on .dropdown-content instead of .dropdown-button
Change attribute data-activates to data-target
Rename classes .dropdown-button to .dropdown-trigger
Rename option belowOrigin to coverTrigger
Removed automatic initialization, initialize it manually as shown in documentation

A: Please replace data-activates attribute with data-target.
Nested DropDown

one▸

two

three

one

two▸

three

three

four

five

six

Materialize changed this attribute in version 1.0 .
Have a look at Materialize Dropdown Doc.

A: Try this solution.

.dropdown-content > li {
  position: relative;
}

.dropdown-content li .dropdown-content {
  position: absolute;
  left: 0 !important;
  top: 0 !important;
}

A: https://codepen.io/FOOGLES/pen/LYYdQeK i hope this help you or other people with the same problem.
nested dropdown its not supported in mat v1 so we need to do some tricks, you need to activate the nested dropdowns with hover, so in matv1 you have to use {
hover: true } in the dropdown selector with Jquery,later with some CSS you make the second and third dropdown take position to the right with left:-100%; or left:100%; if you want the dropdown take left position, i comment the three common options in the CSS.
HTML:

    Menu

uno

uno*

uno

dos

dos

dos

dos

dos*

tres

tres

tres

tres

    .dropdown-nested {
        overflow-y: visible;
    }
    .dropdown-content .dropdown-content {
       /* left: 100%;*/ /*drop hacia la izquierda*/
       left: -100%; /*drop hacia la derecha*/
       /* left: auto;*/ /*drop hacia el centro*/
    }
    .container {
        background: #eee;
        padding: 200px 100px;
        border-radius: 8px;
    }

$('.dropdown-trigger').dropdown();
  $('.sub').dropdown(
  {
    hover:true
  }


text:
Q: Dropdown Code works in Chrome but not in Safari? Anyone know why this dropdown code would be working in Chrome(mac), but not Safari(mac)?
http://jsfiddle.net/v917ycp6/5/
$(function(){

var $cat = $("#category1"),
    $subcat = $("#category2");

$cat.on("change",function(){
    var _rel = $(this).val();
    $subcat.find("option").attr("style","");
    $subcat.val("");
    if(!_rel) return $subcat.prop("disabled",true);
    $subcat.find("[rel="+_rel+"]").show();
    $subcat.prop("disabled",false);
});

});

A: It seems that Safari's selects doesn't work the same as Chrome, and it doesn't allow to disable options with display: none nor with the hidden attribute, so you will need to remove the option elements from the parent select. Other option might be to have 3 different selects, one for each category, and what you show / hide are the full selects in this case.


text:
Q: Who is $(S^1\times S^2)/\mathbb{Z}_2$ with the action $1\cdot (w,z)=(\overline{w},-z)$? Let $\mathbb{Z}_2=\{0,1\}$ act on $S^1\times S^2$ via
$$1\cdot (w,z)=(\overline{w},-z),$$
with $S^1\subset \mathbb{C}$ and $\overline{w}$ is the conjugate of $w$.
I'm trying to understand topologically who is $(S^1\times S^2)/\mathbb{Z}_2$.
At a first glance I was tempted to say that it was a product of a semi circle with a projective plane. But this action is identifying the antipodal points in distinct $2$-spheres. It seems that only when $w=\pm 1$ the associated spheres are projected onto a projective plane.

A: It is $\mathbb{R}P^3\#\mathbb{R}P^3$, since $\mathbb{R}P^3$ can be seen as a half hemisfere of $S^3$ after the identification given by the antipodal map, in which each meridian is a $S^2$ and the equator is $\mathbb{R}P^2$. That is, $\mathbb{R}P^3$ is the mapping cone of the canonical projection $\pi:S^2\to \mathbb{R}P^2$.
If one takes the pole of $\mathbb{R}P^3$ as the base point of the connected sum $\mathbb{R}P^3\#\mathbb{R}P^3$, we have exactly the double mapping cylinder given by
$\pi:S^2\to \mathbb{R}P^2$, which is topologically the same thing that I have said in a the comment, $]0,1[\times S^2\cup \{0,1\}\times \mathbb{R}P^2$.


text:
Q: How to encode flickr short url (base58) in python? How to encode short URLs of Flickr photos? There is no documentation about the base58 method on the official API page about urls.
I can't find examples in Python that are just a function, there are only complicated classes.

A: def b58encode(fid):
  CHARS = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
  CHAR_NUM = len(CHARS)
  encoded = ''
  fid = int(fid)

  while fid >= CHAR_NUM:
    div, mod = divmod(fid, CHAR_NUM)
    encoded = CHARS[mod] + encoded
    fid = div
  return CHARS[fid] + encoded

print(b58encode(2222223333333))

Answer based on https://gist.github.com/mursts/2247355


text:
Q: New versions of Xcode (3.2.5 and up) don't build distribution binaries by default I found that while building in the new 3.2.5 Xcode I wasn't getting the distribution binaries. When I right clicked on the Products folder App no option for "Show in Finder" appeared.
I'm putting this for documentation purposes because I couldn't find an answer here but I figured it out in the end.
Answer is below.

A: Go to your Build menu and select Build and Archive. This will open up Organizer which will bring up a new screen from a section called Archived Applications. This keeps a track of all the bianary builds. From here you can Validate and Submit your App. You no longer have to zip the file and upload with Application Loader.
It's interesting that it lets you validate without having to upload. I haven't played with this a lot so there might be other neat things about it.


text:
Q: How do you find all instances of a substring, followed by a certain number of dynamic characters? I'm trying to find all instances of a specific substring(a!b2 as an example) and return them with the 4 characters that follow after the substring match. These 4 following characters are always dynamic and can be any letter/digit/symbol.
I've tried searching, but it seems like the similar questions that are asked are requesting help with certain characters that can easily split a substring, but since the characters I'm looking for are dynamic, I'm not sure how to write the regex.

A: When using regex, you can use "." to dynamically match any character. Use {number} to specify how many characters to match, and use parentheses as in (.{number}) to specify that the match should be captured for later use.
>>> import re
>>> s = "a!b2foobar a!b2bazqux a!b2spam and eggs"
>>> print(re.findall("a!b2(.{4})", s))
['foob', 'bazq', 'spam']

A: If you're only looking for how to grab the following 4 characters using Regex, what you are probably looking to use is the curly brace indicator for quantity to match: '{}'.
They go into more detail in the post here, but essentially you would do [a-Z][0-9]{X,Y} or (.{X,Y}), where X to Y is the number of characters you're looking for (in your case, you would only need {4}).

A more Pythonic way to solve this problem would be to make use of string slicing, and the index function however.
Eg. given an input_string, when you find the substring at index i using index, then you could use input_string[i+len(sub_str):i+len(sub_str)+4] to grab those special characters.
As an example,
input_string = 'abcdefg'
sub_str = 'abcd'
found_index = input_string.index(sub_str)
start_index = found_index + len(sub_str)
symbol = input_string[start_index: start_index + 4]

Outputs (to show it works with <4 as well): efg

Index also allows you to give start and end indexes for the search, so you could also use it in a loop if you wanted to find it for every sub string, with the start of the search index being the previous found index + 1.

A: import re
print (re.search(r'a!b2(.{4})')).group(1))

.{4} matches any 4 characters except special characters.
group(0) is the complete match of the searched string. You can read about group id here.


text:
Q: Does the layout of this card-based board game impact play? In the game Sequence, players hold a hand of cards from a standard 52 card deck. The "board" consists of two decks of cards (sans Jacks) arranged like so:

When you play a card from your hand, you place a chip on the corresponding card on the board. The goal is to get five chips in a row, orthogonally or diagonally. Each card appears twice on the board, except the Jack which is used as a wild card.
The arrangement of the cards on the table is striking at first, until you notice they form an inward spiral in order of suit and rank. My question is:

If the arrangement of cards were different on the board, would the game be qualitatively different?

My first assumption was no, because either way, your hand consists of a set of random locations on the board where you may play a chip. If the board itself is randomized on top of that, the locations which you have access to from the cards in your hand are still randomly distributed.
But then, in the course of play, I noticed a feature on this board: in the third from the right column, bottom five rows, there is a sequence of five cards capped on either end by the same card: the King of Clubs. So in order to get that specific sequence, one needs to draw both Kings of Clubs (or one or two Jacks), in addition to the cards in between. And I thought: if the board were randomly reordered, maybe there wouldn't be any sequence of five cards capped on either end by the same card. Then, wouldn't play be qualitatively different in that circumstance?
The draw deck consists of two decks of cards, so each card appears twice (like the board itself). There are therefore only two Kings of Clubs in the deck. In another case, suppose the desired pair was the Ace of Spades and the Five of Diamonds (in the top row). There are two Aces of Spades and two Fives of Diamonds in the deck, so it is therefore slightly more likely (?) to obtain that pair than the pair "two Kings of Clubs".
On the other hand, it may be that (through some pigeonhole/graph coloring type argument) one can say that the event "a sequence of five cards is capped on either end by the same card" actually occurs in every arrangement of the board. In which case, play would not be qualitatively different except for the labelling of the cards in the draw deck/on the board.
I am not sure. I think a more precise question is as follows:

Which events over this board have a probability which is preserved under all rearrangements of the board?

As an example of a nontrivial event which satisfies this property: there are always as many red cards on the left half of the board as there are black cards on the right half, by combinatorics. This aspect of the game is therefore persistent in every arrangement of the board.


text:
Q: Two way trust Exchange mailbox creation We have a two way trust between Domain A and Domain B. They are both Windows Server 2012 R2. Domain A has Exchange 2013 on it for the use of Domain A users. We want to create user mailboxes from Domain B on Domain A. Is this possible without creating new AD users on Domain A?

A: You can create linked mailboxes in Domain A for the users in Domain B.
https://technet.microsoft.com/en-us/library/jj673532(v=exchg.150).aspx


text:
Q: How to pass % in a URL query string? I am trying to pass a string via HTTP request which has one of the character as % in the URL query string.
url = url + "?q=" + str + "&block=" + block;  // str contains the '%' character

But on the ColdFusion page where I'm sending this information is returning following error:

Element Q is undefined in URL.

How can I encode the % sign in a URL?

A: Pass your string trough the function encodeURI(...) it will escape all the special characters not only the %

A: %25
http://www.w3schools.com/TAGS/ref_urlencode.asp

A: URLEncodedFormat() in ColdFusion

A: You should url-encode all the values you are passing as query parameters, but the url-encoding for % is %25
Update: if you're constructing the query parameters in javascript, you probably want to do:
url=url+"?q="+encodeURIComponent(str)+"&block="+encodeURIComponent(block)

(Updated again with ZeissS' very helpful suggestion to use encodeURIComponent instead of escape. See also http://xkr.us/articles/javascript/encode-compare/)

A: We can use URLEncodedFormat() in ColdFusion as well as we can use the below mentioned one.

*

*encodeURI(...)

*encodeURIComponent

This two also help us to resolve our issue.


text:
Q: if-else spipping search strategy in LINQ query I am trying to filter multiple attribute from the database. I am filtering with 3 attributes. Which may be empty or a key in any combination. I have tried this code, It working fine when I filtered in three steps,
IEnumerable<Employee> ItemsList = _db.Employees.AsEnumerable().Where(e => e.Role == 2).OrderByDescending(e => e.EmployeeID);
 if (!String.IsNullOrEmpty(SearchKeyByName))
            {
                ItemsList = ItemsList.Where(e => e.FirstName.ToLower().StartsWith(SearchKeyByName.Trim().ToLower()) || e.LastName.ToLower().StartsWith(SearchKeyByName.Trim().ToLower()) || (e.FirstName + " " + e.LastName).ToLower().StartsWith(SearchKeyByName.Trim().ToLower()));
                ViewBag.Search_FullName = SearchKeyByName;
            }
            if (!String.IsNullOrEmpty(SearchKeyByDepartment))
            {
                ItemsList = ItemsList.Where(e => e.Department.DepartmentTitle.ToLower().StartsWith(SearchKeyByDepartment.Trim().ToLower()));
                ViewBag.Search_Department = SearchKeyByDepartment;
            }
            if (!String.IsNullOrEmpty(SearchKeyByDesignation))
            {
                ItemsList = ItemsList.Where(e => e.Designation.ToLower().StartsWith(SearchKeyByDesignation.Trim().ToLower()));
                ViewBag.Search_Designation = SearchKeyByDesignation;
            }

But I want to minimize this 3 if condition with LINQ, I have tried 1 of this using this code
IEnumerable<Employee> ItemsList2 = (from e in _db.Employees.AsEnumerable()
                                               where e.Role == 2
                                                where (!String.IsNullOrEmpty(SearchKeyByName) && (e.FirstName.Trim().ToLower().StartsWith(SearchKeyByName.Trim().ToLower()) || e.LastName.ToLower().StartsWith(SearchKeyByName.Trim().ToLower()) || (e.FirstName + " " + e.LastName).ToLower().StartsWith(SearchKeyByName.Trim().ToLower())))
                                                select e).OrderByDescending(e => e.EmployeeID);

But the filtering result is being null/empty. 1st one is working well. Mention that, The search key may be empty, then it need to peek up all values but when key is provided then it will take only key findings one.

A: The problem is the &&; you are requiring that SearchKeyByName is always not empty/null by using that. Your filter should keep all records if SearchKeybyName is null or missing or use it in the search otherwise: SearchKeyByName.IsNullOrEmpty() || (rest of it). But in this case, you can even simplify that out by using null coalescing, since every string starts with the empty string:
var ItemsList2 =
    from e in _db.Employees
    let loweredSearch = (SearchKeyByName ?? "").Trim().ToLower()
    where
        e.Role == 2
        && (
            (e.FirstName + " " + e.LastName).ToLower().StartsWith(loweredSearch)
            || e.LastName.ToLower().StartsWith(loweredSearch)
        )
    orderby e.EmployeeID descending
    select e;

But this is probably more efficient:
var ItemsList2 =
    from e in _db.Employees
    let loweredSearch = (SearchKeyByName ?? "").Trim().ToLower()
    where
        e.Role == 2
        && (
            loweredSearch == string.Empty
            || (e.FirstName + " " + e.LastName).ToLower().StartsWith(loweredSearch)
            || e.LastName.ToLower().StartsWith(loweredSearch)
        )
    orderby e.EmployeeID descending
    select e;


text:
Q: How to reserve public API to internal usage in .NET? I have objects and collections, which should support the Merge API (it is my custom API, the signature of which is immaterial for this question). This API must be internal, meaning only my framework should be allowed to invoke it. However, derived types should be able to override the basic implementation.
The natural way to implement this pattern as I see it, is this:

*

*The Merge API is declared as part of some internal interface, let us say IMergeable.

*Because the interface is internal, derived types would not be able to implement it directly. Rather they must inherit it from a common base type. So, a common base type is introduced, which would implement the IMergeable interface explicitly, where the interface methods delegate to respective protected virtual methods, providing the default implementation. This way the API is only callable by my framework, but derived types may override the default implementation.

The following code snippet demonstrates the concept:
internal interface IMergeable
{
  void Merge(object obj);
}

public class BaseFrameworkObject : IMergeable
{
  protected virtual void Merge(object obj)
  {
    // The default implementation.
  }

  void IMergeable.Merge(object obj)
  {
    Merge(obj);
  }
}

public class SomeThirdPartyObject : BaseFrameworkObject
{
  protected override void Merge(object obj)
  {
    // A derived type implementation.
  }
}

All is fine, provided a single common base type suffices, which is usually true for non collection types.
The thing is that collections must be mergeable as well. Collections do not play nicely with the presented concept, because developers do not develop collections from the scratch. There are predefined implementations - observable, filtered, compound, read-only, remove-only, ordered, god-knows-what, ... They may be developed from scratch in-house, but once finished, they serve wide range of products and should never be tailored to some specific product. Which means, that either:

*

*they do not implement the IMergeable interface at all, because it is internal to some product

*the scope of the IMergeable interface is raised to public and the API becomes open and callable by all.

Let us refer to these collections as standard collections. Anyway, the first option screws my framework, because now each possible standard collection type has to be paired with the respective framework version, augmenting the standard with the IMergeable interface implementation - this is so bad, I am not even considering it.
The second option breaks the framework as well, because the IMergeable interface should be internal for a reason (whatever it is) and now this interface has to open to all.
So what to do?
My solution is this. make IMergeable public API, but add an extra parameter to the Merge method, I call it a security token. The interface implementation may check that the token references some internal object, which is never exposed to the outside. If this is the case, then the method was called from within the framework, otherwise - some outside API consumer attempted to invoke it and so the implementation can blow up with a SecurityException.
Here is the modified code snippet demonstrating this concept:
internal static class InternalApi
{
  internal static readonly object Token = new object();
}

public interface IMergeable
{
  void Merge(object obj, object token);
}

public class BaseFrameworkObject : IMergeable
{
  protected virtual void Merge(object obj)
  {
    // The default implementation.
  }

  public void Merge(object obj, object token)
  {
    if (!object.ReferenceEquals(token, InternalApi.Token))
    {
      throw new SecurityException("bla bla bla");
    }

    Merge(obj);
  }
}

public class SomeThirdPartyObject : BaseFrameworkObject
{
  protected override void Merge(object obj)
  {
    // A derived type implementation.
  }
}

Of course, this is less explicit than having an internally scoped interface and the check is moved from the compile time to run time, yet this is the best I could come up with.
Now, I have a gut feeling that there is a better way to solve the problem I have presented.
I do not know, may be using some standard Code Access Security features? I have only vague understanding of it, but can LinkDemand attribute be somehow related to it? Anyway, I would like to hear other opinions.

A: Don't try to modify the objects at all. Create a merge service instead.
public interface IMergerService
{
    void Merge(object value);
}

and build mergers for each type you like to support:
public interface IMergerFor<T> where T : class
{
}

public class UserMerger : IMergerFor<User>
{
}

In this way you can expose a custom api which the user can use and leave all the secret details hidden.


text:
Q: Obj-c UIImageView is null when calling from outside class I have a UIViewController containing a UIImageView that has been correctly wired up (I can set image inside controller).
I have also set an iVar using
UIImageView *_imgQRCode;

and a property using
@property (strong, nonatomic) IBOutlet UIImageView *imgQRCode;

Synthesized using:
@synthesize imgQRCode = _imgQRCode;

But when I call something like below I nothing happens the image and when I inspect in Xcode the reference is memory reference is 0x00000000. note the code works when called inside the ViewController. The following is called from any other view controller with controller instantiated as follow:
QRPopupViewController *qrPop = [[QRPopupViewController alloc] initWithNibName:@"QRPopupViewController" bundle:nil];

[controller.imgView setImage:[UIImage imageNamed:@"sample.png"]];

Any ideas how to fix this and why i'm getting null?

A: Firsty: outlets should be weak
@property (weak, nonatomic) IBOutlet UIImageView *imgQRCode;

You have to hook imgQRCode outlet to your viewController, and you can use it inside viewDidLoad.

A: You will get null for all UI Control's instances which are not part of the currently visible view controller. So due to this all your calls to that UI control will not perform the UI related operation.
If you want to update any UI control which is not part of currently visible view controller, you can use app delegate. It is the only place which is centralized in between all view controllers.
There is a mechnism, called "protocol delegate" to call some method to update UI part from the currently visible view controller. You can go through this URL for detail about this.
If you are selecting the approach of "protocol delegate", then explore the method execution flow in detail. When you call a protocol from a method of currently visible view controller, the corresponding protocol implementation method will be called after the completion of the caller method. So you need to take care of synchronization.


text: Q: Would scrolling of mouse be a hardware or a software interrupt? I'm basically a computer science grad student and have developed an interest in device drivers and software-hardware interaction. I am assuming that clicking the mouse or pressing a key on the keyboard would be a hardware interrupt managed by a software event-handler for the programmer to interact with it, but I'm unable to figure out whether scrolling of mouse would be a hardware or a software interrupt. Also which type of interrupt is more costly to handle for the processor?


text:
Q: How to filter properly my access logs with GoAccess? I want to generate a report with only the POST /xmlrpc.php requests, so I run the following command :
zcat access.log.*.gz | grep 'POST /xmlrpc.php' | goaccess -a -o report-xmlrpc.html

The results of the report are not all displayed (in the graph I see only 9 days, but I checked on the others logs and I have POST /xmlrpc.php requests almost every days (30 in total) ).
Am I using zat / grep / goaccess wrong ?

A: You are parsing only *.gz logs, I assume you want to parse all of them (compressed and not compressed), try this instead:
zgrep -h 'POST /xmlrpc.php' access.log* | goaccess -a -o report-xmlrpc.html


text:
Q: ansible loop over ip addresses in variable file instead of inventory i am having an issue where playbooks are executed multiple times.I have ip address of servers set in inventory as well as in variable file.
---
- hosts: servers
gather_facts: no
vars_files:
- input.yml
tasks:

- name: Powering On Servers
  local_action: ipmitool -I lanplus -H {{item.consoleofserver}} -U {{item.consoleuser}} -P {{item.consolepassword}} power on
  with_items:
   - "{{ computeserver }}"

- name: Waiting for Servers to be up
   local_action:
   wait_for
   host={{ item.ipaddress }}
   port=22
   delay=10
   timeout=3600
  sudo: false
  with_items:
   - "{{ computeserver }}"

- name: Configuring ip address on application
 lineinfile:
   state=present
   create=yes
   dest=/etc/app/app.conf
   regexp='^my_ip =.*'
   line='my_ip = {{item.ipaddress}}'
 with_items:
    - "{{ computeserver }}"
 when: ansible_nodename == item.name

variable file - input.yml
---

computeserver:
- name: compute4
  ipaddress: 192.168.211.251
  console: 192.168.211.10
  consoleuser: administrator
  consolepassword: 1

- name: compute5
  ipaddress: 192.168.211.253
  console: 192.168.211.11
  consoleuser: administrator
  consolepassword: 1

- name: compute6
  ipaddress: 192.168.211.252
  console: 192.168.211.12
  consoleuser: administrator
  consolepassword: 1

inventory file:
[servers]
192.168.211.251
192.168.211.253
192.168.211.252

Result:
ansible-playbook addserver.yml
TASK: [Powering ON Servers]   ***************************************************
changed: [192.168.211.251 -> 127.0.0.1] => (item={'console': '192.168.211.10', 'consolepassword': 1, 'ipaddress': '192.168.211.251', 'name': 'compute4', 'consoleuser': 'administrator'})
changed: [192.168.211.253 -> 127.0.0.1] => (item={'console': '192.168.211.10', 'consolepassword': 1, 'ipaddress': '192.168.211.251', 'name': 'compute4', 'consoleuser': 'administrator'})
changed: [192.168.211.252 -> 127.0.0.1] => (item={'console': '192.168.211.10', 'consolepassword': 1, 'ipaddress': '192.168.211.251', 'name': 'compute4', 'consoleuser': 'administrator'})
changed: [192.168.211.251 -> 127.0.0.1] => (item={'console': '192.168.211.11', 'consolepassword': 1, 'ipaddress': '192.168.211.253', 'name': 'compute5', 'consoleuser': 'administrator'})
changed: [192.168.211.253 -> 127.0.0.1] => (item={'console': '192.168.211.11', 'consolepassword': 1, 'ipaddress': '192.168.211.253', 'name': 'compute5', 'consoleuser': 'administrator'})
changed: [192.168.211.252 -> 127.0.0.1] => (item={'console': '192.168.211.11', 'consolepassword': 1, 'ipaddress': '192.168.211.253', 'name': 'compute5', 'consoleuser': 'administrator'})
changed: [192.168.211.251 -> 127.0.0.1] => (item={'console': '192.168.211.12', 'consolepassword': 1, 'ipaddress': '192.168.211.252', 'name': 'compute6', 'consoleuser': 'administrator'})
changed: [192.168.211.253 -> 127.0.0.1] => (item={'console': '192.168.211.12', 'consolepassword': 1, 'ipaddress': '192.168.211.252', 'name': 'compute6', 'consoleuser': 'administrator'})
changed: [192.168.211.252 -> 127.0.0.1] => (item={'console': '192.168.211.12', 'consolepassword': 1, 'ipaddress': '192.168.211.252', 'name': 'compute6', 'consoleuser': 'administrator'})

So instead of adding servers in inventory file can i tell ansible to use ip address defined in variable file to use as target servers,this may fix looping over same server again and again.

A: There is the add_host module.
You should be able to do something like this:
- hosts:
  - localhost
  gather_facts: no
  vars_files:
  - input.yml
  tasks:
  - add_host: hostname={{ item.ipaddress }} groups=generated_group
    with_items: computeserver

- hosts: generated_group
  tasks:
  ... your other tasks

A: You can limit a task to be only executed once, with the run_once property.
- name: Powering On Servers
  local_action: ipmitool -I lanplus -H {{item.consoleofserver}} -U {{item.consoleuser}} -P {{item.consolepassword}} power on
  run_once: true
  with_items: computeserver


text:
Q: Logistic Regression using for loops in R I am trying to run a binary logistic regression using For loops in R.
My code for the same is as follows:
mydata5<-read.table(file.choose(),header=T,sep=",")
colnames(mydata5)
 Class <- 1:16
Countries  <- 1:5
Months  <- 1:7
DayDiff  <- 1:28
mydata5$CT <- factor(mydata5$CT)
mydata5$CC <- factor(mydata5$CC)
mydata5$C <- factor(mydata5$C)
mydata5$DD <- factor(mydata5$DD)
mydata5$UM <- factor(mydata5$UM)
for(i in seq(along=Class))
   {
     mydata5$C=mydata5$C[i];

for(i2 in seq(along=Countries))
{
  mydata5$CC=mydata5$CC[i2];

for(i3 in seq(along=Months))
{
  mydata5$UM=mydata5$UM[i3];

for(i4 in seq(along=DayDiff))
{
  mydata5$DD=mydata5$DD[i4];

  lrfit5 <- glm(CT ~ C+CC+UM+DD, family = binomial(link = "logit"),data=mydata5)
  summary(lrfit5)
  library(lattice)
  in_frame<-data.frame(C="mydata5$C[i]",CC="mydata5$CC[i2]",UM="mydata5$UM[i3]",DD="mydata5$DD[i4]")
  predict(lrfit5,in_frame, type="response",se.fit=FALSE)
}
}
}
}

However, I'm getting the following error:
Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels
Why is the error occurring? Also,the dataset "mydata5" has around 50000 rows.Please help.
Thanks in Advance.

A: You have tried to do a regression with a factor having only one level. Since you haven't given us your data we can't reproduce your analysis but I can simply reproduce your error message:
> d = data.frame(x=runif(10),y=factor("M",levels=c("M","F")))
> d
            x y
1  0.07104688 M
2  0.11948466 M
3  0.20807068 M
4  0.24049508 M
5  0.44251492 M
6  0.69775646 M
7  0.44479983 M
8  0.64814971 M
9  0.75151207 M
10 0.38810621 M
> glm(x~y,data=d)
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels

By setting one of the factor values to "F" I don't get the error message:
> d$y[5]="F"
> glm(x~y,data=d)

Call:  glm(formula = x ~ y, data = d)

Coefficients:
(Intercept)           yF
    0.39660      0.04591

Degrees of Freedom: 9 Total (i.e. Null);  8 Residual
Null Deviance:      0.5269
Residual Deviance: 0.525    AIC: 4.91

So somewhere in your loops (which we cannot run because we don't have your data) you are doing this.


text:
Q: LinkedIn OAuth a required parameter "client_id" is missing I am working with the LinkedIn API and trying to make request but when I try to get my accesstoken I am getting the following error in my json print:
Array ( [error] => missing_parameter [error_description] => A required parameter "client_id" is missing )

This is my code:
<?php

    $url = parse_url("https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
    parse_str($url['query'], $url);

    $code = $url['code'];

    $data = array("grant_type" => "authorization_code",
                  "code" => $code,
                  "redirect_uri" => "REDIRECT_URI",
                  "client_id" => "SECRET",
                  "client_secret" => "SECRET"
              );

    $url2 = "https://www.linkedin.com/oauth/v2/accessToken";

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_URL, $url2);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    curl_close($curl);

    $result_array = json_decode($result, true);

    print_r($result_array);

    include('../twitter/navigatie.php');

    echo '
';

    echo '';

    echo '
';

?>

A: I found the problem
it needed to be in a string.
so this:
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

became this:
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));

Curl or LinkedIn seemed kinda sensitive for it.


text:
Q: Json System.err: Unexpected character () at position 0. only from php URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();

int code = urlConnection.getResponseCode();
System.out.print(code);

if (code==200) {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    if (in != null) {
        String content = in.toString();
        System.out.print(content);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(new InputStreamReader(in, "UTF-8"));
        result = (String) jsonObject.get("name");
        System.out.print(jsonObject);
    }
    in.close();
}

When I have a host string like http://www.example.com/json.txt it all works fine, but when I have host string like www.example.com/index.php?data=data&data2=data2 I get the following error:

W/System.err: Unexpected character () at position 0.
  I/System.out: 200java.io.BufferedInputStream@8bc189fpp = [0, 700, 250, 700]

My PHP output in browser looks fine, when I copy it to json.txt it also works fine.
I try to play with urlConnection POST, GET, RAW without luck.
Any ideas?

A: Problem was probly BOM in php json.
I do:
URL url = new URL(host);
            urlConnection = (HttpURLConnection) url.openConnection();

            int code = urlConnection.getResponseCode();
            System.out.print(code);
            if(code==200){
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                StringWriter writer = new StringWriter();

                if (in != null) {

                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                        String line = "";

                        while ((line = bufferedReader.readLine()) != null)
                            result += line;

                    result = result.substring(1);
                    JSONParser jsonParser = new JSONParser();
                    JSONObject jsonObject = (JSONObject)jsonParser.parse(result);
                    result=(String) jsonObject.get("name");
                    System.out.print(jsonObject);
                }
                in.close();
}

And it works.


text:
Q: drupal 6 mini pager theming I am trying to theme particular pagers on the site and no matter what id I try it doesn't seem to get picked up. This is what I am using to theme all pagers now.
function Subtle_Hightlights_views_mini_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 9) {
  global $pager_page_array, $pager_total;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  $pager_max = $quantity;
  // End of marker calculations.

  $li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('')), $limit, $element, 1, $parameters);
  if (empty($li_previous)) {
    $li_previous = "";
  }

  $li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('')), $limit, $element, 1, $parameters);
  if (empty($li_next)) {
    $li_next = "";
  }

  if ($pager_total[$element] > 1) {
    $items[] = array(
      'class' => 'pager-previous-mini',
      'data' => $li_previous,
    );
 if ($pager_current == 9){
    $li_next = "";
 }
    $items[] = array(
      'class' => 'pager-current-mini',
      'data' => t('@current of @max', array('@current' => $pager_current, '@max' => $pager_max)),
    );

    $items[] = array(
      'class' => 'pager-next-mini',
      'data' => $li_next,
    );
    return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
  }
}

now this works to theme all mini pagers but when I try to apply the name of the view and block like this.
function Subtle_Hightlights_views_mini_pager__news_items__block_2($tags = array(), $limit = ``10, $element = 0, $parameters = array(), $quantity = 9) {
does nothing acts as though the code isnt there anymore. Anyone else tried this and it actually worked?

A: There is a good step by step instructions on how you can overwrite the pager (mini or full). The only step that I would suggest that you do different is when you get to list of theme function names that you can use to override your views pager inside your template.php file, just use this module: Theme developer. Once it's enabled it will provide in a much easier way the suggestions. If that fails, then just try the article's methods.
Drupal 6 Override views pager theme function


text:
Q: the telegram bot does not work;in your opinion, why does the bot not work? I'm building a telegram bot with the Python-Telegram-Bot framework.To test the bot, I added it to a super group and I got the bot into the Super group Admin.
My code for creating a bot:
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters

updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher

def sticker_method(bot, update):
    update.message.delete()

def main():
    dispatcher.add_handler(MessageHandler(Filters.sticker, sticker_method))

dispatcher.add_handler(CommandHandler('start', main))
updater.start_polling()
updater.idle()

I want to create the bot that when /start command send to the bot, then the bot delete the stickers that the members send to the super group.that means as /start of a command, when the creator super group(I) sends a bot , the bot should delete the stickers that are sent to the super group.
But the bot does not work!And do not give any error!
In your opinion, why does the bot not work?

A: Is this duplicate question?
My answer, that is impossible.

Your bot need have Delete Message permission, and Privacy Mode should be disabled.
Bots can't get message list, they can only receive that when someone sends it, so you need to log Enable/Disable state to your own database and delete Sticker when received new messages.


text:
Q: Strapi & Next.JS - SEO data at build time I've had a crack at trying to get a dynamic SEO component working for my website, by grabbing the data, waiting until it's loaded, and inserting it into a component. I'm going to change some of the names of things to simplify the example.
This is in one of my pages, an [id].js that Next supports.
import Head from "next/head"
import {useRouter} from 'next/router'
import Layout from "../../components/layout/layout"
import SEO from "../../components/layout/seo"
import { DATA } from "../../components/dataFetch"

const ID = () => {
    const router = useRouter()
    const { id } = router.query

    const strapi = DATA(`strapi?_slug=${id}`)
    // ...
    return (
      <Head>
        {!strapi.loading && strapi.data.map((s) => {
          <SEO

            title={s.name} // the name of the strapi item
            description={strapi.description} // description for whatever it is
            keywords={[s.name, s.keyword_tag, s.keyword_tag_2]} // mostly an example
            image={s.thumb.formats.medium.url} // image

          />
        })}
      </Head>
    )
}

And then here is what the SEO component in question looks like:
import React from 'react'

const SEO = ({title, description, keywords, image}) => {
    if (keywords) { /* combine all the keywords in the array and make it a string for meta */
        keywords.join(',')
    }
    if (!image) { /* Set the default image if there is none currently */
        image = 'https://google.com/image.png';
    }
    return (
        <>
            {/* meta */}
            <title>{title} | website</title>
            <meta name="viewport" content="initial-scale=1.0, width=device-width"/>
            <meta name="description" content={description} />
            <meta name="keywords" content={keywords} />
            {/* og */}
            <meta property="og:title" content={`${title} | website`} key="facebook title" />
            <meta property="og:description" content={description} />
            <meta property="og:url" content="" />
            <meta property="og:image" content={image} />
            {/* twitter */}
            <meta property="twitter:title" content={`${title} | website`} key="twitter title" />
            <meta property="twitter:description" content={description} />
            <meta property="twitter:card" content="summary_large_image" />
            <meta property="twitter:image" content={image} />
        </>
    )
}

export default SEO

This SEO code will work in a place like the index page, because the data isn't fetched - it's statically written (at least in the home page). I want to try and get it so that I can dynamically grab this content and insert it into my header if possible.
And as well, just to make sure all of my bases are covered, here is my dataFetch component, which is referenced as DATA(`strapi?_slug=${id}`) in the code.
import {useState, useEffect} from 'react'
import axios from 'axios'

export const DATA = (query) => {
    const [data, setData] = useState([])
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState(false)

    useEffect(() => {
        const fetchData = async() =>
        {
            setError(false)
            setLoading(true)
            try {
                const res = await axios(`${process.env.REACT_APP_STRAPI_API}/${query}`)
                setData(res.data)
            } catch (error) {
                setError(true)
            }
            setLoading(false)
            console.log(data, query)
        }
        fetchData()
    }, [query])

    return {data, loading}
}

This dataFetch code works fine in the context of fetching the data and providing it. For just about all the strapi data I grab. Not sure this would be a problem but just wanted to include it, just in case.
So TD;LR: Trying to dynamically generate SEO meta headers with Strapi Data, isn't working as the connection isn't working at lightspeed so it appears as an error 500 and doesn't append the data to the header. Any tips?


text:
Q: Wix doesn't remove its files if I remove mine I have a Wix installer which installs and removes fine if I don't execute my custom actions. But if I do execute them then my custom action does its job, and the uninstall does succeed, but all of the files installed remain in the program files application directory.
On install, my custom action (After="InstallFiles") extracts a number of files from a Zip into directories under the main install directory. I also capture a list of all files extracted (added). This works perfectly.
On uninstall, my custom action (After="MsiUnpublishAssemblies") runs through the list and removes the added files, added sub-directories and the file list itself. This works fine - my added files are removed. But the primary files originally installed by the installer are left behind even though the installer goes through all the steps (as far as I can tell by the log file) and ends successfully.
Any ideas would be a great help here.
Thanks!
Update:
I have tentatively solved this the brute-force way, but I would still like a real answer. Here's my brute-force code. I call it with a DirectoryInfo of my InstallDir.
    private static void CleanupTheRest(DirectoryInfo dirInfo)
    {
        // until I figure out why the unistall won't remove these after executing my CA
        foreach (var subDirInfo in dirInfo.GetDirectories())
        {
            CleanupTheRest(subDirInfo);
        }
        foreach (var file in dirInfo.GetFiles())
        {
            file.Delete();
        }
        dirInfo.Delete();
    }

A: Extracting a ZIP really isn't the best way of going about things, that aside however you just need to use the RemoveFile element to have Windows Installer delete the files during uninstallation.

A: The approach you are using to extract files from an embedded zip isn't something I would put into my MSI. Rather I would have the application extract the zip on launch - much more controllable and reliable. Actually I wouldn't recommend any unzipping at all, but sometimes it is necessary for data files.
How have you scheduled your remove operation? Immediate / Deferred? Do you use synchronous or asynchronous running mode? If you comment out your uninstall custom action, does the uninstall work? If you have enabled the "legacy shareddll ref-count" feature, you could have trash reference counts in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs (if so delete the entries and try again - this may make the uninstall work as expected).


text:
Q: TypeError: 'DiscreteFactor' object is not subscriptable I have a Bayesian algorithm program to be executed, I am using python 3
import numpy as np
import csv
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)

print('Few examples from the dataset are given below')
print(heartDisease.head())

model = BayesianModel([('age','trestbps'),('age','fbs'),('sex','trestbps'),('exang','trestbps'),('trestbps','heartdisease'),('fbs','heartdisease'),('heartdisease','restecg'),('heartdisease','thalach'),('heartdisease','chol')])

print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)

print('\n Inferencing with Bayesian Network:')
HeartDisease_infer = VariableElimination(model)

print('\n 1. Probability of HeartDisease given Age=28')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
print(q['heartdisease'])

print('\n 2. Probability of HeartDisease given cholesterol=100')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'chol':100})
print(q['heartdisease'])

the error that i have recieved when i run my Bayesian network program is:
TypeError                                 Traceback (most recent call last)
<ipython-input-7-84a6b48627b2> in <module>
     23 print('\n 1. Probability of HeartDisease given Age=28')
     24 q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
---> 25 print(q['heartdisease'])
     26
     27 print('\n 2. Probability of HeartDisease given cholesterol=100')

TypeError: 'DiscreteFactor' object is not subscriptable

So far I haven't seen this exact error here on stackoverflow. Can anyone explain why I am getting this error?

A: After trying to solve the error I came up with the solution.
print('\n 1. Probability of HeartDisease given Age=28')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
print(q['heartdisease'])

print(q['heartdisesase']

over in this part of the code snippet I just removed ['heartdisease'].
here the output was actually trying to store itself into a array object, however the output actually is in special table format that cant be stored into an array so printing the actual answer 'q' gives you a required result.
print(q)

this get's your job done..!!

A: The API you are using to fetch the data might be old . You should get back to the old API by simply passing joint=False as an another argument on line number 24. As in
24 q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28},joint=False)
25 print(q['heartdisease'])
print(prob_offer['Offer'])