What is tacky finish?

Question: I see this mentioned all the time in guides but I don't know what this looks like. Google does not make this obvious. Can anyone please tell me what a tacky finish is or is supposed to look like? Bonus points if you show pictures!
EDIT:
I'm amazed I even need to clarify this in a DIY home improvement forum, but here goes....
No, I'm not referring to style or glue. I'm referring to this type of explanation:
"Rub a small amount of acetone, using a clean cotton swab, into another less-visible part of the wood. If the acetone beads, the current finish is polyurethane. If not, wait for a couple of minutes. Touch or scrape the area lightly with your finger. The lacquer will dissolve completely in this time, but varnish and shellac will become tacky."
Source: https://www.hunker.com/12437441/how-to-tell-which-kind-of-finish-is-on-a-wood
Dozens of other guides use this word to describe a finish, but I can't find any consistent explanation of what this means specifically with respect to wood finishes. I also can't find any pictures, so even if something was tacky I would have no way to identify it.
What does "tacky" mean in this context?
Comment: So Style or glue?
Comment: @SolarMike neither, I'm referring to the clearcoat finish on stained wood (polyurethane, lacquer, etc.).
Answer: At least two very different meanings.
One has nothing to do with how it looks - it's "tacky" meaning slightly sticky. For a finish, that's not fully cured/hardened.
The other is tacky meaning that in the opinion of the observer it's in poor taste or style. That one is a moving target as things go in and out of style and tastes change or are simply different. Something finished with glitter might be divine to one person and tacky to another, say.

What is tacky finish?


Can you improve the amulet of articulation?

Question: I tried using a workbench, but it did not show up in the options. I was wondering if there was some other arcane method of improving it, like tossing it in the Atronach Forge, etc.?
Answer: Jewelry can not be improved as the only stats they have are from enchanting. Also, once an item has been enchanted it also can not be altered, this includes quest given items. However, the stats can vary on some quest rewards, often depending on the players level.
Sources personal experience and wikia
Comment: Just wanted to add that this Amulet is not leveled. There are a 7 different versions the character can receive upon completion of the quest. [Found Here](http://www.uesp.net/wiki/Skyrim:Amulet_of_Articulation#Amulet_of_Articulation)  It is possible/ likely that reloading a save previous to receiving the reward will allow the player to eventually get the best amulet stats possible.


How to handle the data that are entered in the filed that are triggered by toggle

Question: Here is a hypothetical test case
Test Case
User is asked if they want  to provide an address
Answer options: Yes or NO
User answer yes and fields to provide an address appears
User entres the information
After all, information is entered user decided to change the answer to NO
The fields disappear
Then
The user decided to select YES again
The fields appear and ...
Question:
Should we prepopulate the fields with previously entered information?
What is the best user experience?
Answer: I would omit the declarative yes/no step before address entry.
It is unnecessary and can actually be a bit annoying, unless some technical, legal, or regulatory constraint compels your application to prefix the address entry fields with an explicit 'do-you-actually-want-to-do-this' type question. This could be analogous to a legally binding declaration of the user's acceptance of cookie policy, or explicit EULA consent.
But unless such constraints apply, simply present the fields necessary to enter an address voluntarily, and identify those unambiguously as optional. This way, if your users do wish to provide an address - consider their privacy concerns - they can do so by simply filling in the necessary information. Otherwise they may just skip the address step - a choice your application should noticeably tolerate.
That clears up the conundrum of needing to cache address information (and then repopulating it) through potentially multiple changes of mind by the user (Yes... No... Yes... er, actually, no!)
Consider presenting a 'Clear all' button in context with the address field block, which allows your users to erase collectively any address information they may have started to provide but then decided against disclosing.
The following may be off topic, and whether you choose to implement it should depend on the specific business case your site seeks to satisfy, but it is a hallmark of good attention to UX detail: When addressing a global audience you may want to consider that address formatting is not uniform across the world, and with that, user habits of writing an address may differ internationally.
You can accommodate that characteristic and make them feel at home.
A good pattern to follow is iOS's (and likely also Android OS's) 'New Contact...' workflow, which decides whether a postal code appears as suffix to the location information, as is common in most English speaking countries (e.g. London WC1A 2XY / New York NY 10016), or as a prefix, (e.g. 75016 Paris / 10159 Berlin etc.) as is customary in mainland Europe and parts of South America.
It is easy to do that when the country choice - even though located at the bottom of the field block - is presented as a drop list, with all preceding fields left void, so the country choice attracts the user's attention first. The same goes for the order in which house number and street name are written, and so forth.
Selection of a specific country causes the postal code - location, and house number / street name fields to trade places as applicable. This should also work if those fields have already been filled. It may seem like a mere nice luxury at first, but to my mind steadfast attention to such details truly distinguishes great UX.
I hope that helps. Best of luck!


Unable to locate package libjpeg-dev

Question: I am trying to install libjpeg-dev through the sudo apt-get install libjpeg-dev command on my Ubuntu machine, but keep getting the following error:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package libjpeg-dev

Some information about my machine:
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.1 LTS
Release:    14.04
Codename:   trusty

Linux ip-172-31-33-222 3.13.0-32-generic #57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

/etc/apt/sources.list file:
deb http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty main
deb-src http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty main

deb http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty-updates main
deb-src http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty-updates main

deb http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty universe multiverse
deb-src http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty universe multiverse
deb http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty-updates universe multiverse
deb-src http://us-west-2.ec2.archive.ubuntu.com/ubuntu/ trusty-updates universe multiverse

I also tried adding the following source, but it didnt help:
 deb-src http://archive.ubuntu.com/ubuntu trusty main universe restricted multiverse

Any ideas?
UPDATE(8/12/2015)
Output of apt-get update:
ubuntu:$ sudo apt-get update
Ign http://us-west-2.ec2.archive.ubuntu.com trusty InRelease
Ign http://us-west-2.ec2.archive.ubuntu.com trusty-updates InRelease
Get:1 http://us-west-2.ec2.archive.ubuntu.com trusty Release.gpg [933 B]
Get:2 http://us-west-2.ec2.archive.ubuntu.com trusty-updates Release.gpg [933 B]
Get:3 http://us-west-2.ec2.archive.ubuntu.com trusty Release [58.5 kB]
Get:4 http://us-west-2.ec2.archive.ubuntu.com trusty-updates Release [63.5 kB]
Get:5 http://us-west-2.ec2.archive.ubuntu.com trusty/main Sources [1,064 kB]
Get:6 http://us-west-2.ec2.archive.ubuntu.com trusty/universe Sources [6,399 kB]
Ign http://archive.ubuntu.com trusty InRelease
Ign http://security.ubuntu.com trusty-security InRelease
Get:7 http://archive.ubuntu.com trusty Release.gpg [933 B]
Get:8 http://security.ubuntu.com trusty-security Release.gpg [933 B]
Ign http://ppa.launchpad.net trusty InRelease
Get:9 http://archive.ubuntu.com trusty Release [58.5 kB]
Get:10 http://security.ubuntu.com trusty-security Release [63.5 kB]
Get:11 http://us-west-2.ec2.archive.ubuntu.com trusty/multiverse Sources [174 kB]
Get:12 http://us-west-2.ec2.archive.ubuntu.com trusty/main amd64 Packages [1,350 kB]
Ign http://ppa.launchpad.net trusty InRelease
Get:13 http://us-west-2.ec2.archive.ubuntu.com trusty/universe amd64 Packages [5,859 kB]
Get:14 http://ppa.launchpad.net trusty Release.gpg [316 B]
Get:15 http://archive.ubuntu.com trusty/main Sources [1,064 kB]
Get:16 http://security.ubuntu.com trusty-security/main Sources [91.1 kB]
Get:17 http://ppa.launchpad.net trusty Release.gpg [316 B]
Get:18 http://security.ubuntu.com trusty-security/universe Sources [29.4 kB]
Get:19 http://ppa.launchpad.net trusty Release [15.1 kB]
Get:20 http://security.ubuntu.com trusty-security/multiverse Sources [2,330 B]
Get:21 http://security.ubuntu.com trusty-security/main amd64 Packages [326 kB]
Get:22 http://archive.ubuntu.com trusty/universe Sources [6,399 kB]
Get:23 http://us-west-2.ec2.archive.ubuntu.com trusty/multiverse amd64 Packages [132 kB]
Get:24 http://us-west-2.ec2.archive.ubuntu.com trusty/main Translation-en [762 kB]
Get:25 http://security.ubuntu.com trusty-security/universe amd64 Packages [113 kB]
Get:26 http://ppa.launchpad.net trusty Release [15.1 kB]
Get:27 http://us-west-2.ec2.archive.ubuntu.com trusty/multiverse Translation-en [102 kB]
Get:28 http://us-west-2.ec2.archive.ubuntu.com trusty/universe Translation-en [4,089 kB]
Get:29 http://security.ubuntu.com trusty-security/multiverse amd64 Packages [3,686 B]
Get:30 http://ppa.launchpad.net trusty/main amd64 Packages [3,019 B]
Get:31 http://security.ubuntu.com trusty-security/main Translation-en [178 kB]
Get:32 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/main Sources [228 kB]
Get:33 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/universe Sources [132 kB]
Get:34 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/multiverse Sources [5,143 B]
Get:35 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/main amd64 Packages [599 kB]
Get:36 http://security.ubuntu.com trusty-security/multiverse Translation-en [1,679 B]
Get:37 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/universe amd64 Packages [302 kB]
Get:38 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/multiverse amd64 Packages [11.9 kB]
Get:39 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/main Translation-en [288 kB]
Get:40 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/multiverse Translation-en [6,148 B]
Get:41 http://us-west-2.ec2.archive.ubuntu.com trusty-updates/universe Translation-en [161 kB]
Get:42 http://ppa.launchpad.net trusty/main Translation-en [2,036 B]
Ign http://us-west-2.ec2.archive.ubuntu.com trusty/main Translation-en_US
Ign http://us-west-2.ec2.archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://us-west-2.ec2.archive.ubuntu.com trusty/universe Translation-en_US
Get:43 http://security.ubuntu.com trusty-security/universe Translation-en [66.3 kB]
Get:44 http://ppa.launchpad.net trusty/main amd64 Packages [705 B]
Get:45 http://ppa.launchpad.net trusty/main Translation-en [464 B]
Get:46 http://archive.ubuntu.com trusty/restricted Sources [5,433 B]
Get:47 http://archive.ubuntu.com trusty/multiverse Sources [174 kB]
Fetched 30.4 MB in 9s (3,333 kB/s)
Reading package lists... Done

Comment: Is this an Amazon EC2 server?
Comment: @A.B. Yes, I am running an EC2 instance
Answer: Use the Ubuntu Main Server.
sudo sed -i.bak 's/us-west-2\.ec2\.//' /etc/apt/sources.list

