How can privacy be maintained when AI humanoid personal robots become commonplace?

Question: What prevents someone from owning a lookalike humanoid robot of someone else? Can't that raise questions about privacy and ethics when say a certain humanoid robot looks and probably behaves like someone near and dear to someone else?
Comment: While it would be possible to create a robot to look like someone else, getting it to behave like someone else is a different matter - people are by nature unpredictable, so how would you have a robot behaving like a specific person? If this were to be possible somehow, then you could just replace that person with their respective robot, without anyone else knowing, which raises lots of potential problems that are probably more important than privacy
Comment: @GrinningX I dont think that's true at all. We have always had an intuitive notion of privacy, at least as far as recorded history. And the way we define interaction in  public spaces , architecture and the way we interact in familial life, takes into account these notions of privacy.
Comment: The topic and the question asked do not line up. Humanoid robots and privacy have nothing to do with each other. It does however raise ethical questions which are best asked in philosophy SE. There are also rights to one's image that would be raised, but that's theoretical a law question that would probably best be asked in the Law SE and not what you're asking. Please edit and clarify and/or ask in those other SEs.
Comment: "Privacy" is an entirely modern construct in human existence.  I am not sure if it can be maintained, but because we made it pretty much all this way without it I'm sure we can still go quite a distance if we lose our current definition of it.
Comment: How can privacy be maintained now, with smartphones everywhere? **It already can not and nobody cares**. But your questions seems to be about identity theft, not privacy. Or some specific threat to "privacy" (as if it really existed). Please make it clear which aspect you have in mind.
Comment: Well, you have little assurance of privacy in a public place any more. But I think most people have an expectation of privacy when they're alone in their homes, for example. Yes, the technology exists to, say, plant a miniature camera in someone's house. But then people in ancient times could hide outside your window and eavesdrop. It's a difference in degree, not really in kind.
Comment: @Jay modern voice controlled, Internet connected TV sets can and will send anything you say to manufacturer's server, or to Google. It's in their user manual to never say anything private in the room you are putting them. And people put them in their living rooms, bedrooms... Mamy people do not want to have privacy, do not care, or can't read enough to know what they're doing.
Comment: This is why robo-ethics is important!
Comment: @molot I don't doubt many people are careless about protecting their privacy. But I suspect most would still be angry if personal conversations, nude photos, etc were made public. Just like, many people don't lock their doors, but that doesn't mean they wouldn't care if a thief broke in and robbed them. It just means they're careless. btw I don't have a voice-controlled TV, but why would it send everything you say to central server? Wouldn't it make more sense to process it locally?
Comment: @Jay no, it wouldn't. Voice recognition is computationally expensive, and by sending to the central server company gets free samples for their AIs to learn from.
Comment: @molot Hmm, but by sending to the central server, the server has to process the input from all customers, presumably millions of customers if this is a successful product, versus having a cheap CPU at each customer's home that just has to process data for one customer. Plus you have the delays to send messages back and forth. Plus the bandwidth to send raw voice files. I'm a software developer. If I was developing such a system, my first thought would be distributed processing. "get free samples" I suppose, but I don't you'd study millions of hours of data. You want a few hundred hours, maybe.
Comment: @Jay you may be right. On the same time, [Samsung appeared to do it the way I described](https://www.cnet.com/news/samsungs-warning-our-smart-tvs-record-your-living-room-chatter/), other manufacturers wasn't really different. True, since then Sam added icon to indicate TV is recording, but it was sh*tstorm by few journalists, not general public demand.
Comment: @molot I'm not saying that you're lying! Just that it seems funny. I wonder if there's more to the story.
Comment: @user2277550 - To a point, yes.  However, consider that for much of human history we did not live in the 'burbs.  People lived very close together in 1-2 room homes, often with friends and extended family, and the houses were much closer together.  Windows didn't exist for most either, so you would see and hear pretty much all of your neighbors business.  You tended to know how much people were paid and what they bought as well.  People were much more social with their neighbors as well, creating another source of knowledge.  We live in starkly different times from a privacy perspective.
Answer: Note you have not one but two assumptions here: (a) that the technology exists to build AI humanoid robots, and (b) that the technology exists to build a 3D facsimile of a human being good enough to fool people who know him. Well, maybe also (c) that you can combine these two things.
Clearly (a) without (b) does not create any privacy issues like you're discussing.
(b) without (a) creates most of the same issues you describe. If the art of make-up and/or plastic surgery and/or prosthetics advanced to the point where one human being could be made to look enough like another to fool people, you'd have the same issues that you describe.
This isn't a totally new problem. People have been impersonating other people since the dawn of recorded history. But presumably a robot built to look exactly like the subject person could at least theoretically be better than any attempt to disguise one person to look like another.
All of which is my way of leading up to ... is the premise of the question that we are assuming that this AI robot can successfully impersonate a person so well that even his family and friends can't tell the difference? Or is that part of the question?
If we just take it as the premise that it can be done, then sure, what stops someone from creating such a robot and having him go to your home or office and examine all your most secret things, read your personal papers, etc? At that point I think I'd be worried about a lot of things besides privacy. Like what if this robot steals my stuff? Signs contracts or otherwise makes commitments in my name? Commits crimes that I then get arrested for? Starts arguments with my friends who think he is me and now they hate me for life? Makes love to my wife? Or what if the creator kills me and replaces me with this robot? If the assumption is that the robot can indeed fool everyone, then the only defense is to have laws against it and punishments severe enough to deter people from trying it. But of course there would always be criminals who would ignore the law, and some number would get away with it.
But I find the premise hard to believe.
No matter how good a duplicate these robots are, surely a plot to impersonate or replace someone could be easily foiled by having passwords. If people knew the technology existed, then the fact that someone looks exactly like so-and-so would not be considered definitive. The bank wouldn't hand over money to someone based on recognizing his face, spies wouldn't reveal secrets, your boss wouldn't accept a resignation, your friends would question uncharacteristic behavior, etc. Looking exactly like Fred Smith would prove about as much has having a sticker on your shirt that says "Hello my name is Fred Smith". You'd have to identify yourself in some way that is not easily duplicated. Like a password. Unless the people who make the robots can not only make an exact duplicate of a person's physical appearance but also read his mind to learn his passwords, that would be an excellent defense.
Beyond that, how good are the duplicates? For example, are the robots made of flesh and blood, or are they electronic and mechanical? If the latter, then if someone is suspicious he could demand a blood sample or take an x-ray.
People could ask the robot things that only the real person would know. Like, "What did you say to me when we spoke last Thursday night?" Again, unless the people who make the robots can read minds, there would be all sorts of things that the real person would know that the robot wouldn't.
I think that if someone is suspicious, they could think of any number of ways to tell that this is an impostor robot. If the real person is someone that many people would have a reason to want to impersonate -- if he's a big shot politician or a billionaire or a spy with vital information -- then if people knew this technology existed, presumably they'd make it a routine practice to check. Just like, even without this sort of technology, you don't just walk onto a military base or into a bank vault or even into many business offices. You're expected to have an ID or some sort of proof of your identity that is at least somewhat difficult to forge. The more damage you could do by gaining unauthorized access, the more effort is put into keeping out impostors.
Perhaps you could get away with it if you can avoid making people suspicious. Like if someone walked into my office tomorrow who looked exactly like one of my co-workers, what would it take for me to suspect he was an impostor, even if I knew the technology to make look-alike robots existed? If I tried to talk to him about something we had discussed the previous day, could he bluff his way through the conversation? If he just said that he forgot what we had talked about, I'd probably buy that once, but if he "forgot" everything we've said to each other for the past month, I think that would arouse suspicion. If he said he lost the key to the front door, okay, people lose things. But if he lost the key to the front door, and he lost his ID card, and he forgot his password on the computer network, etc, at some point you'd start to get suspicious.
Even if we assume that AI's can pass for intelligent human beings -- which is a big assumption, we're nowhere near such technology today and one could fairly question if it's possible -- but even if we assume an AI can pass for an intelligent human in general, could it pass for a PARTICULAR person? Could it duplicate all his mannerisms, his style of speech, know everything he knows and not let slip that it knows things he doesn't know, etc? How would the creator of the robot impostor get all this information? They'd have to follow someone around for weeks or months recording everything he said and did. Could they do that with no one noticing?
One could imagine that the technology exists, but is used fairly rarely so that people do not normally consider the possibility. Like, when I go to the bank, they make me show my drivers license before they'll give me money. Does the technology exist to forge a drivers license? Of course. But it's rare enough for people to do it that the bank doesn't worry much about it. If these AI robot impostors existed but it cost a million dollars to build one, no one is going to build one to impersonate me and go to the bank and withdraw the thousand dollars or so I may have there. They might build one to impersonate Bill Gates and go to his bank. The real vulnerability would be people who are worth going to the trouble to build an expensive robot impersonator but who no one really thinks about as being worth the trouble. Someone is a friend of the big-shot general but not really powerful himself, but by impersonating him you can get into the general's office and steal military secrets, that sort of thing.
Whew, long answer. Interesting subject, I guess.
Answer: From the Digital Media Law Project:
"In most states, you can be sued for using someone else's name, likeness, or other personal attributes without permission for an exploitative purpose. Usually, people run into trouble in this area when they use someone's name or photograph in a commercial setting, such as in advertising or other promotional activities."
http://www.dmlp.org/legal-guide/using-name-or-likeness-another
I think a lookalike robot would fall into this area. At the very least, our current laws would provide some precedent to argue this point when such issues come up in the not-too-distant future.
Comment: A person's appearance can certainly be trademarked. Doesn't the Marilyn Monroe estate still make MILLIONS selling her likeness? Whoops, looks like it expired. Time to get my MM sex doll! :P http://photosecrets.com/marilyn-monroe-loses-publicity-rights
Answer: It all depends on the context of your world. A world I'm building will feature a heavy taboo on AI within human society as the first time AI was created, it spiralled out of control and - in short - caused an apocalypse that left the entire species reeling and barely able to believe that it survived.
The species has recovered since then, and not reverted into barbarism a la mad max; tech levels only dipped slightly and have continued to increase afterwards. It's just that machine intelligence, emotional computing, computer vision and all such topics are considered very seriously before any sort of work is done on them, if at all.
The kind of robots you are proposing, that not only mimic humans in appearance, but also in behaviour to such a degree that someone near and dear to the original human would be fooled would be inconceivable in this setting - unless it was an artefact created before/during the apocalypse, in which case, yes, that's a very big problem (but relatively benign compared to other artefacts from this era).


non homology based polynomial time computable invariants

Question: I am wondering if there are polynomial time computable invariants of topological spaces (say, finite simplicial complexes, or finite CW complexes with computable attaching maps to be a bit more general) which are somehow fundamentally different from homology? Certainly cohomology admits a ring structure, but this is really just more structure on a homology group. Is there something "in between" say homotopy groups and homology based structures?
Comment: Invariants of what? you did not say!
Comment: I meant of spaces. Say finite simplicial complexes.
Answer: There are several questions you ask, and I think I can say something about the last question.
It is worth thinking about the origins of homology, see for example essays in IM James (editor) "History of Topology". The early writers on what we now call algebraic topology wanted to take "cycles modulo boundaries" but were not too clear about the meanings of those words.  It was Poincar\'e who brought in the idea of "formal sums" of oriented simplices,  and so the famous equation $\partial \partial=0$, defined on what we now call a free abelian group. The work of E Noether led to the abelian group theoretic formulation of homology we know today.
The topologists of the early 20th century, such as Dehn,  were well aware,   particularly by the 1920s, that for a connected space $X$ the first homology $H_1 X$ was $\pi_1(X,x)$ made abelian, and that the nonabelian nature of the fundamental group was important in applications in geometry and analysis. So they looked for higher dimensional versions of the fundamental group.
In 1932, E. Cech submitted a paper on higher homotopy groups to the ICM at Zurich, but Alexandroff and Hopf persuaded Cech to withdraw his paper on the grounds of their abelian nature (it is not clear if this was known by Cech or was proved by Alexandroff and Hopf). Later, worries about the abelian nature of the homotopy groups would be seen as a quirk of history.
However work was done on the generally nonabelian second relative homotopy groups $\pi_2(X,A,a)$ by JHC Whitehead, who introduced in 1946 the notion of crossed module, and in 1949 the notion of free crossed module.  This allows one to say that for the standard diagram of a Klein bottle, we can write $\delta \sigma = a+b-a +b$, with values in the  free group on generators $a,b$.  He pursued  these ideas in his 1949 paper "Combinatorial Homotopy II".
Now the reason for the abelian nature of the higher homotopy groups can be put as  that group objects in the category of groups are just abelian groups.
There are arguments for phrasing the theory of the fundamental group in terms of groupoids. It then turns out that group objects in the category of groupoids, or groupoid objects in the category of groups, are equivalent to crossed modules, see this 1976 paper.
This was part of a search for Higher van Kampen Theorems started about 1965, whose results are described in this 2011 book Nonabelian algebraic topology and this 1992 expository article, which deals also with some algebraic models, cat$^n$-groups,  of homotopy $(n+1)$-types, and calculations involving these. Note that the book does not require the development of singular homology, even for a statement and proof of a Relative Hurewicz Theorem!
What may be seen as a catch is that the strict higher homotopy groupoids used are defined for filtered spaces and $n$-cubes of spaces, not directly for spaces. (The original question does not say of what we should have invariants!) My own view, influenced by spending 9 years on trying and failing to define a homotopy double groupoid of a space,  is that the emphasis on theories for spaces without additional structure is likely to be a mistake: this is kind of confirmed by remarks of Grothendieck in Section 5 of his 1984 "Esquisse d'un Programme". (See my comment below for a link to this work.)
Just to develop the last point, the usual method in singular homology is to define singular homology of a space and then after a lot of palaver to get the cellular chain complex of a CW-complex, based on its filtration by skeleta. Instead, one can define homotopically invariants of any filtered space, and then one needs quite a lot of work to show how to calculate them for a CW-filtration, but in the process gets more information since we deal with nonabelian structures in dimension 2 and keep the operations of the fundamental groupoid.
As regards  computation, this is always a question in dealing with nonabelian methods; but the above  cited book has many calculations involving crossed modules, and so second relative homotopy groups, while one spinoff from the work on cat$^2$-groups, a nonabelian tensor product of groups, has had lots of work mainly by group theorists, see this bibliography, with 130 items.
What does seem to be lacking in this work is the vision of the workers of the early 20th century, namely the applications of these particular nonabelian methods in geometry and analysis!
I have attempted to indicate some work "between homotopy and homology"; it seems to me to deserve this appellation, because it involves homotopically defined functors, and honest (partial) compositions of mappings defined by using gluings of cubes, not the "trick" of using free abelian groups.
I am not sure if this  answers your question.
Comment: If you have the remarks of Grothendieck you mention at hand, could you edit them in? :-)
Comment: @Mariano: Thanks for the question, as a web search has just shown me an English translation at http://matematicas.unex.es/~navarro/res/esquisseeng.pdf
Comment: Hi, thanks for the exposition I'm very interested in polynomial time computable invariants though. Can you comment?
Comment: @rhl: Do you regard the fundamental groupoid $\pi_1(K,K^0)$ of a simplicial complex $K$ as a polynomial time computable invariant? If not, then you might have to restrict invariants nearer to homotopy to those for which their fundamental groupoids are of that type. But this is just a guess.
Comment: Or restrict the applications to those $K$ for which the fundamental groupoid has this property, of which there may also be higher dimensional versions.


Does fair use supersede the permission of copyright holders?

Question: Fair use seems inherently contradictory. I need help understanding the exact context. According to copyright, you need permission to use intellectual property but fair use says you don't need permission as long as you use the work under specific circumstances. Hypothetically, if a copyright terms explicitly stated it cannot be used by others and at the same time someone used this specific copyrighted content without permission in a context that matches the criteria of fair use, would the doctrine of fair use supersede the copyright?
Comment: The terms stated on a site or a license can't take away a right that you already have by law. See: [How is internet archiving legal, when it appears to violate many websites terms of use?](https://law.stackexchange.com/questions/27407/how-is-internet-archiving-legal-when-it-appears-to-violate-many-websites-terms)
Comment: Copyright terms cannot control the use of something, only its reproduction, so you couldn't use copyright to prohibit e.g. the use of a recipe in the sense of stopping someone cooking that thing. Controlling use would depend on licensing, which is a whole other area of law.
Answer: Almost all works recorded in some fixed way that are not a couple of hundred years old or created by a government agency are protected by copyright.
In the absence of an exception to the general rule, copying a work that is protected by copyright is copyright infringement, which can be a basis for the copyright owner to sue the infringer. This can also be a basis for criminal liability is certain additional elements are proved and a prosecutor proves a case of copyright infringement in a criminal case.
But, there are some important exceptions to this general rule of what constitutes legally sanctionable copyright infringement.
The most important exceptions to the general rule have the character of affirmative defenses. In order words, if someone sued for copyright infringement and the person sued admits that they copied the copyright protected work, they can use these exceptions to avoid having legal liability.
One of the exceptions is the permission from the copyright owner to use the copyright work. This can be either in the form of affirmatively given permission to use the copyrighted work in a particular way (called an "express license" to use the copyrighted work), or in the form of permission to use the copyrighted work that can be inferred from context (called an "implied license" to use the copyrighted work).
Another of the main exceptions is "fair use". If the way a copy of a copyrighted work is used constitutes fair use, the person using the copyrighted work without an express or implied license to do so it not liable for copyright infringement.
Of course, while you don't need more than one exception to the general rule to avoid liability for copyright infringement, you can have more than one.
For example, you can use copyrighted work in a way that would constitute "fair use" and not give rise to liability for that reason if you were sued, even if you can't be sued anyway because you already have been given permission by the owner of the copyright to use the copyright in the way that you did.
It isn't a case of a contradiction. It is a case of a general rule that has exceptions.
Answer: Yes, fair use supersedes the requirement of permission from the copyright holder.
In general, the holder has the exclusive right to copy the work, publicly perform it, create derivative works, and so on.
If you copy the work without permission or otherwise infringe the holder's exclusive rights, you will generally have committed a copyright violation, but 17 U.S.C. § 107 explicitly excepts fair use from the definition of an infringement:

The fair use of a copyrighted work ... is not an infringement of copyright.

Therefore, you generally have no duty to obtain permission from the copyright holder to make fair use of a work, no matter what restrictions the holder has placed on it.
Comment: Although the holder and the person who copies may well have different views of how 'fair' the use was, so the copier may well still get sued (and may win, or may not).


Looking for a compound

Question: TL;DR;
I need a compound that is harmeless to the human body, odorless, tasteless, causes some kind of visible reaction (urine coloration perhaps) AND can be bought without medical recomendation.
LONG VERSION;
Food stealing in my company fridge has become a serious problem. It's not only a recurring issue but a targeted one... our thief has been targeting "high" value, particularly coconut water. HR seems to ignore our complains... so I decided to take matters in my own hands... since I have access to timesheets, I thought that if I can scare out thief to leave work or skip it, I can narrow-it-down/point-him-out because we have about 30 people in our office...
Answer: Urine typically is yellow, but in combination with blue dyes, a green colour can be obtained.
Noteworthy compounds are methylene blue, thymol, Cimetidine (antacid), or Mitoxanthrone (used in cancer therapy).
I've mentioned these just for the sake of completeness - I think it is irresponsible and stupid to spike food with anything that doesn't belong there.
Hiding a webcam in a shelf and running zoneminder probably isn't legal either and will get you in trouble with the privacy officer, but at least that doesn't mess around with the health of anybody else.
Comment: You could use asparagus extract. That would attract your nose's attention.
Comment: for the sake of completeness I do intend to label my coconut water bottle with a big "DO NOT EAT. SCIENCE EXPERIMENT UNDER DEVELOPMENT" label... wich i'm sure the little thief will ignore...

Looking for a compound


Why put the bits of a port on non-adjacent pins?