The command removes us-west-2.ec2. in /etc/apt/sources.list and creates a backup in /etc/apt/sources.list.bak
Comment: Yeah, first thing to try... **;-)**

Unable to locate package libjpeg-dev


How to use a PipedInputStream in a Producer Endpoint in Apache Camel

Question: I am using Camel to consume a huge (GB) file, process/modify some data in the file and finally forward the modified file via an AWS-S3, FTP or SFTP producer endpoint to its target. In the actual usage scenario using an intermediate(temporary) file holding the processed data is not allowed.
In case of the AWS producer, the configure method of the corresponding RouteBuilder specifies the route as follows:
from("file:/...")
    .streamCaching()
    .process(new CustomFileProcessor())
    .to("aws-s3://...");

In it's process(Exchange exchange) method the CustomFileProcessor reads the input data from exchange.getIn().getBody(InputStream.class) and writes the processed and modified data into a PipedOutputStream.
Now the PipedInputStream connected with this PipedOutputStream should be used as the source for the producer sending the data to AWS-S3.
I tried exchange.getOut().setBody(thePipedInputStream) in the process method but this doesn't work and seems to create a deadlock.
So what is the correct way - if it is possible at all - of piping the processed output data of the CustomFileProcessor to the producer endpoint so that the entire data is send over?
Many thanks in advance.
Answer: After further digging into this the solution was quite simple. I only needed to place the pipe reader into a separate thread and the problem was solved.


Decrease the components size of Material UI

Question: I've been trying to figure out a way to decrease the fontSize to all the components set (http://www.material-ui.com/#/components), they are too big for my taste, so I started creating a selectable list and using styles trying to decrease the fonts and sizes but I'm seeing isn't that easy.
I've started with List and ListItem, I was able to reduce all the elements except the rightToggle element, I'm not seeing a way to override its style.
Also I couldn't change the secondaryText font size.
Is there a specific approach to achieve this without to much pain?, I'm seeing there are a lot of "magic" numbers hardcoded for the paddings and positioning, wouldn't be better make them overridable?
Thanks
Comment: A temp workaround I settled on was to use good old external css.
Comment: I agree with using css. It always works.
Answer: Even though MUI uses the inline-style approach, it is a good idea to use a CSS file to provide some global styles. Our MUI project uses a "main.css" file to set anchor color, bg color, and several other attributes that we know will be consistent across the app.


Amazon RDS CPU Utilization due to COUNT query

Question: I have published my website on Amazon EC2 (Singapore region) and I have used MySQL RDS medium instance for data storage in the same region.
In my case, most of the select queries have some COUNT functionality. These queries are showing very slow results. I have already created appropriate indexes on the table and I checked the EXPLAIN command to analyze these queries. It shows me that full table scans are necessary to get results.
On my RDS medium instance, I have configured the custom parameter group with the following settings.
log_queries_not_using_index = true,
slow_query_log = true,
long_query_time = 2 sec,
max_connections = 303,
innodb_buffer_pool_size = {DBInstanceClassMemory*3/4}

Yesterday my CPU utilization went above 95% and my site crashed due to this. There was no major increase in traffic.
Also, I dumped the data on my local system, and tested one of the COUNT queries. While it takes about 1.5 seconds for it to run on RDS, it takes only about 400 milliseconds for it to run on my local system. The configuration on my local system (4GB RAM, Intel core 2 duo 2.8GHz) is:
max_connections = 100,
slow_query_log = true,
long_query_time = 2 sec,
innodb_buffer_pool_size = 72351744

So, what could be the reason for the spike in CPU utilization as well as the difference in performance times between RDS and my local system?
Thanks,
Answer: Depending on the table size - the RDS instance uses EBS to store the data - if you're doing a table scan and its going to have to get the data from EBS instead of a locally cached in-memory key and then scan it.  So - you're likely seeing the increased lag of the network between the RDS instance where the CPU resides and the EBS data in the SAN.  When you do the same query on your local computer the only lag is the disk head seek time.
Then there is the difference between CPU time - an m1.medium has less CPU time (and therefore less opportunity to scan the results) than the core2 duo based on Amazon's definition of EC2 units.
HTH - in general, I'd try to avoid doing COUNT(s) in your queries as this is a terribly inefficient query (as you've seen) which can and will continue to cause nasty undesired results when the DB is under real-time varying levels of load.
R


Is it possible to prevent a file from being deleted unless in safe mode?

Question: Is it possible to make a file only deletable when in safe mode on linux? Specifically I am using ubuntu 14.04 and I need to prevent a file from being deleted.
If this solution is not possible is there another way where it would be difficult for Sudoer's to remove the file?
The only solution I know of is using chattr +i/-i and it is too easy to remove.
Answer: No. The problem you have is that if an admin would not be able to remove a file it would introduce a security risk: someone with malicious intent and access to the system would then be able to install a file on your system even the admin of that system could not remove. A disgruntled admin could have some real fun with that...
Besides attr (that can be easily changed by an admin) you can also start the file with a dot making it invisible for normal commands (ls would need the -a option) making it harder for uneducated people to find and delete it (It will not fool someone who knows that there is a secret file present on the system). Nothing that can prevent deleting the file.
But ...
One method that will work though is to mount the file on a read only encrypted partition. The encryption is needed so "root" can not remount it without knowing the password. Someone could still remove the file when that person is able to remount it writeable and it has no relation to the "only in safe mode" part of your question though. But this seems to be the most practical approach.
Ubuntu also supports encrypted private directories (package ecrypt-utils but there are similar tools like cryptkeeper). But it depends if you need the contents of the file to enforce something or if it is actually the deleting of it that is a concern. To use the file you will need to open the directory with your login and password; it is then also possible to remove the file (so when you are not behind the system you will need to unmount the private directory to prevent deleting; when you are behind the machine and need it you can mount it and unmount it when not needed; limiting the time frame someone can delete it).

I do have one problem with your question: in general you really should trust an administrator to not mess with files. If you can not trust that person remove his access and restrict his account to a normal account with some extra privileges. Making sure you are the only admin is a better and a lot easier method in preventing deletion of that file.
Comment: Nice!  I would just have said: no...
Comment: Not really; since you can get around it by booting into a safe mode, that allows the real admin to do what they need to while preventing a hacker who has compromised the system remotely from doing too much damage.  There has been a lot of work in the area of preventing even root from doing things that can harm the system, for example, SELinux and Apparmor.  I'm pretty sure you can use these to accomplish what the OP wants, but I'm not sure exactly how.
Comment: @psusi selinux and apparmor are not going to stop an admin.
Comment: Like I said, they won't stop a real admin since they can boot the machine into an insecure mode when needed, but their whole point is that they can stop programs from doing things, even if they otherwise would be allowed to by virtue of their uid, and that includes root.  With a sufficiently locked down apparmor or selinux setup, even root can't do things like install a new kernel or format a disk, or as the OP asked, modify certain protected files.


Which upgrades can be unlocked?

Question: As you upgrade, you will unlock new upgrades. Which upgrades can be unlocked – and when?
Answer: This is the list of abilities and upgrades, with when they are unlocked.
You can take a look at this Reddit thread for more information.
Before we begin...
I'm not using scientific notations, because they're plain confusing to compare with metric measurements (which increment in pretty much "every 3 powers of 10")...
k = Kilo = 1,000 (1 x 103)
M = Mega/Million = 1,000,000 (1 x 106)
B = Billion = 1,000,000,000 (1 x 109)
T = Trillion = 1,000,000,000,000 (1 x 1012)
Also base obviously mean "the value at the very start of the game".
Upgrades
Note: Health, Click and Auto-click (DPS) upgrades open up their next tier when the top-most unlocked tier is at Level 10.
Health Upgrades: (Your base health is: 1000)

Tier 1: Light Armor (x1.3 everything per Level)
Tier 2: Heavy Armor (+10k HP/Level)
Tier 3: Energy Shields (+100k HPLevel)
Tier 4: Personal Training (+1M HP/Level)
Tier 5: Cybernetic Enhancements (+10M HP/Level)
Tier 6: Exoskeleton (+100M HP/Level)
Tier 7: Yoga Training (+1B HP/Level)
Tier 8: Protein Shakes (+10B HP/Level)
Tier 9: Martial Arts Training (+100B HP/Level)
Tier 10: Seriously? Another AP Upgrade (+1T HP/Level)

Auto-clicker Upgrades: (Your base is: 10)

Tier 1: Auto-Fire Cannon (+10 DMG/s/Level)
Tier 2: Advanced Targeting (+100 DMG/s/Level)
Tier 3: Farming Equipment (+1k DMG/s/Level)
Tier 4: AFK Equipment (+10k DMG/s/Level)
Tier 5: Level 1 Sentry Gun (+100k DMG/s/Level)
Tier 6: Level 2 Sentry Gun (+1M DMG/s/Level)
Tier 7: Level 3 Sentry Gun (+10M DMG/s/Level)
Tier 8: Level 1 Drones (+100M DMG/s/Level)
Tier 9: Level 2 Drones (+1B DMG/s/Level)
Tier 10: Level 3 Drones (+10B DMG/s/Level)

Click Upgrades: (Your base DPC; damage-per-click is: 10)

Tier 1: Armor Piercing Rounds (+10 DMC/Level)
Tier 2: Explosive Rounds (+100 DMC/Level)
Tier 3: Railgun (+1k DMC/Level)
Tier 4: New Mouse Button (+10k DMC/Level)
Tier 5: Titanium Mouse Button (+100k DMC/Level)
Tier 6: Double-Barreled Mouse (+1M DMC/Level)
Tier 7: Bionic Finger (+10M DMC/Level)
Tier 8: Bionic Hand (+100M DMC/Level)
Tier 9: Bionic Arm (+1B DMC/Level)
Tier 10: [Name Unknown] (+10B DMC/Level)

Miscellaneous Upgrades: (Those that does not belong to an upgrade tree)

Elemental Damage (unlocks at the very beginning)
Lucky Shot (Unlocks when Armor Piercing Rounds is at Level 5)
Boss Loot (Unlocks when Auto-Fire Cannon is at Level 10)

Abilities

Medics (Unlocks when Light Armor is at Level 1)
Good Luck Charm (Unlocks when Armor Piercing Rounds is at Level 5)
Tactical Nuke (Unlocks when Armor Piercing Rounds is at Level 10)
Cluster Bomb (Unlocks when Auto-Fire Cannon is at Level 10)
Napalm (Unlocks when Auto-Fire Cannon is at Level 10)
Morale Booster (Unlocks when Auto-Fire Cannon is at Level 20)
Decrease Cooldown (Unlocks at the start of the game)
Metal Detector (Unlocks at the start of the game)
Comment: Base HP is 1k (1000) if it helps=)  Nice writeup.