Question: Some micros have all bits of a port nicely lined up, while others' bits seem to have been scattered by the winds to all four points of the compass. Why?
Comment: I am thinking about the interesting and cheaptastic LPC1* ARM chips. They only put 3 or 4 bits max per port in a row.
Answer: I occasionally do chip design - as mentioned above many chips will intersperse power and grounds within parallel buses so that the drivers will have enough power (lead inductance is an issue - plus you don't want to starve the core when driving external loads).
However there are other issues - you might be constrained for on-die routing resources meaning it makes more sense to push those issues externally - I worked on a PCI interface where we tried hard to push pins to the right places (total system cost means getting to a 4 layer board can be important) but were constrained in some critical timing paths that meant we had to push some of the timing budget off-chip by moving the pads closer to the rest of the logic they drove while assuming longer external traces
Sometimes you design a die but it goes into multiple packages - maybe the BGA package is optimally pinned out but not the QFP - or maybe the package was chosen late in the design cycle after the pads on the die were already chosen
So there's lots of reasons - sometimes it really is that the chip designer didn't think ahead
But remember for some buses you don't always have to wire up all pins exactly - if you're wiring up a SRAM/DRAM (or sometimes even flash if it's not being pre-loaded) you can often switch bits within a byte or even (carefully! depends on the chip) address bits
Answer: Often this has alot to do with lead inductance. You need to keep your grounds spread out, and based on layout decisions in the chip internal to the package it may need to spread out the I/O pins.
Would you rather have ground problems or spread out pins. In general, I use #define to handle which pin I am using and all but forget which actual pin it is. Since most people do this also, chip manufacturers know this and focus on electrical parameters.
Comment: I don't think the question was referring to having a few grounds.  It read *scattered by the winds to all four points of the compass*.  Also, while programmers don't have to worry about it after they import the header, I think that the bigger problem would be in the layout of the PCB.
Comment: The fact that you have to spread apart your grounds has an effect on the placement of all pins. There is also a lot to do with how the chip was designed at the gate level. When you look at chip designs like this http://vega.unitbv.ro/~nicula/vlsi/layout.html you might be able to begin to see how it could be hard to put pins in order by their port
Comment: @reemrevnivek, Yes, I understand that they are scattered, but why does that affect your layout. There should be Digital I/O almost everywhere. If you have a D- and a D+ for USB on a chip they are normally close for impedance reasons. But if it is general I/O you should know you can swap one Digital I/O to almost any other Digital I/O. decent layout/schematic suites allow you to mark pins as swappable. That way the layout runs smoothly.
Answer: Might have something to do with the alternate uses for a pin.  If you have an oscillator connection then it would be a good idea to have it kept away from high-noise paths for instance.


Trello Online indicators are gone

Question: We're not seeing online indicators in Trello anymore and I can't find mention of this anywhere as an official change.  Is anyone else noticing this? Is this a known change I just haven't found mention of?
Comment: They're back again. So they worked hard and fixed it I guess
Answer: The team has temporarily disabled after experiencing some technical issues. They will be back in the future, but it's not known when.
Comment: Any update on when this could be back? For distributed teams this was a really nice feature.
Comment: @Ostemar We are working on a smarter "presence" service for online status. We don't have a time estimate for when they'll be back, though.

Trello Online indicators are gone


Virtual UART ports

Question: I want to use a Rpi to interface with 3 atmega ics in an embedded system but the pi seems to only have one uart port. I know arduino can emulate a serial connection over two io pins, will this be possible on a pi? I plan on using a headless raspbian setup with a mono c# terminal application.
Answer: What you are referring to is called Software Serial, where bytes are bit banged and create the same effect as a serial port.
Using a normal Linux distribution the answer is, No.  The reason is because bit banging required real time processing of data, otherwise the data will just be junk.
This answer at Electronics Stack shows a USB board with 4 hardware serial ports on it. Its not cheap but it will great.
You can use a multiplexer which is a cheap way to get 4 serial ports but you cannot use all 4 at the same time. You can switch between ports on demand.
You can buy a SC16IS752 that  uses I2C - Which means you can add a few of these with real time data flow. It is more complicated since you have to build everything around it your self.

You also buy cheap USB to UART - a USB Hub and add as many as you like
Comment: Ok, is there any way to enable the second serial port on the RPi so that I can at least interface with two atmegas? Otherwise I will probably have to use i2c.
Comment: There is a second one but its not connected to anything... go figure. So i'm afraid the answer is No.
Answer: You need to use RS485 for connecting instead of RS232. Then you can have single master (RPi) polling multiple slaves (AVRs) one after another in a loop. For this you can use MODBUS or some other similar communication protocol.
Comment: There are RS232<>RS485 convertors, both as ready made devices and as microchips you might want to embed. After that, from developer side you do everything the same as you did with RS232. RPi polls AVRs one by one and sends data requests. Each data request message includes slave address. Once AVR gets the message, it looks into address and decides wether it should answer it or pass it.
Comment: I will look into it but I am not sure how far this functionality has been implement for the pi yet, especially in terms of c#

Virtual UART ports


Insert Animated GIF into Powerpoint 2013?

Question: As per title, I am looking for a way to embed animated GIF files within my powerpoint presentation.  I was hoping for this to be native functionality but either inserting as image or as video does not appear to work.
Answer: You can add any animated *.gif by just drag and drop from explorer window, or in the ribbon UI click Insert - Pictures and navigate to your gif image, and click Insert. Press F5 to begin the slideshow. Make sure your GIF file is animating by opening it with Internet Explorer, because static GIFs never animate.

Here's the MS Powerpoint 2013 demonstration:
Comment: Love the way you reply with an animated gif; +1
Comment: Do you know a way to keep the GIF also playing when you format it with some style effects (like a border)? in office 2007 it worked, but I could not identify a way for 2013 so far
Comment: @ClickOk It's LiceCap. [http://www.softpedia.com/get/Multimedia/Graphic/Graphic-Capture/LICEcap.shtml](http://www.softpedia.com/get/Multimedia/Graphic/Graphic-Capture/LICEcap.shtml)
Comment: Hey Isaac, awesome reply! What the software you use to produce this animated gif?
Comment: What about .PNG?


How do I find non-exported symbols of a binary?

Question: You can use nm(liux/mac) to find exported and imported functions/symbols, is it possible to find the non-exported symbols of a binary in a similar way? Are there command line tools to assist with this?
Primarily looking to do .apk/.ipa analysis.
Comment: Is this for a binary you built yourself from source code? Or is this for a binary someone else built? If the latter, who was the developer and what is the binary? (Some developers like Microsoft make public symbols available for some of their binaries).
Comment: This is for pre-built binaries, or sometimes library .so files. The binaries are from various developers for android/iOS.
Answer: You would need to ask the developers of those Android / iOS apps for the symbols. It's very unlikely that they've made their apps' symbols publicly available.
However, keep in mind that although symbols are helpful, they aren't required to reverse engineer an app.


Navigate with keyboard in Gallery shortcode

Question: I am using Wordpress Gallery shortcode and I was wondering if there is a way to navigate using the arrow keys? Like if I view an single image and used the right arrow to navigate to the next image in the gallery set. Any idea how to do this?
Comment: You could use javascript.
Comment: Plugin recommendation is off-topic now... & there are plenty of *Imagebox* plugins in the [Repository](http://wordpress.org/extend/plugins/tags/lightbox), surely one or more will have this feature.
Comment: I'm not a programmer so I would prefer if there's a plugin
Answer: The Underscores (_s) starter theme comes with a keyboard navigation script for this. I haven't tested this myself though. But the JS file looks like this:
jQuery( document ).ready( function( $ ) {
    $( document ).keydown( function( e ) {
        var url = false;
        if ( e.which == 37 ) {  // Left arrow key code
            url = $( '.previous-image a' ).attr( 'href' );
        }
        else if ( e.which == 39 ) {  // Right arrow key code
            url = $( '.entry-attachment a' ).attr( 'href' );
        }
        if ( url && ( !$( 'textarea, input' ).is( ':focus' ) ) ) {
            window.location = url;
        }
    } );
} );

It also needs some modifications to your attachment theme file to make the links work correctly. My suggestion is that you download the _s theme and take a look in the image.php file.
Basically what you need on the attachment page is a link to the next/prev image inside an element with the class "previous-image" / "entry-attachment".
Answer: I am using standard WP galleries and have each image link to an attachment page where the image is displayed fullsize. To show PREVIOUS and NEXT links in order for the user to get to the corresponding images I found the functions previous_image_link and next_image_link useful.
In my attachment.php I have the following lines to make WordPress display previous/next links:

                    <?php previous_image_link( false, '
' . __( '<< Previous Image', '$text_domain' ) . '
' ); ?>
                    <?php next_image_link( false, '
' . __( 'Next image >>', '$text_domain' ) . '
' ); ?>

This results in markup that might look like:

<< Previous Image

Next image >>

My client wanted to be able to use his keyboard to switch back and forth between the images of any gallery, so I added jzatt's jQuery script and edited it to my footer.php that listens for the KEYDOWN event and, if triggered, grabs the links WP provided and changes the URL of the page.
This is the jQuery script:

What I need to add, though, is an IF statement to first check whether the user is indeed on an attachment page.
Comment: If the user is on an attachment page then there will be a class on the body tag to show that, so you could just update your jQuery selector accordingly and your code will then only apply in the right context.

To make sure dependencies load in the right order, consider adding your code using `wp_enqueue_script` instead.  Then you can also add a conditional using `is_attachment` and so only load your script on attachment pages.


Powering ATtiny85 for temperature sensing

Question: I have been working on a miniature temperature sensing module which buzzes once the temperature crosses a threshold using ATtiny85, lm35 and a pico buzzer. When I power the whole circuit using an arduino board and take readings of the temperature sensor, they are consistent. But when I try to take the readings after powering the whole thing using 2xcr2016 3V coin cells, the readings are erratic. How do I solve this issue?
Comment: What does your decoupling look like?
Comment: How fast are you clocking the ATtiny85? If you are clocking it faster than is allowed for a 3 volt supply the micro could behave irregularly
Comment: Also, why aren't you using the internal temperature sensor?
Comment: Are you connecting the coin cells directly, for 3V or 6V? Do you have anything between the batteries and the uC, like a voltage regulator or decoupling caps?
Answer: Coin cells have ultra high series resistance - any loads greater than 10mA or even less will make them sag significantly. They are intended to power ultra-low power circuits like Real Time Clocks, watchdogs, battery monitoring, and keep volatile memory intact during power failures.
The AT tiny when running at significant clock speeds will be sapping up to or more than 10mA, plus the sensors and other circuitry will be causing havoc to your little coin cells. They will be sagging a lot during sampling periods, and may cause brownouts on your AT Tiny.
Get a better power source, add many more capacitors (low and high values to cover all bases), and use an oscilloscope on the VCC rail to see visibly how it sags, and then you will understand.
If you ran the AT Tiny at 32kHz or a few hundred kHz at most, it may work at a low enough power level to use the coin cells. It will just be slow.
Comment: The ADC is inoperable at so low a speed unfortunately.
Comment: @IgnacioVazquez-Abrams perhaps the OP can use an external ultra-low-power accumulation style ADC instead, to interface with his AT Tiny if the onboard ADC is too high-power/clock requirement
Comment: Okay so here's what I did. I used 3xcr2016 and regulated the output via a 7805 5v regulator. Works like a charm. And yes I'll not be keeping the circuit on forever. I'm using a watchdog timer to wake every 5 seconds to check the ambient temperature.
Comment: @SiddharthShah interesting - I suggest you try 3 cells in parallel and use a boost regulator -this gives you 3 times less resistance and allows for more current - and the boost regulator should be about 80%+ efficient, meaning you can get better life span than using a 9V -> 5V linear converter circuit.


Looking for a Isekai Manga that is the MC has weak mana but very proficient to water magic

Question: The isekai that I'm looking for is an adventurer kid that is strong with water body around him but weak without. He can make mist,ice and heat(boil water inside an enemy) using magic.
Comment: Hi, welcome to SF&F.  Where and when did you read this?  Do you remember any details of the art?
Answer: This is likely Clearing an Isekai with the Zero-Believers Goddess.

After his class gets buried alive on their way back from a school trip, 18 year old Makoto Takatsuki and class get transported to another world. Unlike the rest of his classmates who gained powerful abilities, Makoto barely gains any power. "This other world is unbalanced!". With the threat of a great Demon Lord rising again and a goddess with zero followers, can Makoto make his way through this new world and clear the isekai!

The main character has extremely low magic power but also extremely high magic control. He has an affinity towards water magic, and is very strong when in/around bodies of water, but can only create small amounts of water otherwise. He is forced to use clever applications of his limited water, including:

Fog generation for stealth
Ice bullets, aimed for the eyes
Stabbing with a dagger and freezing the target's blood
Creating a slick ice floor

He does not boil off blood, but freezing the blood is basically the same idea.


Are there sequence $(u_n)\subset \mathbb R^+$ s.t. $\sum_{n=1}^\infty u_n<\infty $ but $nu_n\not\to 0$?

Question: I have an exercise that ask me to prove that if $(u_n)$ is decreasing, $u_n\geq 0$ for all $n$ and $\sum_{n=1}^\infty u_n$ converge, then $nu_n\to 0$. I proved it, but for me this result in fact correct even if we remove $(u_n)$ decreasing. Because I have in mind that $1/n$ is the quickest speed of non convergence, i.e. if $\sum_{n}v_n$ converge, it will have $\alpha $ s.t. $v_n\leq \frac{1}{n^\alpha }<\frac{1}{n}$ for all $n$ for a certain $n$. But if we impose $u_n$ decreasing, maybe my imagination is wrong. So is there a positive sequence s.t. $\sum_{n=1}^\infty u_n$ converge but $nu_n\not\to 0$ ?
Comment: Do you mean $1/n$ is the *slowest* speed of non-convergence?
Comment: @packetpacket I think maybe he is referring to $n$, i.e. if $n$ would grow any faster then the series would converge. Some people think of the series about how fast the denominator is growing, but do not explicitly state that.
Answer: To answer the question in your title. For each positive integer $t$ set $u_{t^2} = \frac{1}{t^2}$. And for all nonsquare positive integers $n$ set $u_n = \frac{1}{n^3}$. Then

On the one hand $\sum_{j=1}^{\infty} u_j$ converges (as $\sum_{t=1}^{\infty} \frac{1}{t^2}$ converges as does $\sum_{n=1}^{\infty} \frac{1}{n^3}$).
On the other hand, $t^2u_{t^2} = 1$ for all positive integers $t$ so $nu_n$ does not converge to 0 as $n$ goes to infinity. i.e., No matter how large $n$ is, there is a positive integer $n'$ s.t. $n'u_{n'} =1$, namely $n'$ is any perfect square larger than $n$.

The $u_n$s are not nonincreasing though.
Answer: You can prove that if $a_n$ is decreasing and $na_n\not\to 0$, then $\sum a_n$ diverges.
Proof: If $na_n\not\to0$, then there is an $\epsilon>0$ and infinitely many indices $n(1)<n(2)<\dots$ for which $a_{n(i)}\ge \epsilon/n(i)$. Since $a_n$ is decreasing, we can group terms based on which of the intervals $[1,n(1)),[n(1),n(2)),\dots$ they lie in, and you get
$$
\sum_n a_n \ge \sum_i (n(i+1)-n(i))\cdot \frac{\epsilon}{n(i)}\stackrel{*}=-\sum_i n(i+1)\Big(\frac{\epsilon}{n(i+1)}-\frac{\epsilon}{n(i)}\Big)=\epsilon \Big(\sum_i \frac{n(i+1)}{n(i)}-1\Big)\tag{1}
$$
where $\stackrel{*}=$ follows by summation by parts (check this!).
Now, let $r(i) = \frac{n(i+1)}{n(i)}$, with the convention $r(0)=n(1)$. It is a fairly standard result that
$$
\sum_i r(i)-1<\infty \iff \prod_i r(i)<\infty
$$
which follows from $\log x\sim x-1$ as $x\to1$. However, since $\prod_{i=0}^k r(i)=n(k+1)\to\infty$, we must have that the  final sum in $(1)$ diverges.


What is SNM(Static Noise Margin) in SRAM?

Question: I have read multiple papers and articles about it but still, I am not able to understand fully. If you can explain me in layman terms I would be much happy. Thanks.
Answer: SNM can tell you a bit about the tolerance an SRAM cell has to noise before it risks loosing the 'memorized' bit.
SNM is a very simple measure with just one number, so it doesn't really tell you what kind of dynamic noise might flip the bit. But, since it's just one number it's easy to compare values and get a feel for when your SNM might land you in trouble.
There are actually three different SNM depending on what is being done with the SRAM cell:

SNM_hold for hold (no operation)
SNM_read for read operation
SNM_write for write operation

To find SNM_hold you consider two back-to-back inverters. If you draw both of their Vout(Vin) DC characteristic but swap the X/Y axes for the second, then you can find SNM graphically as the diagonal of the largest square that fits within the back-to-back DC characteristics. If the two inverters are not symmetric you must choose the smaller of the two possible squares for the SNM (one on each side of the cross-over point).
To find SNM by simulation you sweep a static noise voltage (DC source) one at each of the gate inputs as shown below. This paper (Seevinck et al. "Static-noise margin analysis of MOS SRAM cells" https://ieeexplore.ieee.org/document/1052809/ ) explains how you can get the largest diagonal using dependent sources.

simulate this circuit – Schematic created using CircuitLab
SNM_read and SNM_write are found same as SNM_hold except that you now load Vi and Vo with the transistors that are connected to the bitline. (You could include the access transistor leakage for SNM_hold but it's rarely relevant).
Answer: An SRAM is a very busy integrated circuit, with lots of surge currents flowing during the Read Cycle. There is magnetic field coupling, electric field coupling, and ground and VDD upsets. These totaled, degrade and reduce the static noise margin.
The read-comparator (perhaps sensing differential read lines) needs an accurate determination of what was the bit-cell (4T or 6T or 8T) state.
The coupling and upsets I mentioned are the causes of reduced confidence in that actual cell state.
Comment: Sorry I am not aware of those.
Comment: So what should be an ideal value of SNM in 6T transistor for 1V VDD. What happens when it is low and high? What can I do to my cell to have a good SNM value. Thanks.
Comment: Do you have the math and physics to compute magnetic coupling? electric coupling? and I*R voltages in VDD and GND rails?


How to remove mirror stickers from a painted wall?

Question: Can you tell me the easiest way to remove adhesive mirrors from a painted wall? The mirrors are made of a thin plastic material and the adhesive is completely covering the back, it is not double-sided foam. Thank you! The first attempt took me down to the drywall.
Answer: Sounds like you're dealing with a pressure sensitive vinyl. It's not going to go down with out a fight. The best course of action is to hit it with a heat gun and very slowly pull with light steady pressure, let the heat do the work. If you do it right the adhesive will detach from the wall and the vinyl in about equal measure, which of course means you'll have to deal with the residual next. If it's the kind of adhesive I think it is, Goo Gone works okay (or any of the orange oil based cleaners) but Rapid Remover is designed for the job. If none of those will touch it then it's something solvent based and you'll have to step up to something with acetone in it (Goof Off) but test a little spot first to make sure it's not going to ruin your paint. He's a link with a bit more information.  http://www.signwarehouse.com/blog/a-basic-guide-to-vinyl-removal-options/
Comment: ... and you may find that you do have to repaint, possibly with a skim coat of plaster first, no matter how hard you try.
Comment: @keshlam True enough. It could be argued that you'd be money ahead just ripping the thing off and dealing with the fall out.


Compromised mobile device on a company network

Question: What can a malicious user / attacker do if access is gained to a mobile device (smartphone/tablet) on a company network ?
Comment: This is a "How long is a piece of string?" question - the answer depends entirely on any security measures in place, and the skill, determination, and motivation of the attacker. Are you able to narrow the question down to a specific threat or important asset?
Comment: I guess my question was too broad ! What I wanted to understand was if a compromised mobile device is **as** risky as a compromised computer... ie. can be used to pretty much do anything depending on the skill, determination, and motivation of the attacker like you mentioned.
Comment: @vibez_well Mobile devices = mobile computers
Answer: Ok, I'm answering the question as posed in your comment:

[Is] a compromised mobile device as risky as a compromised computer?

Yes. Absolutely.
Per @Sean W, a modern smartphone/tablet is a computer, albeit a little one with not that much CPU, that is easy to carry around and prone to being dropped into puddles. Therefore the risk profile is similar (at the very least).
In fact, in many cases I would argue that a smartphone/tablet is much more risky once compromised:

It's small and easily hidden. If connected to AC power in a dark corner, it might go un-noticed for months.
They often have data connectivity via cellular network, allowing an attacker to bypass any corporate security controls.
The mobile OS usually runs on chips (as opposed to hard drives, which can be removed). This makes post-attack analysis much more difficult for Infosec analysts.

An attacker connects to the smartphone, which in turn is connected to the corporate network. End result? The attacker is connected to the corporate network, just as if a desktop computer had been compromised. Almost every mobile device will have enough CPU to run a SSH server for the attacker to connect to.


Hidden pins in Proteus

Question: I'm implementing the following scheme and I have trouble with IC4 element (7430: 8-pin NAND) that have 7 and 14 pins, as I understand, VCC and GROUND respectively. But in Proteus 8 NAND don't have these pins. Also on IC[1-3] pins +V are missing. What should I do?
Comment: what about the 7490? ... why are you not asking about them? ... does the simulation work without the power connections?
Comment: You know, yes, 7490 too. In general, some elements in the scheme have pins that aren't in Proteus.
Comment: Does it mean that the scheme should be revised?
Comment: what do you mean by `revised`?
Comment: When I said that the scheme should be revised, I meant that the schematic should propably be updated to reflect the actual pinouts of the ICs.
Comment: what does that mean? ... aren't the pin numbers accurate?
Answer: This is fortunately a very simple task. By default, the GND and VCC pins are connected to the GND and VCC net. If you haven't changed them, VCC will be defaulted to 5V.
To change them, right click the component and select properties. You can then select "hidden Pins". This will be an option for any IC where pins are hidden.

Once you have done that, you can select the nets for them to be connected to.

Simply select the net you want the power rails connected to. Make sure you have set your nets up before.

Hidden pins in Proteus


Can I reverse a registry setting, "DelegateExecute"=-, recommended in a previous post

Question: I provided your advice on a post (below) for a user that was having trouble with hyperlinks in Windows 8 IE 10 and it did not fix his problem. He now wants me to tell him how to put it back the way it was and I do not know how. He did not make a backup of his registry as recommendded. If it is not too much trouble could you please tell me how to reverse this registry update if it is possible? If it is not possible could you please let me know what effect if any this upodate will have on his computer?

Copy and Paste the following:
<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\IE.HTTP\shell\open\command]
"DelegateExecute"=-

[HKEY_CLASSES_ROOT\IE.HTTPS\shell\open\command]
"DelegateExecute"=-
</code>
Answer: Extracted from Windows 7, should work on Windows 8 too:
<code> Windows Registry Editor Version 5.00

 [HKEY_CLASSES_ROOT\IE.HTTP\shell\open\command]
 "DelegateExecute"="{17FE9752-0B5A-4665-84CD-569794602F5C}"

 [HKEY_CLASSES_ROOT\IE.HTTPS\shell\open\command]
 "DelegateExecute"="{17FE9752-0B5A-4665-84CD-569794602F5C}"
</code>
The procedure is the same: save it as a .reg file and double-click.
Comment: and Windows 10 Fwiw


How do you emulate ADTs and pattern matching in TypeScript?

Question: Unfortunately, as of 0.9.5, TypeScript doesn't (yet) have algebraic data types (union types) and pattern matching (to destructure them). What's more, it doesn't even support instanceof on interfaces. Which pattern do you use to emulate these language features with maximal type safety and minimal boilerplate code?
Answer: I went with the following Visitor-like pattern, inspired by this and this (in the example, a Choice can be Foo or Bar):
interface Choice {
    match<T>(cases: ChoiceCases<T>): T;
}

interface ChoiceCases<T> {
    foo(foo: Foo): T;
    bar(bar: Bar): T;
}

class Foo implements Choice {

    match<T>(cases: ChoiceCases<T>): T {
        return cases.foo(this);
    }

}

class Bar implements Choice {

    match<T>(cases: ChoiceCases<T>): T {
        return cases.bar(this);
    }

}

Usage:
function getName(choice: Choice): string {
    return choice.match({
        foo: foo => "Foo",
        bar: bar => "Bar",
    });
}

The matching itself is expressive and type-safe, but there's lot of boilerplate to write for the types.
Comment: Maybe you can use sweetjs to create a macro for 'match' and wrap around multiple types of Choice so you have type-checking but the actual implementation would be provided by the macro.
Answer: Example to illustrate the accepted answer:
enum ActionType { AddItem, RemoveItem, UpdateItem }
type Action =
    {type: ActionType.AddItem, content: string} |
    {type: ActionType.RemoveItem, index: number} |
    {type: ActionType.UpdateItem, index: number, content: string}

function dispatch(action: Action) {
    switch(action.type) {
    case ActionType.AddItem:
        // now TypeScript knows that "action" has only "content" but not "index"
        console.log(action.content);
        break;
    case ActionType.RemoveItem:
        // now TypeScript knows that "action" has only "index" but not "content"
        console.log(action.index);
        break;
    default:
    }
}

Comment: The example is inspired by [actions in Redux](https://redux.js.org/basics/actions).
Answer: TypeScript 1.4 adds union types and type guards.
Comment: link returns 404
Answer: To answer

it doesn't even support instanceof on interfaces.

Reason is type erasure. Interfaces are a compile type construct only and don't have any runtime implications. However you can use instanceof on classes e.g. :
class Foo{}
var x = new Foo();
console.log(x instanceof Foo); // true

Comment: Thank you for this insight, it is interesting, but it doesn't answer the question itself, so I suggest converting it to a comment instead.
Answer: Here's an alternative to the very good answer by @thSoft. On the plus side, this alternative

has potential interoperability with raw javascript objects on the form { type : string } & T, where the shape of T depends on the value of type,
has substantially less per-choice boilerplate;

on the negative side

does not enforce statically that you match all cases,
does not distinguish between different ADTs.

It looks like this:
// One-time boilerplate, used by all cases.

interface Maybe<T> { value : T }
interface Matcher<T> { (union : Union) : Maybe<T> }

interface Union { type : string }

class Case<T> {
  name : string;
  constructor(name: string) {
    this.name = name;
  }
  _ = (data: T) => ( <Union>({ type : this.name, data : data }) )
  $ =
    (f:(t:T) => U) => (union : Union) =>
        union.type === this.name
          ? { value : f((<any>union).data) }
          : null
}

function match<T>(union : Union, destructors : Matcher<T> [], t : T = null)
{
  for (const destructor of destructors) {
    const option = destructor(union);
    if (option)
      return option.value;
  }
  return t;
}

function any<T>(f:() => T) : Matcher<T> {
  return x => ({ value : f() });
}

// Usage. Define cases.

const A = new Case<number>("A");
const B = new Case<string>("B");

// Construct values.

const a = A._(0);
const b = B._("foo");

// Destruct values.

function f(union : Union) {
  match(union, [
    A.$(x => console.log(`A : ${x}`))
  , B.$(y => console.log(`B : ${y}`))
  , any (() => console.log(`default case`))
  ])
}

f(a);
f(b);
f(<any>{});

Answer: This is an old question, but maybe this will still help someone:
Like @SorenDebois's answer, this one has half of the per-case boilerplate as @theSoft's. It is also more encapsulated than @Soren's. Additionally, this solution has type safety, switch-like behavior, and forces you to check all cases.
// If you want to be able to not check all cases, you can wrap this type in `Partial<...>`
type MapToFuncs<T> = { [K in keyof T]: (v: T[K]) => void }
// This is used to extract the enum value type associated with an enum.
type ValueOfEnum<_T extends Enum, U = any> = EnumValue

class EnumValue<T> {
  constructor(
    private readonly type: keyof T,
    private readonly value?: T[keyof T]
  ) {}

  switch(then: MapToFuncs<T>) {
    const f = then[this.type] as (v: T[keyof T]) => void
    f(this.value)
  }
}

// tslint:disable-next-line: max-classes-per-file
class Enum<T> {
  case<K extends keyof T>(k: K, v: T[K]) {
    return new EnumValue(k, v)
  }
}

Usage:
// Define the enum. We only need to mention the cases once!
const GameState = new Enum<{
  NotStarted: {}
  InProgress: { round: number }
  Ended: {}
}>()

// Some function that checks the game state:
const doSomethingWithState = (state: ValueOfEnum<typeof GameState>) => {
    state.switch({
      Ended: () => { /* One thing */ },
      InProgress: ({ round }) => { /* Two thing with round */ },
      NotStarted: () => { /* Three thing */ },
    })
}

// Calling the function
doSomethingWithState(GameState.case("Ended", {}))

The one aspect here that is really not ideal is the need for ValueOfEnum. In my application, that was enough for me to go with @theSoft's answer. If anyone knows how to compress this, drop a comment below!


Sports vocabulary

Question: I'm a little bit confused.
I'm trying to learn sport vocabulary but I can't understand the difference between course and court, also there are some words which meanings aren't very clear for me.For example the words like circuit,slope,track and pitch. Could you help me with this?
Comment: Have you looked them up in a dictionary? What was it that it was so confusing to you that you decided to ask this question on ELL?
Answer: It's pretty much down to idiomatic usage for each sport.
"Course" is mainly used for races of various kinds, since "course" means a path to follow.
Tennis and basketball are played on "courts".
Some usages are even regional. Soccer is played on a "field" in the US but on "the pitch" in the UK.

Sports vocabulary


How to find out how many lines of code there are in an Xcode project?

Question: Is there a way to determine how many lines of code an Xcode project contains?  I promise not to use such information for managerial measurement or employee benchmarking purposes.  ;)
Comment: If you want lines, then you can use this answer: http://stackoverflow.com/questions/5901758/xcode-4-see-the-number-of-the-line-of-code-i-am-on But it includes spaces
Comment: Does this answer your question? [Count total number of lines in an Xcode project](https://stackoverflow.com/questions/28764408/count-total-number-of-lines-in-an-xcode-project)
Answer: I see this floating around and use it myself:
find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.swift" ")" -print0 | xargs -0 wc -l

Comment: it appears the .m and .mm tests are missing an * (edited: seems SO is not rendering those without a preceding slash) The above was not working for me until I added them as such: find . "(" -name "\*.m" -or -name "\*.mm" -or -name "\*.cpp" ")" -print0 | xargs -0 wc -l
Comment: To handle subdirs with spaces in the names you need: find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" ")" -print0 | xargs -0  wc -l
Comment: Note for Swift users - replace or add another 'or' with the file  extension .swift
Comment: How can I get total number of lines excluding commented and blank lines ?
Answer: Check out CLOC.

cloc counts blank lines, comment lines, and physical lines of source code in many programming languages.

(Legacy builds are archived on SourceForge.)
Comment: CLOC is available via Homebrew. The ease of use in the command line was refreshing.
Comment: I love the pun in the name there -- yes you can tell how productive you've been by checking out your CLOC.
Comment: Use above link to download './cloc-1.56.pl' perm version of cloc tool. Make sure that you enable execution permission on cloc-1.56.pl file using 'chmod u+x cloc-1.56.pl' command.

If your source code is located in directory 'project_code'
You just need to run following command.
Answer: I have been using CLOC as mentioned by Nathan Kinsinger and it is fairly easy to use. It is a PERL script that you can add and run from your project directory.
PERL is already part of Mac OS and you can invoke the script this way to find out your number of lines you have written:
perl cloc-1.56.pl ./YourDirectoryWhereYourSourcesAre

This is an example of output i got from such command:
   176 text files.
   176 unique files.
     4 files ignored.

http://cloc.sourceforge.net v 1.56  T=2.0 s (86.0 files/s, 10838.0 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Objective C                     80           3848           1876          11844
C/C++ Header                    92            980           1716           1412
-------------------------------------------------------------------------------
SUM:                           172           4828           3592          13256
-------------------------------------------------------------------------------

Comment: Nice! I like this better than my own answer. :-)
Comment: You may need to download the script first. Then navigate to the directory where that script is and run that command with whatever file name you downloaded.
Comment: One last thing, I had to run span Moo as per error that appeared when running it for the 1st time so checkout for that one as well
Comment: Should be cloc perl-1.56.pl ./YourDirectoryWhereYourSourcesAre and not as above, if you install perl from scratch make sure you enter the current perl version (mine was 5.30.1 so basically cloc perl-5.30.1.pl ./)
Answer: Open up Terminal.app, go into your project's root directory, and run this command:
For Swift only:
find . \( -iname \*.swift \) -exec wc -l '{}' \+

For Obj-C only:
find . \( -iname \*.m -o -iname \*.mm -o -iname \*.h \) -exec wc -l '{}' \+

For Obj-C + Swift:
find . \( -iname \*.m -o -iname \*.mm -o -iname \*.h -o -iname \*.swift \) -exec wc -l '{}' \+

For Obj-C + Swift + C + C++:
find . \( -iname \*.m -o -iname \*.mm -o -iname \*.c -o -iname \*.cc -o -iname \*.h -o -iname \*.hh -o -iname \*.hpp -o -iname \*.cpp -o -iname \*.swift \) -exec wc -l '{}' \+

Terminal quick tips:
  ls: list directory contents
  cd: change directory
  Press tab to autocomplete
  Remember to put "\" backslash before spaces
  I suggest going one folder down from the main project so you get rid of code count from the frameworks
Answer: In terminal, change into the project directory and run:
find . -type f -print0 | xargs -0 cat | wc -l

If you want only certain file types, try something like
find . -type f -name \*.[ch]* -print0 | xargs -0 cat | wc -l

Comment: Nice, but includes comments and blank lines and thus is not exactly what was asked for. A LOC measure should be as independent of code formatting style as possible and thus a bunch of blank lines or comments between to logical parts in a file shouldn't count towards the sum.
Answer:
open terminal
navigate to your project
execute following command inside your project:
find . -path ./Pods -prune -o -name "*.swift" -print0 ! -name "/Pods" | xargs -0 wc -l

Or:
find . -path ./Pods -prune -o -name "*[hm]" -print0 ! -name "/Pods" | xargs -0 wc -l

(*Excluding pod files count from total count)
Answer: Check out Xcode Statistician, it does exactly what you want. It also provides other interesting statistics so is worth a run for fun now and then.
Note that it will not look inside real folders, though it will look in groups. Odds are you aren't using real folders so it'll work great. If you are using folders then you just have to do the count in each folder and add them together.
Note: As of June, 2012, it seems this does not work properly with the latest versions of Xcode.
Comment: Note that Xcode Statisician doesn't deal with subdirs in your project at this point.
Comment: Seems it doesn't work at all with X-Code 4.2 projects on Lion (at least it didn't give any statistics for my project)
Comment: Just a heads up for those who mix Objective-C and C/C++: It doesn't count *.c or *.cpp files.
Comment: @Matt__C Aye, hence "Note that it will not look inside real folders". Quite a bit more manual work, unfortunately (and recursive folder searching is easy to code), but it's workable.
Comment: Ah, bummer, it may be outdated now.
Comment: It still works as of xcode 4.5.1. It just has a bug where it doesn't count lines in subfolders. If you navigate into each folder, it will tell you the number of lines in that folder. A bit tedious to add them up, but you probably won't have more than a dozen or so folders anyway (hopefully)
Comment: Sorry, but this program fails to recurse down sub-directories, and is also not code-signed by any identified developer - so may be malware. So for most reasonably sized projects, it is unusable
Comment: @MottiShneor This answer was from 8 years ago. Things have changed a great deal since then. In fact, the edited answer (made 3 years ago) specifically notes that it no longer works.
Answer: If you go to your project's directory in terminal and enter:
find . "(" -name "*.h" -or -name "*.m" -or -name "*.mm" -or -name "*.hpp" -or -name "*.cpp"  -or  -name "*.c" -or -name "*.cc" -or -name "*.swift" ")" -print0 | xargs -0 wc -l

That will give you a project breakdown, as well as the line total for each file and the project as a whole.
Comment: Absolutely. Everyone has their own solution. And if they have their own prefix (eg: "RE"), they could even do `find . "(" -name "RE*.swift" ")" -print0 | xargs -0 wc -l`
Comment: For swift just removed everything and added .swift `find . "(" -name "*.swift" ")" -print0 | xargs -0 wc -l`
Comment: @WCByrne Alternatively, we can just add .swift to the original command
Comment: Indeed. Since most libraries and borrowed code are still in .h & .m it helped to trim the count down to just what I had written.
Answer: Steps to implement CLOC library in Mac as below:

Open Terminal.
Install Homebrew by copying and pasting the below command in the Terminal (including double quotes).

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter system password if asked.
You will see the terminal screen as below.

System will popup so many permissions, allow all the permissions
If everything goes fine, you will see terminal screen as below,

Now its time to install CLOC using below command.

brew install cloc

Navigate to the project directory and run either of the following commands.

cloc . --exclude-dir=Pods (to exclude pod files)
cloc . (including pod files)
If everything goes fine, it will display the number of lines of code as below,
Answer: Nozzi's version doesn't work for me, but this one:
find . -type f -print0 | xargs -0 cat | wc -l

Comment: short and concise - but it counts lines also on non-source-code files. So actually the filename-extension filtering is crucial here. The OP wanted to count "source code lines". not any text lines.
Answer: A quick & easy way:
Use a regex search (Find Navigator, choose Find > Regular Expression).

.\n

Works conveniently with Xcode search scopes and you can easily customize it to whatever type of line you'd like to count ;).
Comment: Now that's a nice one! not the fastest, but without leaving the dev environment. I like it. Probably a better regular expression can avoid counting white-space lines and things like that.
Comment: Keep it simple. I like it.
Answer: I am not familiar with xcode, but if all you need is to count the number of lines from all those specific files within a directory tree, you may use the following command:
find .... match of all those files ... -exec wc -l {} +

Following Joshua Nozzi's answer, in GNU find the regular expression for such files would be like:
find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.swift" ")" -exec wc -l {} +

or even
find -regex ".*\.\(m\|mm\|cpp\|swift\)$" -exec wc -l {} +

this uses a regular expression to match all files ending in either .m, .mm, .cpp or .swift. You can see more information about those expressions in How to use regex in file find.
If you are working with Mac OS find, then you need a slightly different approach, as explained by Motti Shneor in comments:
find -E . -regex ".*\.([hmc]|mm|cp+|swift|pch)$" -exec wc -l {} +

Both will provide an output on the form of:
234 ./file1
456 ./file2
690 total

So you can either keep it like this or just pipe to tail -1 (that is, find ... | tail -1) so that you just get the last line being the total.
Comment: Finally, you must also provide a path where to search on OSX. so the variation that does work, looks like this: find -E . -regex ".*\.([hmc]|mm|cp+|swift|pch)$" -exec wc -l {} +
Comment: well --- the find -regex ".*\. etc doesn't work for me on MacOS - it claims an illegal option --r what kind of find are you using?
Comment: @MottiShneor you probably want to check [this question](https://stackoverflow.com/q/5905493/1983854) where they talk about `\|` and others in MacOS. `--regex` is valid in both GNU find (the one I use) and MacOS.
Comment: well --- no. I found out in MacOS you must find -E for extended regular expressions. Do copy the suggested command above onto whatever OS-X you can get, and see for yourself. man find on MacOS-X tells you you must -E for that.
Comment: @MottiShneor thanks for providing the approach in MacOS. I have updated the answer with that.
Answer: You can install SLOCCount through MacPorts. Or, more crudely, you can use wc -l.
Comment: "Total Estimated Cost to Develop                           = $ 1,934,715". This made my day!
Comment: CLOC is based on SCLOCount so i guess it is still a better approach to use CLOC
Answer: line-counter is a good alternative. It's lighter than CLOC and much more powerful and easier to use than other commands.
A quick overview
This is how you get the tool
$ pip install line-counter

Use line command to get the file count and line count under current directory (recursively)
$ line
Search in /Users/Morgan/Documents/Example/
file count: 4
line count: 839

If you want more detail, just use line -d.
$ line -d
Search in /Users/Morgan/Documents/Example/
Dir A/file C.c                                             72
Dir A/file D.py                                           268
file A.py                                                 467
file B.c                                                   32
file count: 4
line count: 839

And the best part of this tool is, you can add .gitignore like configure file to it. You can set up rules to select or ignore what kind of files to count just like what you do in '.gitignore'. Yes, this tool is just invented to make knowing how many lines I have easier.
More description and usage is here: https://github.com/MorganZhang100/line-counter
I'm the author of this simple tool. Hope it can help somebody.
Comment: Good Job! It helps me a lot.
Answer: Easy way - 100% working Tested
When I'm working on a swift project, I sometime's get the urge to know how many lines of code I have actually written. It would be interesting to see. However, I'm not just going to sit there counting every single line, we're programmers after all, we can do better!
Using Terminal
Open up terminal and navigate to your project:
cd path/to/your/project/

Next, type in one of the following lines of code to get the total number of lines in your project. It works by reading all the swift files (sorry objc users!) in your directory and counting up the lines.
Not Including Pods
find . -path ./Pods -prune -o -name '*.swift' -print0 ! -name '/Pods' | xargs -0 wc -l

Including Pods

find . -name '*.swift' -print0 | xargs -0 wc -l

Using Cloc
If you have homebrew on your mac, there is a much easier way to show the number of lines. Navigate to your project using terminal:
cd path/to/your/project/

Next, install Cloc
brew install cloc

Finally, type in one of the following commands
Not Including Pods
cloc . --exclude-dir=Pods

Including Pods
cloc .

Results:


How can I change keyboard shortcuts for Evince (and other GNOME programs)?

Question: Is there a way to customize keyboard shortcuts for Evince, the GNOME document viewer?
Comment: Have you tried these?
https://askubuntu.com/questions/136062/permanent-custom-keyboard-shortcuts-for-evince-document-viewer

https://askubuntu.com/questions/555401/how-to-customize-add-keyboard-shortcuts-for-evince/899956#899956
Answer: I downloaded the source code of evince (source code provided by Debian 9.9, evince 3.22.1) and since every shortcuts are written "as-is" in internationalization files (.po), i guess they are hardcoded.
For example:
help/fr/fr.po:msgid "<keyseq><key>Ctrl</key><key>R</key></keyseq>"
help/fr/fr.po:msgstr "<keyseq><key>Ctrl</key><key>R</key></keyseq>"

I'm trying to dig more, but the way evince manage shortcut is quite ... strange :)
Answer: You can edit them in the source code, where they are defined, and rebuild the package:
In theory, evince should read the accels file at init time and merge with the ones it has, so you can also change the accels file, in ~/.config/evince/accels. Keep in mind that it gets overwritten if there are syntax errors.
Comment: I don't have a file at ~/.config/evince/accels. Is there supposed to be something there?
Comment: It might be distribution/window manager dependent. It is there in Debian 9 + Xfce4. It is created automatically by evince if it does not exist.
Comment: Do I have to copy it over from some place in the filesystem, like `/usr/...evince`? I can't find it anywhere
Comment: It should be there. What is your system, its version and the the Evince version?
Comment: Evince 3.34.1 on Manjaro, with all the latest updates.
Answer: I resigned to customize keyboard shortcut for Gnome Program.
I can not use accels file.
I wrote patch for source code in old by portage.
However, I gave up because the source code changes frequently.
In now, I use mooz/xkeysnail: Yet another keyboard remapping tool for X environment.
I write config file.
define_keymap(re.compile("Evince"), {
    # t
    K("k"): K("r"),
}, "Evince")

One caution is required, and if you touch a key without a modifier key, it will be converted when you enter it in the search form.


Editing minor polygon discrepancies?

Question: I have a "park area" shapefile and a "lake" shapefile both consisting of polygons. There are some areas where the park area polygons do not entirely match the borders of the lake polygons due to data collection inconsistencies, even though the park area should match the lake outline completely. I am wondering if there is a way to properly extend the park area polygons in certain locations so they follow the outline of the lakes. I have attempted to use the Draw functions in ArcGIS for Desktop to no avail. I am not overly concerned with the accuracy of the park area polygons as this editing is for cartographic purposes, so if the park area ends up "inside" the water bodies it isn't an issue, but if there is a way to make the park area polygon automatically end at a lake border that would be preferable. Below is an image showing the issue I am having - The yellow background "sticks out" underneath the park area polygon at points it should not.
Answer: The quickest process to solve your problem is to use a combination between Symmetrical Difference and Merge tools in ArcGIS, however, to use Symmetrical Difference tool you should have ArcInfo License. If you don't have ArcInfo license, then QGIS is your friend in this case.
You can do it using the following steps:

Use the yellow background polygon as a base if its extent covers both the lake and the park area.
Use the difference tool two times:
(a) In the input use the yellow polygon as input and the park as the difference polygon, and save the output poylgon
(b) Use the out polygon from step (a) as input, and the lake area as the difference polygon, and save the output to a new file.
Use Merge tool to merge the output from step (b) with the lake polygon to extend the lake to edge of the park.

The above process is a general process, you can adjust it based on the data that you have.
Comment: I believe the old ArcInfo license is now Advanced license
Comment: A symmetrical difference in ArcGIS for Desktop can be done with a Basic level license by using Union then Select.
Comment: It is true. I followed what is written in the Symmetrical Difference tool of "This topic applies to ArcInfo only" to avoid any confusion.
Comment: Thanks for the solution - I appreciate it. I have been able to edit a few locations like this, but anything that is cut off by the map's extent doesn't seem to play well with the Symmetrical Difference tool. Do you have any advice on how to handle this?
Comment: You can create a new background polygons for other parts, then use the same process again.

Editing minor polygon discrepancies?


Silverlight 5 in-browser connect to socket

Question: I'm making a silverlight 5 in-browser app which will read and write from socket which is on server (192.168.1.92). I'm testing app on my development machine (192.168.1.10). I checked "Require eleveated trust when running in-browser" and it works. So I'm wirtting from 192.168.1.10 to socket on 192.168.1.92 and it works! But when I deploy app on web server on 192.168.1.92 and run app from my development machine (192.168.1.10) I get security exception "An attempt was made to access a socket in a way forbidden by its access permissions.".
In example there is need for changing registry, but I don't want to change it because I want to run app from other machines too, and I don't want to change registry each time.
Is it possible to give app permissions without changing anything on client side?
And how can I do this?
Answer: You should certify your application.


Help for wiring a bathroom exhaust fan

Question: I have a NuTone model QTN130LE1 ventilation fan/light. I have 2 switches on the wall. One is for the light,the other is for the fan.im not sure how to wire it up properly. I don't think I can use the nightlight because I don't have consistent power to the unit,unless a switch is on. I have a black,white,red and a bare ground wire for power. From what I can see,the red wire is coming from the fan switch.  The unit has a green,taped red and white,taped white and blue,and a taped together black and white wires. Any help would be much appreciated.
Comment: What do the installation instructions say to do?
Comment: I can't post a pic, because its too big. Wiring diagram is a little confusing
Comment: Take a picture of the instructions, post it to imgur, paste the link in a comment and someone will embed it for you.
Comment: I added a screenshot of the diagram
Comment: With the wires being taped for color you may have conduit and may be able to pull a new wire for the night light. ??  A photo of the wiring would clear this up.
Answer: Your green wire from the fan gets connected to the bare copper wire from your ceiling box. Then connect the white wire taped with the blue to the white wire taped to the black to the white wire from your ceiling box. Then connect the red wire from your switch to the black wire from your fan and connect the blue wire from your fan light to the black wire coming from your other switch.  The remaining red and white wires from your fan fixture are for the night light which you would need another switch to operate it
Comment: Does the grounds hook up to the ground screw on unit?
Comment: @ChrisHill  Yes it does.
Comment: Awesome, ty so much

Help for wiring a bathroom exhaust fan


Am I using DTOs wrong with my service?

Question: I currently have a WCF service that exposes a SOAP enpoint.  In this webservice I have the following metthod:
<code>    public List<DataField> GetAvailableFields(string accountNumber, string accountKey, Models.Enums.CountryEnum country)
    {
        //Code that builds DataFields
        return dataFields;
  }
</code>
My Datafields may look something like this
<code>      [DataContract]
public class DataField
{
    public DataField()
    {
        AlternativeFields = new List<DataField>();
    }
    [DataMember]
    public string FieldName { get; set; }
    [DataMember]
    public string Value { get; set; }
    [DataMember]
    public bool IsRequired { get; set; }
    [DataMember]
    public List<DataField> AlternativeFields { get; set; }
    public DataField ParentField { get; set; }
}
</code>
So I have 2 questions.
1:  The ParentField reference...I am guessing that this needs to go as I'm not sure how that would serialize
2:  Is it appropriate to have my list of alternative fields?  This is essentially a list of DTOs inside a DTO but it seems that this should serialize just fine and there should be no interoperability issues with this.  In general..is it bad practice to have DTOs inside other DTOs?
Thank you and feel free to point out anything I am doing incorrectly.
Answer: If the entire dataset will be required, then it's perfectly legitimate to have DTOs within DTOs. Otherwise consider sending only enough information for your domain entities to be fully populated (eg IDs of referenced entities).
FYI The parent field should serialize fine (as long as there are no cyclic references).
Answer: 1) The parent field doesn't have the DataMember decorator on it, so it won't serialize in the first place.
Supposing that it did have the decorator on it, you'd still be ok and it would serialize properly (since DataField is a data contract).  However, you need to be careful that you don't get into loops with this and start sending over everything for infinity times (that's a good way to get an exception).
2) The List of DTOs are fine.  Once again, however, you need to make sure that you're not sending over duplicate data.  Just send the data you need, and process it on the other end.
Generally, I send a list of DTOs, all with unique IDs, and they would all have Lists of Int32's pointing to those unique IDs.   However, if there are being sent over only for this purpose, then this is fine.

Am I using DTOs wrong with my service?


Expected number of successes from $N$ Bernoulli trials with different $p$

Question: Suppose I have N probabilities $(p_1, p_2,...,p_N)$ that represent the chance that each that a corresponding test was passed. How do I apply the Bernoulli distribution to determine the expected number of passes?
Comment: It's not completely clear how success is being "estimated" here.
Comment: I'll try to be clearer. I have a number of locations. I apply a test in each location. However, I only have a probability that the test passed. I want to estimate the number of passed tests, with some confidence interval.
Comment: Thanks, yes, that's clearer now. I have attempted an edit to your question to perhaps make it clear in the question itself, but you may want to edit it further. Is this for a class?
Comment: Ha - no its not a homework question. It is for some work I am doing and I have significantly reduced the problem so that it is a simple question.
Comment: see also section 3 of http://stats.stackexchange.com/questions/160458/estimate-accuracy-of-an-estimation-on-poisson-binomial-distribution/164746#164746
Answer: If $p_i$ is the probability that test $i$ passed, then we can model each test as a Bernoulli random variable:
$$X_i \sim Ber(p_i)$$
The expected number of passed tests is equal to:
$$E[\text{#passed}]=E\left(\sum_{i=1}^N X_i\right)=\sum_{i=1}^N E(X_i)=\sum_{i=1}^N p_i$$
This is due to the linearity of expectation and the fact that a $Ber(p)$ random variable has expected value $p$.

Per your response to glen_b, the distribution of the total number of passed tests will have a Poisson Binomial distribution.
Comment: Sorry for not replying! Your answer agrees with what I thought, I just wanted to check.
Answer: If you add up $n$ Bernouilli random variables with a different success probabilities then the sum has a Binomial Distribution of Poisson.
If the success probabilities are $p_i$ then the mean of the Binomial of Poisson is $n \bar{p}$ where $\bar{p}=\frac{\sum_i p_i}{n}$ and the variance of the Binomial distribution of Poisson is $n \bar{p} (1-\bar{p}) - n \times var(p)$  (Note: for $var(p)$ there must be $n$ in the denominator!).
Note that if $var(p)$ is relatively small then the variance reduces to a binomial variance, which was expected because a small $var(p)$ means that the success probabilities of the Bernouillis are more or less equal.
I have some code to simulate this:
# Function that simulates Poisson Binomial random variable
#
#   parameter 'ps' contains the success probabilities of the Bernouilli's to add up
#   parameter n.sim is the number of simulations
#
#   The return value is a list containing
#      - the simulated mean
#      - the simulated variance
#      - the 'true' mean of Poisson Binomial namely  n x average(ps)
#      - the true variance of Poisson Binomial namely n x average(ps) x (1-average(ps)) - n var(ps)

simulate.Poisson_Binomial<-function(ps, n.sim=100000) {

  sum.all<-vector(mode="numeric", length=n.sim)
  for ( i in 1:n.sim ) {
    # generate the random outcome for each Bernouilli
    random.outcome<-( runif(n=length(ps)) <= ps )

    # count the number of successes
    sum.all[i]<-sum(random.outcome)
  }

  ret<-list(sim.mean=mean(sum.all),
            sim.var=var(sum.all),
            PoisBin.mean=length(ps)*mean(ps),
            PoisBin.var=length(ps)*mean(ps)*(1-mean(ps))-(length(ps)-1)*var(ps))

  return(ret)
}

# Generate 50 Bernouilli success probabilities
set.seed(1)
N<-50
ps<-runif(n=N)

# do the simulation
simulate.Poisson_Binomial(ps=ps, n.sim=5e5)

In the return of the R-function there is (length(ps)-1)*var(ps) this is because the R-function var() has (n-1) in the denominator. so $-n \times var(p)$ in the formula above should be 'translated' to -length(ps) * ( var(ps) * (length(ps)-1)/length(ps) which becomes - var(ps) * (length(ps)-1)
See also this Intuitive explanation for dividing by $n-1$ when calculating standard deviation?


How can I find out which program takes how much bandwidth in Windows 7?

Question:
Possible Duplicate:
Is there a way to find out what app is using most of my bandwidth in windows

When I connect to the Internet in Windows 7 Home Premium a program is taking up all the bandwidth. I can't find which program is doing this. I have a new Windows installation with all my software installed.
I already checked Window Update and for antivirus updates but this is not the cause.
Is there any software that can tell me which program is using this bandwidth?
Answer: Why don't you use Resource Monitor from Task Manager in Windows 7?
Its in Task Manager > Performance > Network > Network Activity.


Can an employer monitor employees off-premises?

Question: Can an employer monitor employees off-premises or during activities not in course of their employment? Can they fix what people can do in their day to day life and activities in any way? For example, an employer dictating what brand of products may be used in the employees' day to day non-working life.
Comment: It might alsso be denia of employment or promotion to people who wrote something in past or do something irrelivant with job in day to day llife .
Comment: Employers were allowed to do so under the traditional English common law doctrine of employment at will. I do not know the extent to which India has modified the common law in that regard. Most U.S. states follow the common law rule (but not Colorado or Montana), but most commonwealth countries (e.g. Canada and Australia and England) have modified that part of the common law by statute.
Answer: Yes
An employer can require their employees to obey lawful and reasonable directions. In this conduct a reasonable direction is one which would prevent a significant adverse effect to the employer and is a reasonable imposition on the employee given their role in the organisation.
Even without a specific instruction, an employee owes a duty to their employer to not damage their reputation.
For example:

McDonald's can require their staff not to frequent KFC while in uniform.

Celebrities who are brand ambassadors can be prohibited from using conflicting brands.

A church leader could be prohibited from extra-marital affairs.

General limits on social media so as not to reflect the employer in a poor light.
Answer: I know that some German banks didn't allow employees to have loans or mortgages with other banks, presumably for security reasons - you don't want other banks to be able to put pressure on your employee who has problems repaying a mortgage. On the other hand, these banks had much more generous terms for employees, so this wasn't a problem; employees actually saved money this way.
There was an interesting case in the UK: If you claim you are ill, so you can't work and the employer still has to pay you, the employer has the right to check that you are telling the truth. What made it interesting was that the case was about a police officer who claimed to be injured. And while the police wouldn't be allowed to check on a random citizen, they are allowed to do this if they are the employer.


The process cannot access the file because it is being used by another process

Question: I use this code but can't close the connection
cnnstr = " Data Source=.\SQLEXPRESS;AttachDbFilename=" & CurDir() & "\datastore.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim con As New SqlConnection(cnnstr())
Dim com As New SqlCommand("insert into tblbackuphistory values('" & dateshamsi & "','" & saat & "','" & mas & "',N'" & user & "')", con)

If con.State = ConnectionState.Closed Then
    con.Open()
End If

com.ExecuteNonQuery()
com.Cancel()
com.Connection.Close()
con.Close()
com.Connection.Dispose()
con.Dispose()

Answer: If an exception is thrown by Open() or ExecuteNonQuery(), none of those .Close() calls that come after will ever execute. That's why you should always use a Try/Finally block for anything like this, and that can be shortened with a Using block.
While I'm here, this code is more than a little vulernable to sql injection attacks. That might be okay for a db that only exists as a local data store for an installed program (no one cares if a user wants to inject data in a database they own), but string concatenation for sql strings is still a bad habit. What happens if you end up with a user name with an apostrophe in it?
This code fixes both issues:
cnnstr = " Data Source=.\SQLEXPRESS;AttachDbFilename=" & CurDir() & "\datastore.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

Using con As New SqlConnection(cnnstr),
      cmd As New SqlCommand("insert into tblbackuphistory values( @dateshamsi, @saat, @mas, @user)", con)

    cmd.Parameters.Add("@dateshamsi", SqlDbType.DateTime).Value = Convert.ToDatetime(dateshamsi)
    'guessing at column lengths here
    cmd.Parameters.Add("@saat", SqlDbType.VarChar, 50).Value = saat
    cmd.Parameters.Add("@mas", SqlDbType.VarChar, 50).Value = mas
    cmd.Parameters.Add("@user", SqlDbType.NVarChar,50).Value = user

    con.Open()
    cmd.ExecuteNonQuery()
End Using

But, based on the error from the title, this isn't the whole story. It sounds like the connection string is wrong because datastore.mdf file is already attached to the DB server. If you just made this DB using Sql Server Management Studio, you don't need to attach it (the AttachDbFileName portion). You just set the Database= option in the string to your database name.
Sql Server Express runs as an always-on service. It's still effectively a server-class engine, and is poorly suited as a simple local data store, even if it can work that way. It's really intended for small work groups and web sites. If you just want a local data store for you app, use Sql Server Compact, Sql Server LocalDb, SqlLite, or even MS Access.


How do I arrive at the α-trimethylsilyloxy ketone from an unmodified ketone using TMSCl, triethylamine and mCPBA?

Question: I'm confused about what is going on here. I gather that step 1 is typically supposed to protect an OH group, but there isn't any in the starting material.
Comment: http://www.organic-chemistry.org/namedreactions/rubottom-oxidation.shtm
Comment: What does MCPBA usually do with an electron rich double bond?
Comment: Since step 2 occurs *after* step 1, epoxidation only occurs *after* the protection of the OH group. By implication, enolization must have occured *before* step 2 ( I suspect enolization catalyzed by NEt3). By logical extension the carbonyl oxygen in molecule A is also the oxygen within the -OTMS group. But since the carbonyl oxygen in meta to the methyl group in molecule A, and para to the methyl group in molecule B, I am unsure of what happened.
Comment: If this was something like TBDMS, I'd expect it to resist hydrolysis, but OTMS normally hydrolyses under acidic conditions as shown. Unless there's stabilisation from the carbonyl?
Comment: @Beerhunter- the TMS would go. Possibly a typo in the question, or possibly just left there as a hint as to what's occured
Comment: Yeah, TMS is more of a disappearance than a protecting group ;)
Answer: In connection with a reasonable base (triethylamine works fine for this), ketones are known to be enolised by silyl chlorides and trapped as silyl enol ethers. This is not only a key process in Mukaiyama aldol reactions but also in your structure.
In general, the combination of $\ce{NEt3}$ and $\ce{TMSCl}$ has three possible ways to enolise your compound:

γ-deprotonation to the methyl group, creating an exocyclic double bond
γ-deprotonation of the ring proton to give a 1-silyloxycyclohexa-1,3-diene system
α-deprotonation to the other side, giving a 2-silyloxycyclohexa-1,3-diene system

By the general rules one is taught to follow, the second option should be identified as the thermodynamically most favoured. However, the third option is typically the kinetically favoured one, so given the correct conditions (low temperatures), we typically expect enolisation by deprotonation the α proton. It helps here that $\ce{TMSCl}$ is a rather small and reactive silyl chloride (Lewis acid), meaning that once it has attached to the keto oxygen deprotonation will be a rather rapid process.
If you left the solution to equilibrise with $\ce{NEt3}$ before quenching you would probably get much more of the γ-deprotonation products.
The next two steps, a Rubottom oxidation, are basically the generation of an epoxide by $\ce{$m$CPBA}$ (as an isolated reaction also known as the Prilezhaev reaction) followed by acid-catalysed epoxide opening which reforms the $\ce{C=O}$ double bond and initiates a Brook migration of the silyl group. The overall mechanism is given in the scheme below.

Scheme 1: mechanism of the Rubottom oxidation.[1]
Reference:
[1]: L. Kürti, B. Csakó, Strategic Applications of Named Reactions in Organic Synthesis, Elsevier Academic Press, 2005, pp. 388–9.
Comment: Brilliant! Though I think there should be an arrow from the O-TMS bond to the O so as to restore the neutral charge, in the final step.