Which upgrades can be unlocked?


How to skip empty value in PowerShell script

Question: I have a little script to set displayname in bulk for some user. But some of my users do not have a value like 'Firstname' and 'Lastname' in there objects. I have tried to look for it, but cannot find to skip this users from my script.
$UPNs = Import-Csv -Path "C:\temp\users.csv" -Delimiter ";"

#.UserPrincipalName, means the value of the first row in CSV file
$Users = ForEach($UPN in $UPNs){Get-MsolUser -UserPrincipalName $UPN.UserPrincipalName | Select-Object Userprincipalname,displayname,firstname,lastname}

$Users | ForEach-Object {
    $DisplayName = $_.firstname + " " + $_.lastname + " " + "(Admin Account)"
    set-msoluser -UserPrincipalName $_.userprincipalname -DisplayName $DisplayName
}

How can I made this script to say, "no 'firstname' or 'lastname' -> do not change object"
Many thanks,
Ricardo
Answer: Use the Where-Object cmdlet:
# Filter out users unless both FirstName and LastName has values
$Users |Where-Object {$_.FirstName -and $_.LastName} | ForEach-Object {
    $DisplayName = $_.firstname + " " + $_.lastname + " " + "(Admin Account)"
    set-msoluser -UserPrincipalName $_.userprincipalname -DisplayName $DisplayName
}

Here, we use the -and boolean logic operator to ensure that both $_.FirstName and $_.LastName has a value that is truthy - $null and empty strings will evaluate to $false in a boolean context, strings with any other value will evaluate to $true.
If you also want to skip when either consists of just whitespace, use the static [string]::IsNullOrWhiteSpace() method
# Filter out users unless both FirstName and LastName has non-whitespace-only values
$Users |Where-Object {-not([string]::IsNullOrWhiteSpace($_.FirstName)) -and -not([string]::IsNullOrWhiteSpace($_.LastName))} | ForEach-Object {
    $DisplayName = $_.firstname + " " + $_.lastname + " " + "(Admin Account)"
    set-msoluser -UserPrincipalName $_.userprincipalname -DisplayName $DisplayName
}


Cast String to date time in Stream analytics Query

Question: We are sending datetime as string in the format 2018-03-20 10:50:037.996, and we have written Steam analytics query as below.
<code>SELECT
    powerscout.Device_Id AS PowerScout,
    powerscout.[kW System],
    CAST(powerscout.[TimeStamp] AS datetime) AS [TimeStamp]
INTO
    [PowergridView]
FROM
    [IoTHubIn]
</code>
When we are sending data through Stream analytics, Job is getting failed.
Any Suggestions please.
Thanks In Advance
Answer: ASA can parse DATETIME fields represented in one of the formats described in ISO 8601. This format is not supported. You can try using custom JavaScript function to parse it.


Nuxt-calendly remove cookie setting option

Question: I want to remove the Cookie Settings option in my calendly popup text integration but the option hideGdprBanner does not work.

does anyone have an idea how to remove it? or if it can be removed at all? Thanks!
Answer: You can fix it by adding this to your Calendly URL ?hide_gdpr_banner=1
https://yourdomain.com/endpoint/30min?hide_gdpr_banner=1
https://help.calendly.com/hc/en-us/articles/4418236309399-Calendly-cookie-management-and-banner#h_01FRRNAC7XQRSYDC1MVST35G5E
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/34812574)


What happens if I buy the Battle Pass at level 100 (using the in-game obtained V-Bucks)?

Question: I am a Fortnite Italian player, who's been playing Fortnite for months, since summer 2019, and in this sense I'm a bit of a young player, since we are currently in the twelfth season, the 2nd of Chapter 2. I'm not going to spend any money for Fortnite, but I would like to get the Batte Pass someday, just using the V-Bucks that I get in the game, as I've always (and now I still do) got the rewards from the free battle pass, not being a premium player.
So far, in my 8 months of free Fortnite,  I've earned 800 V-Bucks, and now I'm a level 21 player. At the level 63 and 99 of this season I'll get another 100 V-Buck reward, so totally when I'll be at level 100 I'll reach the good number of 1000 V-Bucks and since the Premium Battle Pass requires 950 of them, I'll be able to get it.
My question is: when in this season I'll reach level 100, and at that point I'll buy the Battle Pass spending 950 V-Bucks, am I gonna get all the Premium Battle Pass rewards of all the previous levels < (and equal to) 100?
In this way, I think, I'd get all the rewards of the season that I didn't get in my Free Battle Pass gaming period, that is, all the rewards excluding the Free rewards, that is, the Premium rewards.
This means that I'd get also the 1500-300= 1200 V-Bucks of the Premium Rewards (since the totality is 1500 of them and the Free Battle Pass V-Bucks are 300), and so in this way I could get straight buy the Premium Battle Pass of the next season that'll come.
And this would also mean that if one buys the Premium Battle Pass once, then he's gonna get back all the V-Bucks that he spent and even more, (1500 per season) so that (if he doesn't spend them in another things) he will always be able to buy the Premium Battle Pass at the beginning of every season, forever. Or at least, if what I know is true.
Am I saying right things or am I wrong?
Answer: Yes, with the Premium Battle Pass you will earn enough V-Bucks to get the next season Premium Battle Pass with those earned V-Bucks.
And yes you will win all the previous levels rewards of Premium Battle Pass, but only for this season.


Econn Reset and Heap memory out of space in node.js client connecting with elasticsearch

Question: I have a code that parses through 70 log files (each file is around 15 mb) . I extract particular fields from the log and send a bulk request to elasticsearch.  Below is the code.
//looks for all the files with .log extension

glob(__dirname + "/../logs/*.log", function (er, files) {
for (var i = 0; i < files.length; i++) {

    lr = new LineByLineReader(files[i]);
    lr.on('error', function (err) {
        console.error(err.stack);
    });

//each line of the file is taken and certain fields are taken from it and pushed into an array
    lr.on('line', function (line) {
        arr = line.replace(/['"]+/g, '').split(" ");
        var jsonArg1 = new Object();
        var temparr = arr[13].split("?");
        jsonArg1.url = temparr[0];
        jsonArg1.method = arr[12];
        pluginArrayArg.push(jsonArg1);
    });
//once the entire file is parsed, the array is pushed into elasticsearch bulk api

    lr.on('end', function () {
        // All lines are read, file is closed now.
        data = (function () {
            var x = '';
            for (var i = 0; i < pluginArrayArg.length; i++) {
                x = x + '{ "index" :  { "_index" : "nodeclient" , "_type": "logs"} }\n' + '{"method" : "' + pluginArrayArg[i].method + '", "url" : "' + pluginArrayArg[i].url + '"}\n';
            }
            return x;
        })();

        client.bulk({
            body: [
                    data
                    ]
        }, function (err, resp) {
            if (err) {
                console.log(err);
            }
            console.log(resp);
            //console.log(JSON.stringify(resp));
        });
    });
    }
});

The code is executing fine for around 7 to 8 log files, after that i start getting the below error repeatedly
Elasticsearch ERROR: 2016-10-28T21:09:21Z
  Error: Request error, retrying
  POST http:/localhost:9200/_bulk => read ECONNRESET
      at Log.error (/home/apitestcoverage/apicoverage_node/node_modules/elasticsearch/src/lib/log.js:225:56)
      at checkRespForFailure (/home/apitestcoverage/apicoverage_node/node_modules/elasticsearch/src/lib/transport.js:240:18)
      at HttpConnector.<anonymous> (/home/apitestcoverage/apicoverage_node/node_modules/elasticsearch/src/lib/connectors/http.js:162:7)
      at ClientRequest.wrapper (/home/apitestcoverage/apicoverage_node/node_modules/lodash/index.js:3095:19)
      at emitOne (events.js:96:13)
      at ClientRequest.emit (events.js:188:7)
      at Socket.socketErrorListener (_http_client.js:308:9)
      at emitOne (events.js:96:13)
      at Socket.emit (events.js:188:7)
      at emitErrorNT (net.js:1271:8)

then finally the below fatal erorr heap out of space error message appears and then it exits
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

I have tried increasing the heap space in command line like below and still doesn't work
node --max_old_space_size=4096 server.js
searching about each of these errors seperately, people speak about  increasing maxSockets and reusing the pooled connections. I have no idea on doing these changes to my code.
how should i proceed to solve these errors ? are both of these errors correlated ?
Answer: I was just getting econnreset errors using my custom bulk insert script to batch many 25-40mb files.
I increased the memory on the virtual box installation from 4mb to about 8mb and I no longer have the issue.


What is the most important component for the airtightness of a room?

Question:
I have looked at the UK building regulations and it says that timberframe cavities should be airtight to a minimum of 0.6 changes. This is for new builds, not renovations which is my case.
Looking online this is normally achieved with several things:

Vapor barrier membrane fitted correctly
Good timberframee construction
Insulation (PIR or Glasswool)
Seals (tape or foam)

As a DIYer who might make mistakes.
What should be the focus when building an internal studwork to make sure it is not too draughty?
Do I just get all the components fitted well and then focus on the vapor barrier membrane?
Also - is thermal (foil) tape better than expanding foam for sealing joints in insulation boards (PIR)? The internet does not provide a conclusive answer.
Comment: Expanding foam is horrible stuff for a host of reasons, so the answer is most likely "yes".
Comment: For a *room* that's the inside of the envelope: the paint on the wall. For the entire structure, that's air-sealing, which is spray foam *or go home*. For studwork: caulk any laminated members. add insulation anywhere the spray foam guys won't be able to get to, like where four corners of four rooms meet and there's a 4"x4" dead zone in there.
Comment: In the UK we use expanding foam for sealing around a window frame, not sure what alternative there is apart from layers and layers of mastic
Answer: If building to certain standards then the use of expanding foam is not allowed. Built to those standards...
So we used a wood based insulation with the same heat retaining properties as other common insulation. Actually the wood based insulation was the same price but much easier to handle with less dust and much less irritation.
So, Fitting the vapour barrier is most important - think of it this way: if you turn the building upside down, will it hold water?
Comment: As in you're not allowed to use expanding foam to seal gaps around windows, timber, etc?
Comment: @tomaytotomato that is what "not allowed" means. The vapour barrier is sealed to the window frame anyway.


Moving back in Python filestream

Question: I am trying to write a compiler and read in a file one character at a time. If I were to find "/" followed by another "/" then I want to interpret the rest of my line as a comment. I am using file.read(1) each time I want another character. However, if I see that I have "/" followed by something that is not a "/" is there any way I can move the file stream back one character so as to not lose that character?
def tokenType(self):
    # PAGE 108
    if (self.current == '{' or self.current == '}'  or self.current == '('  or self.current == ')'  or self.current == '['  or self.current == ']'  or self.current == '.'  or self.current == ','  or self.current == ';'  or self.current == '-'  or self.current == '*'  or self.current == '/'  or self.current == '&'  or self.current == '|'  or self.current == '<'  or self.current == '>'  or self.current == '='  or self.current == '~'):
        if (self.current == '/'):
            next = self.file.read(1)
            if (next == '/'):
                while (next != "\n"):
                    next = self.file.read(1)
                return "IGNORE"
            if (next == '*'):
                while (True):
                    next = self.file.read(1)
                    if (next == '*'):
                        next = self.file.read(1)
                        if (next == '/'):
                            break
                return "IGNORE"
            else:
                return "SYMBOL"
        return "SYMBOL"
    elif (self.current == " " or self.current == "\n"):
        return "IGNORE"
    elif (self.current == "'"):
        while(next != "'"):
            self.current = self.current + next
        return "STRING_CONST"
    elif (type(self.current) == int):
        next = self.file.read(1)
        while(next != " "):
            self.current = self.current + next
        return "INT_CONST"
    else:
        next = self.file.read(1)
        while(next != " " and next != ""):
            self.current = self.current + next
            next = self.file.read(1)
        if (self.current == 'class' or self.current == 'constructor'  or self.current == 'function'  or self.current == 'method'  or self.current == 'field'  or self.current == 'static'  or self.current == 'var'  or self.current == 'int'  or self.current == 'char'  or self.current == 'boolean'  or self.current == 'void'  or self.current == 'true'  or self.current == 'false'  or self.current == 'null'  or self.current == 'this'  or self.current == 'let'  or self.current == 'do'  or self.current == 'if' or self.current == 'else'  or self.current == 'while'  or self.current == 'return'):
            return "KEYWORD"
        else:
            return "IDENTIFIER"

My problem seems to be when I have something like 10/5 and my program checks to see if the next character is a "/". Then on the next pass through my character interpreting function, the 5 has already been removed when it was checking for a comment.
So, is there any way I can get a character from a file stream without it being "removed" from the stream or is there a way I can move it back a character when I hit a case like this?
Comment: `self.file.seek(-1, 1)` for moving -1 from current position.
Comment: `file.seek` works, but I question your strategy of reading one character at a time.  You need to do more research on lexing in order to tokenize your input into more meaningful chunks.
Comment: Please show a relevant code fragment.
Answer: It's not pretty, but you could pass the current and next symbol into your function if you don't mind reading the entire file into memory.  You would only need some way to track ignoring the next character.
data = open('input_file').read()

for first, second in zip(data, data[1:]):
    tokenType(first, second)

But like roippi says, there are better ways to lex input.

Moving back in Python filestream


Show that if $n>0$, then there exists $x$ such that $\tau (nx) = n$.

Question:
Show that if $n>0$, then there exists $x$ such that $\tau (nx) = n$.

Note: $\tau (a)$ is the number of divisors of $a$.
I tried working with the prime factorization of the numbers in the equation but that did not get me anywhere.
Comment: @vonbrand $\tau (10*1) \neq 10$ ?
Comment: $x=1$ works (trivially)...
Answer: Since $n>0$ we have that $n=p_1^{a_1}\cdot p_2^{a_2}\cdot\ldots\cdot p_k^{a_k}$, for some non-negative integer $k$, distinct primes $p_1,\ldots,p_k$, and some positive integers $a_1,\ldots,a_k$.
Let $x$ be defined as follows:
$$x=p_1^{p_1^{a_1}-a_1-1}\cdot p_2^{p_2^{a_2}-a_2-1}\cdot\ldots\cdot p_k^{p_k^{a_k}-a_k-1}.$$
Note that $x$ will be a positive integer since for each positive integer $m$ and each prime $p$ we have that $p^m-1\ge m$, with equality holding iff $p=2$ and $m=1$. And we also have the following:
$$\begin{align*}
\tau(n\cdot x) &= \tau\left(p_1^{a_1}\cdot p_2^{a_2}\cdot\ldots\cdot p_k^{a_k}\cdot p_1^{p_1^{a_1}-a_1-1}\cdot p_2^{p_2^{a_2}-a_2-1}\cdot\ldots\cdot p_k^{p_k^{a_k}-a_k-1}\right) \\
&= \tau\left(p_1^{p_1^{a_1}-1}\cdot p_2^{p_2^{a_2}-1}\cdot\ldots\cdot p_k^{p_k^{a_k}-1}\right) \\
&= p_1^{a_1}\cdot p_2^{a_2}\cdot\ldots\cdot p_k^{a_k} \\
&= n
\end{align*}$$
Answer: To find a multiple of $n$ with exactly $n$ divisors, simply replace each prime power $p^a$ in the factorization of $n$ with $p^{p^a-1}$.


How to install Fogger?

Question: I Want to know that how to install Fogger application, which Interact with different web accounts including Facebook on Ubuntu 13.10.
In main Ubuntu repository, it is only available for Ubuntu 12.10
How to install it ?
Answer: Fogger can be installed with Launchpad repository ppa:loneowais/fogger
<code>sudo add-apt-repository ppa:loneowais/fogger

sudo apt-get update

sudo apt-get install fogger
</code>

How to install Fogger?


How to hide sub-total and total rows in the pivot table of Atoti visualization?

Question: I would like to hide the sub-total and total row from pivot table. Is that possible? How?
Answer: Disclaimer: I work on atoti.
There is no feature in the UI to hide the grand total and the sub totals yet. In the meantime, you can change the MDX query stored in the state of your widget.
Here for instance, your MDX should contain something like:
Crossjoin(Hierarchize(Descendants({[SomeDimensionName].[CUSTOMERS].[AllMember]}, 1, SELF_AND_BEFORE)), Hierarchize(Descendants({[SomeDimensionName].[S_MAX_DEGRAD].[AllMember]}, 1, SELF_AND_BEFORE)))

adapt it like that:
Crossjoin([SomeDimensionName].[CUSTOMERS].[CUSTOMERS].Members, [SomeDimensionName].[S_MAX_DEGRAD].[S_MAX_DEGRAD].Members)

and the totals will be gone.


When doing electrical work, what do I use to check wires are safe?

Question: If I am thinking of replacing a light switch, a light-fitting, a socket/outlet or doing other work with household wiring where there may be 120 Volts or 240 volts present ...
There is already a question on "what should I have done differently [to avoid electric shock]" which is mostly about procedures but ...
what types of tools are available for testing that wires are safe and, as an average householder, which type of tool should I buy to help avoid electrocution?
Answer: Test Tools
In approximate descending order of safety (though the professional multimeter could arguably be higher if you are careful about how you use it)
Voltage tester
A professional electrician would very likely have one of these:

If you expect to do occasional DIY electrical work in the rest of your life, you should consider buying something like this.

It does not make you part of the circuit.
It has no knobs or switches that can accidentally be left in the wrong position.
It has no removable leads that can be accidentally left in the wrong socket.
it can easily be used with two hands (more so than a typical multimeter)
It will operate without batteries.
It is relatively inexpensive (<£25 in UK).
It is a major brand - so the design can be expected to incorporate high standards for safety and reliability.
It will likely last the rest of your life.

If money is an issue you can get cheaper versions of the above as shop-brand items (e.g. cheapest CPC/Farnell "Tenma" branded device <£8), this is what I use now.

2-in-1 tester
At the cheapest extreme you might consider one of these instead:

It does not make you part of the test circuit
It will work without batteries
Cheap (~ £4 from eBay vendors)

It does have some disadvantages

It is very cheaply made.
The LED indicators are a bit dim and hard to see, especially at lower voltages.

I'm not sure I trust it fully. It is certainly safer, and a better buy, than a "voltage test screwdriver" (see below).

Non-Contact Voltage (NCV) detector
Sometimes called a "voltage detector pen" or just "voltage detector"

This type of detector is widely used for the following reasons

Inexpensive (the one pictured is more expensive as it also detects current).
No contact with wiring needed.

So does not make you part of the circuit.

few or no controls to set (so fewer mistakes possible)

It has some disadvantages

Can be misleading and "detect" voltage several inches (or more) from the wires
Not very good for detecting which specific wire is live in a cable
Battery required
Can be fiddly to verify correct operation.

The one I have has a thumb-wheel that has to be turned to set the sensitivity, you need to do this each time you use it and a consequence is that the test result isn't necessarily as clear and distinct as the other types of tester.
Some electricians say that NCV detectors are good for an initial test but that, for safety, you should follow up with a contact based voltage detector like the one at the top of this answer.
See Is a negative reading from a non-contact voltage detector sufficient?

Multimeter (professional)
I have several of these bought cheaply from eBay (around £70).

Advantages:

It is credibly Cat-II rated .
The leads are also Cat-II rated.
It has a four-socket design, so current measurements are physically separated from voltage measurements.
It contains a good HRC fuse (two actually).
It has lots of other protections (MOVs etc).
The case is sufficiently well-designed and made to contain the small electrical explosions that might occur when you make a bad mistake.

Hold
A nice feature with this meter is that the "Hold" button is a true hold and not a mere "data hold". This is useful for those of use with fewer than three arms.
With a true hold, you can put the multimeter on the floor (or hang it nearby), press the hold button, then take a probe in each hand and make the measurement without looking at the meter display, you stop taking the measurement when the meter beeps, you take your hands away from the wiring then look at the meter to see what value it shows.
With a "data hold", you have to use a third hand and your other set of eyes to press the hold button during the reading. In practice it can mean using one hand to hold both probes, looking away from what your hands are doing near the wiring (dangerous) and pressing the hold button.
So the former (rarer) type of "hold" is useful, the latter not.
Low-Z
A problem using multimeters to test for voltage is that they typically have high impedance, typically 10 MΩ and can pick up "ghost voltages". These are induced voltages caused by proximity of wires. They are not dangerous voltages as no significant current can be supplied inductively in typical household wiring. Some meters have a Low-Z setting designed to prevent this measurement artifact.
Disadvantages
Like all multimeters it has some significant disadvantages

You can accidentally try to measure volts with the leads plugged into the current sockets (some meters have a jack-alert feature to warn about this)
You can accidentally try to measure volts with the knob set to the wrong range (perhaps making you think wires are safe when they are not)

Multimeter (cheap)
I have several of these type of cheap multimeters

Even though this one is apparently rated Cat-II I prefer not to use it to test for 120V/240V. Because

The case is not designed to contain electric arcs.
The fuse is a cheap fuse not a high rupture capacity fuse.
It has a 3-socket design. The same socket is used for volts and current.

All these things mean more likelihood of unpleasant injury when you make a mistake.

Voltage Test Screwdriver
Most folk have one of these

The bottom type contains only a small 1/4W resistor and a neon indicator.
The top type is battery powered and can be used for a variety of purposes: mains voltage, continuity test, finding the break in a cable, etc.

Both of them are fundamentally unsafe because

They make you part of the 120V/240V test circuit.

This is bad. Even though they are cheap and millions of people use them. Buy the 2-in-1 tester if money is an issue.

Test Tools Summary
Use a reputable simple voltage-tester, a really decent multimeter or a 2-in-1 type tester. An NCV detector is useful for initial tests but be careful not to rely on it too much. Don't use a tester that makes you part of the circuit and don't use a cheap multimeter.

Other Tools
Most DIYers own ordinary screwdrivers, pliers, wire-cutters and strippers. It can be safer to buy insulated tools intended to protect you when working on 120V/240V AC electrical wiring.
There are different standards bodies which makers test their products against. In Europe it is normal to look for VDE rated tools. In the US I guess the equivalent is UL. This should be stamped on the tool (but be wary of cheap unbranded or off-brand tools made in countries that have a poor record for faking such marks)
Insulated screwdriver

Often a low-cost set of these will include a voltage test screwdriver (see above) which I suggest be discarded.
Insulated wire-cutter/stripper

Note that this one combines wire-cutting and insulation-stripping features
Insulated Pliers

Note that the insulation is rated for 1000 volts and that the handles have protruding guards to help stop your fingers slipping onto the metal conductive parts.

Electrical test tool categories
Test equipment is rated and marked as Cat-II etc -

So Cat-II is OK for most electrical work around the home - changing light-fittings, light-switches and sockets/outlets. For working inside the main electrical panel, or near to it, Cat-III would be more appropriate.

Techniques
See Electric shock - was I stupid, unlucky, or a combination of both?
The main principles are

turn off the circuit using the circuit-breaker at the main electrical panel. It is prudent to mark, tape or even lock the circuit breaker switch so that someone else doesn't switch it back on while you are working on the wiring.
keep your hands away from bare metal (wires etc). This is why good probes have prominent finger-guards and probe-tip shields.
check and recheck that your test equipment

leads are plugged into appropriate sockets
knobs are set to appropriate ranges
other features of the test equipment are set appropriately

After a test confirms a wire is dead, check the equipment has not just now failed. Test it on a known live source before proceeding to handle the wiring.

The third point above is why multimeters are not an ideal tester for 120V/240V work.
Comment: Man, above and beyond on this one.  Great question and answer.
Comment: I'm curious how you'd categorize [this](http://www.homedepot.com/p/Klein-Tools-Digital-Multimeter-MM1000/202521270) one.  I bought it to test my A/C unit's run-start capacitor but have since used it to test if wires are safe.  It hasn't failed me yet but maybe I'm just lucky.
Comment: I wouldn't even recommend a non-contact voltage tester. The scenarios they are useful in are a subset of the areas a voltage tester/multimeter are useful in, and to do a lot of work you need test/multimeter anyway. (When you have 4 runs entering a junction box and you need to determine which are hot, if your neutrals are okay, blah blah, you just need to make contact with them.)
Comment: Great Answer.  I would consider adding something about locking out a circuit breaker panel to prevent someone from turning a breaker back on while you are doing your work.
Comment: The 'professional' meter looks like a fluke 77 IV, which should be Cat IV, not Cat II. Cat II should not be used on any installation wiring, generally.
Comment: I see you included a pair of stripper pliers. If the OP is going to do a lot of wiring, I highly suggest getting a [*"catapult" wire stripper*](https://www.google.com/search?q=katapult+wire+stripper&biw=1024&bih=639&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiPm939xcbMAhWBKCYKHU1_CcwQ_AUICCgD) ; they're also much less likely to nick the wire.
Comment: @SomeoneSomewhere: I have updated the answer to cover what is meant by Cat-II, Cat-III etc.
Answer: RedGrittyBrick has an excellent description of tools. I would like to add some more to the topic of procedures.
Whichever tool you choose, use it in the way that gives the most assurances that the result is accurate, and then still act as though the circuit is hot.

Test with the power on to verify that your tool is working.
Test with the power off to verify that the power is off.

When you are first learning to use the test tool it is a good idea to test turning the power on and off and testing each time to build confidence that when you turn the power off you always get a negative result and when you turn the power on you always get a positive result. Reduce the chance that errors in your procedure are contributing to a false confidence.
Don't make any assumptions about how the house is wired or about the safety of your surroundings.
Buy a good tool and learn it well, and tell other people what you are doing.
Comment: Good points, all of them. In particular, with a two-contact tester, *don't just test for voltage between the live and neutral wires.* This can produce a false negative if, say, the live wire is still live but the neutral has been disconnected. Also check that there's no voltage between live and ground, neutral and ground (might happen due to a miswiring, e.g. if live and neutral are swapped), or between any of the wires and any nearby conductive objects. And preferably, also double-check with a contactless tester just to be sure.
Answer: Take a hint from how power company electricians approach (literally) this situation: if you think you're very sure that the power is off, then there should be no danger from attaching[2] a (higher rated [1]) grounded conductor to the circuit in question [3].
[1] The ground "strap" must be of higher rated amperage than the (circuit breakers, conductor rating, etc.)
[2] If you actually do this you should be wearing the appropriate safety equipment.
[3] In a normal residential wiring situation the risk is lower since most circuits will only have a 15 or 20 amp breaker. The arc produced by shorting a live circuit is fairly small (albeit still a bit of a shock (pun intended).
Comment: This seems like dangerous advise to give to DIYers.
Comment: What is the correct PPE for working on 120v wiring?


Gernerationg XML With JAX-RS

Question: I want to generate follpwing xml format
<order_history>
    <order store_id="SSO">
            <attribute name="store_label">SSO Store</attribute>
            <attribute name="order_id">7039012</attribute>
            <attribute name="status">Shipped</attribute>
            <attribute name="total">11.76</attribute>
            <attribute name="description"/>
            <attribute name="tracking_num"/>
            <attribute name="lineItemCount">ssolineItemCount</attribute>
            <attribute name="tracking_href"/>
            <attribute name="submitted_date">11/19/2015</attribute>
            <attribute name="sort_date">1448316686906</attribute>
            <attribute name="detail_url">http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039011</attribute>

    </order>
<order_history>

With the following mapping class:
order.java
@XmlRootElement
public class Order {

    @XmlAttribute(name="store_id")
    private String store_id="SSO";

    @XmlAttribute
    private String store_label;
    @XmlAttribute
    private int order_id;
    @XmlAttribute
    private String status;
    @XmlAttribute
    private double total;
    @XmlAttribute
    private String description;
    @XmlAttribute
    private int tracking_num;
    @XmlAttribute
    private String lineItemCount;
    @XmlAttribute
    private String tracking_href;
    @XmlAttribute
    private String submitted_date;
    @XmlAttribute
    private int sort_date;
    @XmlAttribute
    private String detail_url;

    public String getStore_label() {
        return store_label;
    }
    public void setStore_label(String store_label) {
        this.store_label = store_label;
    }
    public int getOrder_id() {
        return order_id;
    }
    public void setOrder_id(int order_id) {
        this.order_id = order_id;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public double getTotal() {
        return total;
    }
    public void setTotal(double total) {
        this.total = total;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public int getTracking_num() {
        return tracking_num;
    }
    public void setTracking_num(int tracking_num) {
        this.tracking_num = tracking_num;
    }
    public String getLineItemCount() {
        return lineItemCount;
    }
    public void setLineItemCount(String lineItemCount) {
        this.lineItemCount = lineItemCount;
    }
    public String getTracking_href() {
        return tracking_href;
    }
    public void setTracking_href(String tracking_href) {
        this.tracking_href = tracking_href;
    }
    public String getSubmitted_date() {
        return submitted_date;
    }
    public void setSubmitted_date(String submitted_date) {
        this.submitted_date = submitted_date;
    }
    public int getSort_date() {
        return sort_date;
    }
    public void setSort_date(int sort_date) {
        this.sort_date = sort_date;
    }
    public String getDetail_url() {
        return detail_url;
    }
    public void setDetail_url(String detail_url) {
        this.detail_url = detail_url;
    }

OrderHistort.java
@XmlRootElement
public class OrderHistory {

    List<Order> orders = new ArrayList<Order>();

    public List<Order> getOrders() {
        return orders;
    }

    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }

With these two classes ia m able to generate following xml:
<order_history>
    <order store_id="SSO">
            <store_label>SSO Store</store_label>
            <order_id>7039012</order_id>
            <status>Shipped</status>
            <total>11.76</total>
            <description>desc</description>
            <tracking_num>12234</tracking_num>
            <lineItemCount>ssolineItemCount</lineItemCount>
            <tracking_href"/>wwww.abc.com</tracking_href>
            <submitted_date>11/19/2015</submitted_date>
            <sort_date>1448316686906</sort_date>
            <detail_url>http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039011</detail_url>

    </order>

</order_history>

Can anybody help me out in getting desired format with
Thanks
Comment: My Correct Order.java is:
Answer: My Order.java class
 @XmlAttribute(name="store_id")
        private String store_id="SSO";

        private String store_label;
        private int order_id;
        private String status;
        private double total;
        private String description;
        private int tracking_num;
        private String lineItemCount;
        private String tracking_href;
        private String submitted_date;
        private int sort_date;
        private String detail_url;

        public String getStore_label() {
            return store_label;
        }
        public void setStore_label(String store_label) {
            this.store_label = store_label;
        }
        public int getOrder_id() {
            return order_id;
        }
        public void setOrder_id(int order_id) {
            this.order_id = order_id;
        }
        public String getStatus() {
            return status;
        }
        public void setStatus(String status) {
            this.status = status;
        }
        public double getTotal() {
            return total;
        }
        public void setTotal(double total) {
            this.total = total;
        }
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
        public int getTracking_num() {
            return tracking_num;
        }
        public void setTracking_num(int tracking_num) {
            this.tracking_num = tracking_num;
        }
        public String getLineItemCount() {
            return lineItemCount;
        }
        public void setLineItemCount(String lineItemCount) {
            this.lineItemCount = lineItemCount;
        }
        public String getTracking_href() {
            return tracking_href;
        }
        public void setTracking_href(String tracking_href) {
            this.tracking_href = tracking_href;
        }
        public String getSubmitted_date() {
            return submitted_date;
        }
        public void setSubmitted_date(String submitted_date) {
            this.submitted_date = submitted_date;
        }
        public int getSort_date() {
            return sort_date;
        }
        public void setSort_date(int sort_date) {
            this.sort_date = sort_date;
        }
        public String getDetail_url() {
            return detail_url;
        }
        public void setDetail_url(String detail_url) {
            this.detail_url = detail_url;
        }

Comment: i tried with first Order.java but result not achieved but with second Order.java i achieved but without  in xml.I want  with each order field.
Comment: Can anybody give me at least any idea if possible.Its been a long time to post it.

Gernerationg XML With JAX-RS


Extract Only Specific Files with Azure Data Factory

Question: I have to extract only "daily" files from a folder in my C: drive into azure data factory but there are "weekly" files that I don't want to extract. Also, I can't separate the two files in different onprem folders. I have to do this for a client but first I'm practicing on my own computer. Here is the onprem folder that I'm referring to. So the ultimate goal is to only transfer the "daily" files out of the folder and into azure data factory
Comment: you can also use get metadata activity to get files name and the filer the file names by using filter activity.
Comment: [tag:azure-pipelines] is for a specific offering that is **not** related to data factory. Please review tag summaries to ensure you're applying appropriate tags to your questions.
Comment: use a wildcard (daily*) since the naming convention tells you what type of file it is.
Answer: As suggested by @Scott Mildenberger in comments as your files have similar naming convention you can use wildcard file path to filter files with name.

Sample data

Dataset settings

Source Setting

In file path type select wildcard file path  and give daily* It will filter all the files from folder with files contains daily.

Output


How to remove existing sessions by specific principal name

Question: I'm using Spring Session 1.3.0 with Redis backend in my project.
I have an use case that the super admin might update the roles of existing user who might already logged in. I want to delete the existing session records for those users after changing their roles.
Is there API of Spring Session to archive it?
Answer: <code>    @Autowired
    private SessionRegistry sessionRegistry;

    public void expireUserSessions(String username) {
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            if (principal instanceof User) {
                UserDetails userDetails = (UserDetails) principal;
                if (userDetails.getUsername().equals(username)) {
                    for (SessionInformation information : sessionRegistry.getAllSessions(userDetails, true)) {
                        information.expireNow();
                    }
                }
            }
        }
    }
</code>
Answer: Also work out another way to clean sessions of specific user,
<code>@Autowired
FindByIndexNameSessionRepository sessionRepository;

sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
                username).keySet().forEach(session -> sessionRepository.delete((String) session));
</code>
Comment: Deleting sessions prematurely  has some side effects if you allow multiple sessions of a single user. Have a look on this question.
http://stackoverflow.com/questions/22370819/how-to-log-a-user-out-programmatically-using-spring-security
Comment: @mirmdasif it's an interesting finding. I'm wondering why spring/spring security still gives the permission of request with invalid session id(expired or removed).


httptest.NewRequest issues with query parameters

Question: I'm using the GIN framework with a Postgres DB and GORM as an ORM.
One of the routes accepts query parameters. When I search for this in my browser, I get the expected results: an array of json objects. Here is the route:
/artworks/?limit=10&last_id=1
However, when I try to test the handler used by that route, I get the following error:
routes_test.go:184: [ERROR] Unable to unmarshal data to artworks: json: cannot unmarshal object into Go value of type []models.Artwork
The query that the ORM is trying to run in the test function is the folowing:
SELECT * FROM "artwork_migrate_artwork" WHERE id = ''
So when I run the request in the browser, it properly pulls the query parameters and then the ORM runs the proper sql query. But when using httptest.NewRequest it seems like the query parameters are not used.
Here is my test function:
func TestGetArtworks(t *testing.T) {
    dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=%s", env_var.Host, env_var.User, env_var.Password, env_var.DBname, env_var.Port, env_var.SSLMODE, env_var.TimeZone)
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect to db")
    }

    route := "/artworks/"
    handler := handlers.GetArtwork(db)
    router := setupGetRouter(handler, route)
    writer := httptest.NewRecorder()
    req := httptest.NewRequest(http.MethodGet, "/artworks/?limit=10&last_id=1", nil)
    fmt.Println(req)
    router.ServeHTTP(writer, req)

    assert.Equal(t, 200, writer.Code)

    data, err := ioutil.ReadAll(writer.Body)
    if err != nil {
        t.Errorf("\u001b[31m[Error] Unable to read writer.Body: %s", err)
    }

    // no body can be unmarshalled
    fmt.Println("Here is the body:", writer.Body.String())

    var artworks []models.Artwork
    if err := json.Unmarshal(data, &artworks); err != nil {
        t.Errorf("\u001b[31m[ERROR] Unable to unmarshal data to artworks: %s", err)
    }

    assert.Equal(t, 10, len(artworks))
}

Here is my route handler:
func GetArtworks(db *gorm.DB) gin.HandlerFunc {
    return func(c *gin.Context) {
        limit, err := strconv.Atoi(c.Query("limit"))
        if err != nil {
            panic(err)
        }
        last_id := c.Query("last_id")

        var artworks []models.Artwork
        db.Where("id > ?", last_id).Limit(limit).Find(&artworks)

        c.JSON(http.StatusOK, artworks)
    }
}
router.GET("/artworks", han.GetArtworks(db))

Here is the model struct:
type Artwork struct {
    ID              int       `json:"id"`
    Title           string    `json:"title"`
    Nationality     string    `json:"nationality"`
    Artist_Bio      string    `json:"artist_bio"`
    Desc            string    `json:"desc"`
    Culture         string    `json:"culture"`
    Gender          string    `json:"gender"`
    Nation          string    `json:"nation"`
    Medium          string    `json:"medium"`
    Date_of_Release string    `json:"date_of_release"`
    Image           string    `json:"image"`
    Image_Small     string    `json:"image_small"`
    Last_Modified   time.Time `json:"last_modified"`
    Artist_ID       int       `json:"artist_id"`
    Source_ID       int       `json:"source_id"`
}

Comment: The error has nothing at all to do with query parameters. The problem is that you're trying to unmarshal a JSON object (`{...}`) into a Go slice `[]models.Artwork`.
Comment: I think you could reduce lots of boilerplate to ask that question. If I understand correctly, your code just fails to unmarshal the request data. The error suggests that you expect a list of `Artwork`, i.e. a json structure like `[ {"id": 2, "title": "mytitle", ...]`, but the `request` data holds a signle json object (without the wrapping `[ ]` forming a list).
Comment: If I were you, I'd add something like `fmt.Println(string(data))` to your test right before the `json.Unmarshal()` call, and paste the output here so we can see what the response body actually looks like. Based on the error message, the response body most likely is a single JSON object, rather than a JSON array. You need the data to look like this: `[{}, {}]` whereas it probably looks like this: `{}`
Comment: Looks like a typo to me. You are using `handler := handlers.GetArtwork(db)` but I suspect you meant to call `handler := handlers.GetArtworks(db)` (note the extra `s` at the end). If that is not your issue then please provide a [minimal example like this](https://go.dev/play/p/THwOyn8HfJI).
Comment: Thank you for the responses. Let me try to clarify the issue. I know that I'm only getting a single object in the test func. When I use a browser, I get an array of objects, as expected. The handler writes a sql query with the query params and properly returns an array of objects when the browser is used.

When I'm using the httptest.NewRequest in my test function however, it fails to write the query properly because it doesn't use the query parameters. Why would the query params be used when sent over the browser but not test?

Thank you again for your responses and for bearing with me!
Comment: @CampbellPadgett please accept your submitted answer so other knows the problem is solved.
Answer: @Brits is correct: It was due to a misspelled handler
handler := handlers.GetArtwork(db)
should have been handler := handlers.GetArtworks(db)


Click not working on RecyclerView in CoordinatorLayout when scrolling

Question: I am facing a strange behaviour with a RecyclerView as a second child of CoordinatorLayout, just after an AppBarLayout (as described in a lot of examples).
My problem is when I scroll the recycler view and I want to click on a particular item. Sometimes I need to click 2 times to select that item, it seems to be linked to the fling behaviour. For example, if I scrolled to the bottom of the recycler view, then if I fling my finger from the bottom of the screen to the top (in order to see more data, but in my case I can't see more data since I am already to the bottom) and then quickly click on an item, it seems to stop the fling, and the second click actually select the item...
This behaviour is clearly not happening when using a simple recycler view without CoordinatorLayout.
My recyclerview is just holding a simple list of String, and using the following layout behaviour : @string/appbar_scrolling_view_behavior
Do you have any idea why ?
[EDIT]
I just tried with the Android Studio sample Scrolling Activity, and it looks like it is a bug from Google support repository.
In fact, when using support version 26.1.O (same with 26.0.0 and 26.0.2), the bug I am talking about is present, but if you try with the version 26.0.0-alpha1 or 26.0.0-beta1, it is actually working...
There is two open bugs at Google about this :
https://issuetracker.google.com/u/1/issues/66996774
https://issuetracker.google.com/u/1/issues/68077101
Please star these bugs if you are facing the same problem
Answer: Google just posted a workaround for this bug, it will be publicly released later.
https://gist.github.com/chrisbanes/8391b5adb9ee42180893300850ed02f2
Comment: Its really helpful
Comment: @gxela Is it publicly released now??
Answer: If Using RecyclerView in NestedScrollView add this line to RecyclerView :
android:nestedScrollingEnabled="false"

I hope it help you.
Answer: I also found this problem ... after wasting so many hours searching and trying different things, I came out with a trick, its not pretty but it could work for someone else too.
Basically the idea is simulate a click on the nestedScrollView.
In my case after I detect the 'AppBarLayout' its fully expanded, I send a tap to the nested.
protected void onCreate(final Bundle savedInstanceState) {

    getAppBarLayout().addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {

      @Override
      public void onOffsetChanged(final AppBarLayout appBarLayout, final int verticalOffset) {

          if (verticalOffset == 0) {
              // State.EXPANDED
              simulatedClick(nestedScroll)
          } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
              // State.COLLAPSED
          } else {
              // State.IDLE
          }
      }
  });
}

private void simulatedClick(@NonNull final View view) {
    // Obtain MotionEvent object
    final long downTime = SystemClock.uptimeMillis();
    final long eventTime = SystemClock.uptimeMillis() + 100;
    final MotionEvent motionEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, 0.0f, 0.0f, 0);
    // Dispatch touch event to view
    view.dispatchTouchEvent(motionEvent);
}

NOTE: I don't really recommend the use of hacks like this, it's unprofessional and unmaintainable, but the more you know...
Comment: simulatedClick(nestedScroll) ?? what is nestedScroll?? How do u get that??


Calculate time difference in hh:mm:ss with simple javascript/jquery

Question: I have two input field for the time start and time end and there is another field for the difference which is the Call Duration. I want the result on the field to be in this format = 00:21:03

  Start of Call
  <input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">

  End of Call
  <input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">

  Call Duration
  <input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8">

I am having a hardtime getting the result due to the "AM/PM" formatting.
I have found a similar question like this but he is using "momentjs". As much as possible, I don't want to use any plugins, just a plain javascript or from jquery will do. This is the code I got working, I am getting the result (0:21:3) but I need it to be two digits for hours, minutes, and seconds (00:21:03).
$("#form_qa_endcall").on('keyup',function(){
  var callStart = $('#form_qa_startcall').val();
  var callEnd = $('#form_qa_endcall').val();
  var timeStart = new Date("01/01/2007 " + callStart);
  var timeEnd = new Date("01/01/2007 " + callEnd);

    function datediff(fromDate,toDate,interval) {
        var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
        fromDate = new Date(fromDate);
        toDate = new Date(toDate);
        var timediff = toDate - fromDate;

        if (isNaN(timediff)) return NaN;
        switch (interval) {
            case "years": return toDate.getFullYear() - fromDate.getFullYear();
            case "months": return (
                ( toDate.getFullYear() * 12 + toDate.getMonth() )
                -
                ( fromDate.getFullYear() * 12 + fromDate.getMonth() )
            );
            case "weeks"  : return Math.floor(timediff / week);
            case "days"   : return Math.floor(timediff / day);
            case "hours"  : return Math.floor(timediff / hour);
            case "minutes": return Math.floor(timediff / minute);
            case "seconds": return Math.floor(timediff / second);
            default: return undefined;
        }
    }
    var seco = datediff(timeStart, timeEnd, 'seconds') % 60;
    var minu = datediff(timeStart, timeEnd, 'minutes') % 60;
    var hour = datediff(timeStart, timeEnd, 'hours');

    $('#form_qa_callduration').val(hour + ":" + minu + ":" + seco);
});

Comment: Please show the HTML and code you have tried with.
Comment: `new Date(new Date() - new Date() ).toISOString().split("T")[1].split(".")[0]`
Comment: the above "middle dates" should be the old and new date values...
Answer: You could use this code:

function diff(a, b) {
    function toTime(a) {
        return Date.parse('1970-01-01 ' + a.substr(0,8)) / 1000
             + (a.includes('PM') && (12*60*60));
    }
    var d = toTime(b) - toTime(a);
    return d >= 0 ? new Date(0,0,0,0,0,d).toTimeString().substr(0,8) : '';
}

$('.qaw_form_input3').on('input', function () {
    $('#form_qa_callduration').val(
        diff($('#form_qa_startcall').val(), $('#form_qa_endcall').val()));
}).click();

  Start of Call
  <input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">

  End of Call
  <input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">

  Call Duration
  <input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8" readonly>

As the duration will be updated by changes to the other two input values, it would be a good idea to make the duration input read-only, by adding the readonly attribute.
Comment: Thank you very much for this code. It's now working. about the input for the call duration, originally they want to manually put the difference but yesterday they want to make it automatic calculations so I may have to make it readonly today. :)
Comment: Users and their (always changing) requirements: we all know what a challenge that can be for our patience ;-)
Answer: Assuming you get it as strings, you can roughly do the following.

var str1 = "11:31:51 AM";
var str2 = "11:52:54 AM";

str1 = str1.split(':');
str2 = str2.split(':');

if(str1[2].split(' ').pop() != str2[2].split(' ').pop()) { // one is AM other is PM
   str1[0] = parseInt(str1[0])+12;
}

var finalStr = m(str1[0], str2[0])+":"+m(str1[1], str2[1])+":"+m(str1[2], str2[2]);

console.log(finalStr);

function m(n1,n2) {
  return Math.abs(parseInt(n1)-parseInt(n2));
}


Camel need Non-blocking Queue - Analogous to not processing events on graphics thread

Question: Sorry I answered my own question - it actually IS just SEDA, I assumed when I saw 'BlockingQueue' that SEDA would block until the queue had been read ... which of course is nonsense. SEDA is completely all I need. Question answered

I've got a problem that's compeletely screwing me, I've been provided a custom Endpoint by company we connect to, but the endpoint maintains a heart-beat to a feed, and when it sends messages above a certain size they take so long to process on the route that its blocking and the heartbeat gets lost and the connection goes down
Obviously this is analogous to processing events on a non-graphics thread to keep a smooth operation going. But I'm unsure how I'd achieve this in camel. Essentially I want to queue the results and have them on a separate thread.
<code>from( "custom:endpoint" )
.process( MyProcesor )
.to( "some-endpoint")
</code>
Answer: as suggested camel-seda is a simple way to perform async/mult-threaded processing, beware that the blocking queues are in-memory only (lost if VM is stopped, etc).  if you need guaranteed messaging support, use camel-jms


How to insert alt tags dynamically in jsp

Question: I want to insert an alt tag in the following lines of jsp code how do I accomplish this?

<c:choose>
<c:when test="${mediaType eq 3}">
    <dsp:valueof param="media.data" valueishtml="true"/>
</c:when>
<c:when test="${mediaType eq 1}">
    <dsp:getvalueof var="imgURL" param="media.url" />
    <img src='<dsp:valueof value="${imgURL}"/>' />

</c:when>
</c:choose>

Comment: What do you mean by dynamically? Is it based on some condition?
Answer: im assuming you meant adding an alt attribute to the img-tag:
just do something like this when trying to set the alt attribute. this example sets the value of the variable fetched via the dsp-tag using media.description as a name of the property on your media object.
<c:when test="${mediaType eq 1}">
    <dsp:getvalueof var="imgAltText" param="media.description" />
    <dsp:getvalueof var="imgURL" param="media.url" />
    <img alt='<dsp:valueof value="${imgAltText}"/>' src='<dsp:valueof value="${imgURL}"/>' />

</c:when>

hope that helped....


How to make desired Joomla site working on live server same as on Local Machine?

Question: I have created a Joomla based website and willing to upload it on live server. I have never done the hosting before. please help me how shall i make this happen successfully?
Answer: There is a much easier way to do this. Look for a component called Akeeba Backup. Install that on your local Joomla install. Then create a backup of your site.
Now using the backup from Akeeba your can restore your site onto any other server - live or test. The restore feature of Akeeba has a installer that is similar to the Joomla installer.
Very simple, very effective!
Answer:
Database. You have to export your database from your local machine to the remote one (using phpMyAdmin for example)
Copy files. Copy your local files to the remote server. (using FTP for example)
Configuration files check. Some paths are hardcoded in it, and database credentials might be changed.

See also http://docs.joomla.org/Copying_a_Joomla_website


Clickable Tree UI using JAVA Swing?

Question: Basically, I need a tree UI using Java Swing. The nodes of UI should be clickable (As it may contain URLs). After searching on the internet I found that there is various type of tree UI available in java like http://graphstream-project.org etc(basically graph). But doesn't give much functionality.

Please suggest.
Answer: Did you consider javax.swing.JTree?
Here is quick peek how it looks and feels.

Clickable Tree UI using JAVA Swing?


the loop in magic 8 ball has a bug

Question: I'm trying to make a Magic 8 Ball program but my loop has a bug.

If you play again, the loop messes up and behaves like you were hitting enter all the time for about three cycles until it will work again.
Also, there is a delay when you enter you question. You have to hit enter twice to get the answer.

<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
void ans(int x);
int main()
{
    system("color 0A");
    srand(time(0));
    int num,i;

    do{

    char question[100] = {" "};

    num = rand()%10;

    puts("MAGIC 8 BALL!");
    puts("Press Enter When Ready.");
    getch();
    system("cls");
    puts("Input Yes or No questions only!");
    printf("\n");
    scanf("%s",&question);
    getch();
    printf("\nTHE ANSWER | ");
    ans(num);
    getch();
    system("cls");
    printf("Press any key to try again.\nPress [x] to Exit.");

    if(getch()=='x'){
        system("cls");
        break;
    }
    system("cls");
    }while(1);
}
void ans(int x){
    switch(x){
        case 1 : printf("YES!");break;
        case 2 : printf("NO!");break;
        case 3 : printf("It's a thumbs down.");break;
        case 4 : printf("Positive!");break;
        case 5 : printf("As I see it Yes.");break;
        case 6 : printf("Certainly!");break;
        case 7 : printf("Negative!");break;
        case 8 : printf("Don't Count on it.");break;
        case 9 : printf("You don't want to know, trust me.");break;
        case 10: printf("I can't say right now.");break;
        default : printf("Cannot be determined right now");break;
    }
}
</code>
Comment: I'd suggest you eliminate the second `getch()` in your main function
Comment: Note also that `num = rand()%10;` gives you values from 0 to 9, not 1 to 10.  You might adjust your switch statement to handle that.
Answer: Fixed your problem. Added comments explaining. Hopefully I caught everything. Tested the program, and it works fine now.
<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
//#include <unistd.h>

#define MAX_QUESTION            1000
#define STATEMENT_AMOUNT        10

int random_num_generator();
void statement_picker(int x);

int main(void) {

    char temp;
    int rand;

    // Your while condition really just needs to be scanning 1 character.
    // No point in scanning the entire string, because we don't even use the string
    // The scanning jus tells us when to start the loop again
    while (1) {

        // The introduction of our program
        system("cls");
        printf("MAGIC 8 BALL!\n");
        printf("Press Enter When Ready.\n");
        getch();

        // Asking user to enter in their question
        system("cls");
        printf("What is your question?\n");
        printf("Only enter yes or no questions!\n");
        // You have to flush (aka clear) stdin. Because it uses your previous inputs
        // automatically. For example, if you type "I am the best?". The program will not work
        // properly for num_of_words - 1 iterations. So 4 - 1. Will not work properly for
        // 3 iterations
        // Also you don't need to scan in the word, because we don't really care what question
        // the user typed. You can save some memory by only scanning in a single character.
        // We only use scanf to give a real magic 8 ball experience by stopping and waiting
        // for the user to type their question.
        scanf("%c", &temp);
        fflush(stdin);

        // Generating a random number
        printf("The answer you seek: ");
        rand = random_num_generator();
        statement_picker(rand);

        // So I noticed here you cls, but you cls without waiting. This the user won't
        // be able to read your answer in time. So you should cls after you ask the user
        // to quit, or have a timer. Commented a timber for you below. You also need to
        // include the unistd.h library to use the sleep function. Just uncomment it
        // in the #includes section if you want the timer.
        // sleep(10);
        // system("cls");

        // Asking the user if they want to try again
        printf("Would you like to ask another question?\n");
        printf("Press [x] to quit\n");
        printf("Press any other character to continue\n");
        scanf("%c", &temp);
        if (temp == 'x') break;

        // Flush at the end too, just in case the person types multiple things rather than
        // one characters
        fflush(stdin);
    }

    system("cls");
    return 0;
}

// Generates a random number between 0 - 10.
/* I noticed in your switch statement you start at case 1. You should start at case 0,
 * because you are using the modulus operator Just for example, if rand generators 30 and
 * you have 10 cases you will be doing (30 % 10) which is equal to 0 because 10 goes into 10,
 * 3 times with no remainders If you really want to start your switch case at 1,
 * then you have to plus one to the return value in random_num_generator
 */
int random_num_generator() {

    time_t t;
    srand((unsigned) time(&t));
    return rand() % STATEMENT_AMOUNT;
}

// Picks a statement and prints it, depending on the value of x
void statement_picker(int x){
    switch(x){
        // Your case should start at 0, not 1 because you will never print out case 0
        // the way you had it before.
        case 0 : printf("YES!\n");break;
        case 1 : printf("NO!\n");break;
        case 2 : printf("It's a thumbs down.\n");break;
        case 3 : printf("Positive!\n");break;
        case 4 : printf("As I see it Yes.\n");break;
        case 5 : printf("Certainly!\n");break;
        case 6 : printf("Negative!\n");break;
        case 7 : printf("Don't Count on it.\n");break;
        case 8 : printf("You don't want to know, trust me.\n");break;
        case 9 : printf("I can't say right now.\n");break;
        // No need for default because you'll never get to it
        // (just because of how we implemented this software)
        // default : printf("Cannot be determined right now");break;
    }
}
</code>
Answer: You may try this
<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void ans(int x);
int main()
{
srand(time(0));
int num,i;

do{
    num = rand()%10;
    char question[1000];
    puts("MAGIC 8 BALL!");
    puts("Press Enter When Ready.");
    puts("Input Yes or No questions only!\n");
    scanf("%s",question);
    printf("\nTHE ANSWER | ");
    ans(num);
    printf("\n\n");
    printf("Press any key to try again.\nPress [x] to Exit.\n\n");
    char c = getchar();
    c=getchar();
    if(c=='x'){
        break;
    }
}while(1);
}
void ans(int x){
switch(x){
    case 1 : printf("YES!");break;
    case 2 : printf("NO!");break;
    case 3 : printf("It's a thumbs down.");break;
    case 4 : printf("Positive!");break;
    case 5 : printf("As I see it Yes.");break;
    case 6 : printf("Certainly!");break;
    case 7 : printf("Negative!");break;
    case 8 : printf("Don't Count on it.");break;
    case 9 : printf("You don't want to know, trust me.");break;
    case 10: printf("I can't say right now.");break;
    default : printf("Cannot be determined right now");break;
}
}
</code>

the loop in magic 8 ball has a bug


E: Package 'libpng12-0' has no installation candidate (Ubuntu 17.04)

Question: When I run: sudo apt-get install libpng12-0, I get this error message:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package libpng12-0 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'libpng12-0' has no installation candidate

How to fix this?
Is having libpng16-16 installed enough to do what libpng12-0 does?

I have:
Distributor ID: Ubuntu
Description:    Ubuntu 17.04
Release:    17.04
Codename:   zesty

Answer:
The repository in Ubuntu Zesty does not include libpng12-0. You have to download it from Xenial's repository. It will, in most cases, work smoothly.
libpng16-16 has a seperate folder for its program libpng16.so.16, which is different from libpng12-0 , which is libpng12.so.0, so having libpng16-16 installed will not at all do what libpng12-0 does.


add foreign key constraint to uuid list column

Question: I have a table with following definition:
CREATE TABLE apartment (
  id      uuid         NOT NULL DEFAULT fellowship.uuid_generate_v4(),
  name    VARCHAR(100) NOT NULL,
  address VARCHAR(100) NOT NULL,
  owners  uuid[]
);

Where the column owners is a list of UUIDs referenced in table owner with following definition:
CREATE TABLE owner (
  id      uuid         NOT NULL DEFAULT fellowship.uuid_generate_v4(),
  name    VARCHAR(100) NOT NULL,
  email   VARCHAR(100) NOT NULL
);

How can I define a foreign key constraint on column owners of table apartment to the table owner?
Comment: it is still not possible to do so see https://stackoverflow.com/questions/41054507/postgresql-array-of-elements-that-each-are-a-foreign-key
Comment: **DO NOT** use array columns to hold references to other rows. Use an associative (bridge) table; e.g., create table, `apartments_owners`, with columns `apartment_id` and `owner_id` having foreign keys to their respective tables and a unique constraint on the pair.
Answer: PostgreSQL currently does not support adding foreign key constraints on elements of an array type column. It is also not something that would generally be recommended as good practice in structuring your SQL data structure.
A best practice for this kind of many-to-many relationship is to use an association table. In your case, you can introduce an apartment_owner table that represents the relationship between apartments and owners:
CREATE TABLE apartment_owner (
    apartment REFERENCES apartment(id),
    owner REFERENCES owner(id)
)

Every time you want to add or remove an owner, you can just add or remove a row from that table. You can also get an apartment with all its owners as a simple JOIN query.
If you really want to return the owners as an array, you can simply do that with an array aggregate query:
select
    a.id,
    a.name,
    a.address,
    array_agg(ao.owner) as owners
from apartments as a
join apartment_owner as ao ON ao.apartment = a.id
group by a.id, a.name, a.address;


unable to use turboc through xp. why? solution?

Question: I'm having problems opening directly TurboC++ compiler(dos version) on Windows X.
if I click on the TurboC++ icon through windows GUI it opens for a sec(a blank dos screen)
and shuts down.
so i have to access it through the command line i.e.,
cmd  (enter)
c:\tc\bin (enter)
tc.exe

This way TurboC++ opens and I'm able to program and everything..
Why do I have to always start tc.exe through the command line? Why can't I start it through Windows XP?
Also, after starting tc.exe through the command line, I am unable to execute any graphics program through it.
I write a simple code for creating a circle using predefined functions..
when i compile and run the program tc.exe exits and returns back to the command prompt.
Why does this happen?Is there a solution?
I have also tried using DosBox to run TurboC++. it closes on executing the graphics program.
ps:  this problem has occurred to only me and my friend.....
all PCs in our college have Windows XP or Vista installed and they have no problems.
im using initgraph(); function for initialising graphics drivers(using autodetect) and graphic mode.i have given the proper address for bgi files. and the folder contains the file required (EGAVGA.bgi). this program works fine in our college.does this have something to do about my graphics card(nvidia 9400 1gb)?
Comment: May I ask why you're using a C compiler from the 80s?
Comment: May I ask why your college still thinks it's the 80s?
Comment: This *has* to be an April Fool's joke.
Comment: As a side note, the high school I went to really used Turbo Pascal (also from the 80s), but what can you expect from a class ran by a math teacher who admits she doesn't understand computers...
Comment: IMHO this question should be closed. It's not about programming, it is about running DOS applications from newer (32-bit) OS. I suspect reading up on Windows `.pif` files would be helpful. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/windows_dos_configure.mspx?mfr=true
Comment: we hv to use it for our college practical exams...
Comment: it doesn't matter ...plzzz help me solve the problm...
Answer: Graphics in the 80s were a completely different world than today - directly accessing hardware, often using undocumented features to optimize performance.  Drivers didn't exist in DOS.  Each program had to write their own hardware layer (hence why under DOS, you had to configure the video and soundcard for every single game separately.  The fact that we can run any software from the 80s is a testament to the backwards compatibility work done by Microsoft.
You might have some luck running it on VirtualPC, VMWare or VirtualBox.  All of them offer a free version, and if you can find and old copy of DOS 6.22 lying around, you might be good to go.  Otherwise, you'll likely be stuck finding a physical 486 running Windows 3.11, and working on that.  Depending on what deals your college has with Microsoft, they should be able to get a copy of DOS 6.22 for free - it's still offered for download on MSDN.  Although, if you're still using TurboC++, they have not likely signed up for anything with MS.  You can also try FreeDOS.
Comment: Just to add another option to the list FreeDOS can be another option
Comment: Note that Fizz said that it works when starting from a cmd window. (TC was using Borland's own TurboVision. I doubt that this poked directly into the graphic card.)
Comment: @Eclipse: You're right, I hadn't read that far. (Sorry, but that spelling makes it really hard to read...)
Comment: sorry guys,, i had no idea it would be hard for you to read(sms language)..please bear with it.. i shall write correct spellings now onwards
Comment: We are able to understand your txt spk fine, but showing some effort and respect by writing proper English will get more people interested in your question.
Answer: Right click on the TC icon and pick Properties. Go to the Compatibility tab. Play with the settings found there. If that doesn't help, ask your teacher how to use a 25 year old program on a modern computer.
Answer: How are you doing graphics? If you're using int 10h (or equivalent) to change the mode, that should work fine as it stands. If you're using BGI, make sure the program's working folder contains the BGI files that come with Turbo C++ -- for more details on initializing BGI, look up initgraph in the help.
Even modern PCs with modern graphics cards seem to have enough legacy support for the BGI code to work, though it seems like the program always runs fullscreen once in graphics mode, rather than in a window.
I don't know why Turbo C++ might not start from the GUI unfortunately. I've used Borland C++ just now to refresh my memory about the BGI stuff, and it worked OK.
Answer: Use visualc++ express instead. Its free and equipped with c++11.
Answer: for opening problem you can use a .bat file for opening Turbo C++
as follows:
open notepad and type the address of TC.exe and name of exe file like
D:\bhanu\TurboC++\TC.exe
and save it as TC.bat instead of TC.txt
and now double click it to run TC.
For graphics you first copy EGAVGA.BGI file from bgi folder to bin and then in the Turbo c++ open options->linker->library
and mark 'X' on bottom two libraries and un-mark all other libraries.


Nearest-neighbour classifier

Question: Given a dataset $\mathcal D =\{x_i, y_i\}$ where $i$ runs from  $1$ to $N$ and a new sample $x$, we simply assign to $x$ the label of the nearest sample to $x$ in $\mathcal D$, i.e.
$f(x)=y_i$ such that $i=$ arg $min_j \Vert x-x_j\Vert^2$
where $\Vert . \Vert$ denotes the usual Euclidean norm.
How do I show that the nearest neighbout classifier can be written purely as inner/dot product?
This is what I have so far.
Since I want the argument $x_i$ that minimizes  $i=$ arg $min_j \Vert x-x_j\Vert^2$, I want to find the $x_i$ such that $(x_m-x_i)^2$ is as close to zero as possible since $\Vert x-x_j\Vert^2=(x_1-xj)^2+(x_2-xj)^2+...+(x_j-xj)^2+...+(x_N-xj)^2$.
But how do i show that it can be written purely as an inner product?
Answer: The answer is simple - this problem could not be solved other than using $argmin$ notation.

Nearest-neighbour classifier