How to update Azure Maps layers dynamically on Android?

Question: I am developing an Android application whereby a map is shown and the location of the device is tracked on a point on the map. I am using the Azure Maps SDK for the map itself and FusedLocationProviderClient (Play Services) for getting the GPS coordinates. The way I'm doing it now is that I'm writing my coordinates to variables with FusedLocationProviderClient and reading them again on map creation in Azure. The problem with that approach is that it will only show my location for the moment I create the app, but will not dynamically change it when I move around. What I want is a way to modify the map after creation. How is that done?
For some context, this is the code I'm using for retrieving the coordinates (Kotlin:)
var location = fusedLocationClient.lastLocation.result
var currentLong : Double = location?.longitude?:0.0
var currentLat : Double = location?.latitude?:0.0

locationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult?) {
        locationResult ?: return
        for (location in locationResult.locations) {
            currentLat = location.latitude
            currentLong = location.longitude
            // This is just so I make sure that the values actually change
            latitudeView.text = currentLat.toString()
            longitudeView.text = currentLong.toString()
            task = client.checkLocationSettings(builder.build())
        }
    }
}

fusedLocationClient.requestLocationUpdates(
    locationRequest,
    locationCallback,
    Looper.getMainLooper()
)

And this is the code for writing a dot on the map
mapControl.onReady {map : AzureMap ->
    //Create a data source and add it to the map.
    val dataSource =
        DataSource()
    map.sources.add(dataSource)
    //Create a list of points.
    dataSource.add(Feature.fromGeometry(Point.fromLngLat(currentLong, currentLat)))
    //Create a LineString feature and add it to the data source.
    //Create a line layer and add it to the map.
    map.layers.add(SymbolLayer(dataSource))
}

I'm new to the field and the documentation is not helping, so all help is appreciated.
Answer: Simply clear the data source and add the new feature to it. For example, try adding the following in the location callback:
var loc = locationResult.getLastLocation()

dataSource.clear()
dataSource.add(Feature.fromGeometry(Point.fromLngLat(loc.longitude, loc.latitude)))

You will need to have a global variable in your Activity for the data source so that it is easy to access from various parts of your app.


Radio buttons always "false" in params

Question: I don't understand... The radio button is always returning false, the rest of the form works.  I had to put "false" for the third argument for the "radio_button" form_for helper method, however, that shouldn't affect the outcome.  Any idea what's going on?

      <%= f.label :delivery_method, :class => 'control-label required' %>

        <input type="hidden" name="auction_holder[delivery_method]" value="">
        <% ['Rail', 'Truck', 'Barge'].each_with_index do |t, i| %>
        <%= f.radio_button :delivery_method, false %> <%= f.label :delivery_method, t, :style => 'padding-right: 10px' %>
        <%if (i + 1) % 3 == 0 %>
 <%end%>
        <% end %>
        <%= f.label :other_delivery_method, "Other:", :style => 'padding-right: 10px' %><%= f.text_field :other_delivery_method, :class => 'other_field' %>

Let me know if you need any other code to help.  I've been stuck on this for a while.
Update method:
  def update_registration
    organization = Organization.find(params[:organization_id])
    @application = organization.auction_application
    p params[:auction_application]
    p "start"
    if @application.update_attributes(params[:auction_application])
      redirect_to auctions_path
    else
      Rails.logger.info(@application.errors.messages.inspect)
    end
    p "end"

  end

Answer: You set value attribute to false while you should have set checked attribute:
<%= f.radio_button :delivery_method, '', checked: false %>

P.S. Now value is set to '', so you should set to whatever value you want.
Comment: Well, the form doesn't blow up with that change, however it won't successfully update the attributes now, with that change.
Comment: @m.sherman: show your controller method. By the way, have you replaced `''` with actual `value`?
Comment: What do you mean by "actual value"?   I replace it with "t".
Comment: @m.sherman: so now you are updating your `delivery_method` field with `t`.
Comment: gotcha, I edited my original post to include the controller method.

Radio buttons always "false" in params


syntax error when trying to query json documents in postgresql

Question: on my postgresql 9.6, I ran into an error with a table created like
create table jsonTest (id integer, data jsonb);

The table has the following data:
select * from jsonTest;
 id |               data
----+----------------------------------
  1 | {"tags": ["AA", "BB", "CC"]}
  2 | {"tags": ["BB", "DD"]}
  2 | {"tags": ["CC"]}
  4 | {"city": "austin", "tags": "EE"}
(4 rows)

But when I tried to select, got syntax error:
template1=# select * from jsonTest where data->>city = 'austin';
ERROR:  column "city" does not exist
LINE 1: select * from jsonTest where data->>city = 'austin';

Any ideas? Thanks a lot!
Comment: `data->>'city'`
Comment: Thank you @klin! It appears to be a common mistake for someone who used javascript a lot.   Please write it up as an answer.
Answer: The right operand  of ->> operator for JSON object is text. Use the apostrophes for the key, because without them Postgres interprets the name as an identifier (a column name):
data->>'city'


C# SQL Needs to include Profile in WHERE clause

Question: I'm new to .NET and need to write a SQL statement.  It needs to read something like
"SELECT Title, Post, CONVERT(varchar, PostDate, 107) AS DatePosted FROM Posts WHERE RepID = " + Profile("RepID");

I need to be able to grab the value of the RepID from the Profile.  When I use the above statement in my code, I get a compiler error that Profile doesn't exist in the current context.  I addded
using System.Web.Profile;

but I still get the error.  What do I need to do include the RepID in my where clause?  I hope I'm referring the to the Profile correctly.  It's a setting in the security database, I think. I'm new to this and I didn't set up the database, so please be patient with me.
Answer: Found what I was looking for.  This is the solution:
ProfileCommon profile = (ProfileCommon)HttpContext.Current.Profile;
string sql = "SELECT Title, Post, CONVERT(varchar, PostDate, 107) AS DatePosted FROM Posts WHERE RepID = " + profile.RepID;

Hope this helps someone who is trying to figure this out, too.


Mkvirtualenv: command not found 19.04

Question: Trying to install Django Framework. This when I am trying to activate an virtual environment for the very first time:
mkvirtualenv test
mkvirtualenv: command not found

Location of the installation:
which virtualenvwrapper.sh
/usr/local/bin/virtualenvwrapper.sh

Update from research
I didn't use sudo when installing.
Here is tutorial one and tutorial two.
Comment: can you provide a link to the tutorials you followed!
Answer: you use python3, but virtualenv uses python2 by default. So you need to modify it.
Add the following sentence at the end of the '~/.bashrc',to modify the default python and configure virtualenv:
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export WORKON_HOME=~/.environments
source /usr/local/bin/virtualenvwrapper.sh

and then reload this configuration file with the command:
source ~/.bashrc

Answer: I needed to change the command to mkdir and follow different steps.

Mkvirtualenv: command not found 19.04


How to splice grounds in a metal box with a 30amp and 20amp circuit

Question: I have a 30amp dryer circuit (4x10 gauge - 2hot, 1neutral, 1gnd) and a 20amp circuit (3x12 - hot, neutral, ground) coming into the same metal box. The 20 amp circuit continues on to another box where the 20amp outlet is and the 30amp outlet is in this box.
Do I need to splice all the grounds together in this box (and to the box)? Or, can I directly connect the 4x10 to dryer outlet (without any splices with the 20amp circuit), then splice the 12gauge ground together and to the box?
If I do need to splice them all together, do I need to use 10AWG to the metal box?
EDIT: Basically I'm wondering if doing something like this is acceptable, or if I need to also to connect the incoming line to the 30amp dryer outlet to the ground bundle.
Comment: What wiring method is being used here?
Comment: @ThreePhaseEel - not sure what you are asking exactly. It's 120v split phase with two separate circuits (1 120v 20amp circuit and 1 240v 30amp circuit) entering the same box.
Comment: Are you wiring this using plastic-jacketed cables? Metal-armored cables? Conduit of some sort or another?
Comment: The wiring entering the boxes (on the right side in the image) is coming in through grounded FMC (all 6 conductors are actually in the same conduit even though my image doesn't show that) and the wire continuing on to the 20amp outlet is in MC
Comment: Is this a flush-mounted or a surface-mounted box, and how long is the FMC run?
Comment: Flush mounted boxes - the FMC run is about 5 feet to the next box
Answer: Splice the ground wires together and to a box ground pigtail
You'll need to splice the ground wires coming into the box to each other and to 10AWG pigtails to both the receptacle ground terminal and the box grounding screw, as per NEC 250.148.  That way, there's a direct path for ground current from the MC's ground conductor to the ground wire in the FMC, instead of sending ground current from the MC cable through the box and the yoke of the NEMA 14-30R in order to get to the ground wire in the FMC (or equivalently, through the box and then the 5' of FMC to get to the next box).


Memory too small on a partition

Question: My home partition is full, so you know at what kind of trouble can leads this. I have two partitions by 40 GB and I was wondering which would be the best method for transferring files or adding a path?
Comment: PLease clarify your question and add the result of `sudo fdisk -l` to your question for better answers.
Comment: Please ask only one question per post.  I have edited out your second question, feel free to ask a new question about it.  Thanks!
Answer: You can extend your size of the given partition with gparted.
It's a tool used for creating/editing the partitions. To install it, open your terminal with CTRL + ALT + T and type:
sudo apt-get install gparted.
There you can extend your partitions.
Helpful link: Geeks
Comment: I've tried Gparted and I have to un mount the home partition which is being used, so no dice. Any other suggestions?

Memory too small on a partition


CSS not using nested className rules

Question: Having an issue creating an accordion component. i have a collapsed state which gets passed as a className, if state is true, to a div tag. In the css, what's supposed to happen is that if collapsed className is true show content but what happens is that when button(that changes the state) is clicked, div gets 'collapsed' className but in the css, it doesn't use the $ .collapsed nested rules. Any help is appreciated. Not really good with css.
ErrorNotification.js
import React, { Component } from 'react'
import { Typography, Button } from 'rmwc'
import { Icon } from 'rmwc/Icon'
import cn from 'classnames/bind'
import styles from './index.css'

const cx = cn.bind(styles)

export class ErrorNotification extends Component {
  state = {
    collapsed: true,
  }

  toggleAccordion = () => this.setState({ collapsed:
    !this.state.collapsed
  })

  buttonIcon = 'keyboard_arrow_down'

  render() {
    console.log('collapsed', this.state.collapsed)
    return (

        <Typography className={cx('error-notification-message')}>There
        was an error in retrieving the configuration data.</Typography>

            <Button className={cx('accordion-button')} onClick=
              {this.toggleAccordion}>
              <Icon strategy="ligature">{this.buttonIcon}</Icon>
            </Button>

            <Typography>
              Lorem ipsum dolor sit amet, consectetur adipisicing elit,
              sed do eiusmod tempor incididunt ut labore et dolore
              magna aliqua.
            </Typography>

    )
  }
}

ErrorNotification.css
.error-notification {
  font-weight: bold;
  border-left: 10px solid #9a2c30;
  background-color: #cb454b;
  color: #ffffff;

  & .error-notification-message {
    margin: 0px;
  }

  & .accordion-container {
    padding: 10px;

    & .accordion-top-section {
      display: flex;
      justify-content: center;
      width: 100%;

      & .accordion-button {
        width: 100%;
      }
    }

    & .accordion-panel {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.2s ease-in;
    }

    & .collapsed {
      & .accordion-panel {
        max-height: 100px;
        overflow: hidden;
        transition: max-height 0.2s ease-out;
      }
    }
  }
}

Comment: That's not vanilla css, are you sure your sass is being preprocessed and converted to vanilla css?
Comment: @Ben if a answer helped you, you should mark it as the answer. This will help others as well
Comment: I see `error-notification-container` but I don't see `error-notification` in your html?
Comment: @SuperDJ thats because I'm using react toastify to render error notification component which has the className attached to that. code looks like this:
`export const renderErrorNotification = details => {
  toast.error(, {className: cx('error-notification')}) }` so it binds the className once it's rendered.
Comment: @Ted yes sass is preprocessing it and it catches the other rules. the only rule not being processed is `.collapsed` class rule.
Comment: Is the output what you expected it to be? https://www.sassmeister.com/gist/a41313db236a8e7edbb9e9748117e61b. Shouldn't the selector be `.accordion-container.collapsed .accordion-panel`?
Comment: @Ted in this case all @ Ben needs to do is to remove the space between the ampersand and `.collapsed` so `&.collapsed` instead of `& .collapsed`
Comment: Yeah I just realized I was wrong about that and deleted my comment
Comment: @Ted removing the space worked! thank you for the help!
Comment: That was @SuperDJ , not me :)
Answer: The problem is this rule:
& .collapsed {

It makes the output:
.error-notification .accordion-container .collapsed

While what you want is:
.error-notification .accordion-container.collapsed

You can achieve this result by removing the space:
&.collapsed {

You can check this here: https://www.sassmeister.com/gist/a41313db236a8e7edbb9e9748117e61b
Answer: The problem is that you are using wrong selector
.accordion-container {
  & .collapsed {
  }
}

Your selector means: select all elements with .collapsed class inside element with .accordion-container class and looks like this in pure css
.accordion-container .collapsed {
}

But you want to select exactly .accordion-container with class .collapsed on the same element, so,
for this you should use this selector
.accordion-container.collapsed

Or according to your code
&.collapsed

Summary: No space between & and .collapsed
Answer: Remove the space between & and .collapsed.
Edit: Actually you can just simplify that selector since the nesting is unnecessary.
.error-notification {
  font-weight: bold;
  border-left: 10px solid #9a2c30;
  background-color: #cb454b;
  color: #ffffff;

  & .error-notification-message {
    margin: 0px;
  }

  & .accordion-container {
    padding: 10px;

    & .accordion-top-section {
      display: flex;
      justify-content: center;
      width: 100%;

      & .accordion-button {
        width: 100%;
      }
    }

    & .accordion-panel {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.2s ease-in;
    }

    &.collapsed .accordion-panel {
      max-height: 100px;
      overflow: hidden;
      transition: max-height 0.2s ease-out;
    }
  }
}

In SASS, if you do this:
.parent {
  & .someClass {}
}

It will select .someClass children of .parent. If you want it to select .parent classes that also have the .someClass class, it needs to be like this:
.parent {
  &.someClass {}
}

CSS not using nested className rules


Can I skip parts of the campaign?

Question: So a while back I started replaying the Age of Empires 3 campaign (nostalgia, y'know). Unfortunately I ended up losing my progress. I was at the beginning of Act II in the original campaign - is there a way to get back there without playing through the entire campaign again?
Answer: You can use the cheat code of  this is too hard, which finishes the current level until you get to Act II.
You can type it in chat in order to activate it.

Can I skip parts of the campaign?


filter based media search with google photos API (python)

Question: I'm trying to use the mediaItems().search() method, using the following body:
body = {
        "pageToken": page_token if page_token != "" else "",
        "pageSize": 100,
        "filters": {
            "contentFilter": {
                "includedContentCategories": {"LANDSCAPES","CITYSCAPES"}
            }
        },
        "includeArchiveMedia": include_archive
    }

but the problem is that the set {"LANDSCAPES","CITYSCAPES"} should actually be a set of enums (as in Java enums), and not strings as ive written. this is specified in the API: (https://developers.google.com/photos/library/reference/rest/v1/albums)

ContentFilter - This filter allows you to return media items based on the content type.
JSON representation
{
  "includedContentCategories": [
    enum (ContentCategory)
  ],
  "excludedContentCategories": [
    enum (ContentCategory)
  ]
}

is there a proper way of solving this in python?
Answer: Modification points:

When albumId and filters are used, an error of The album ID cannot be set if filters are used. occurs. So when you want to use filters, please remove albumId.
The value of includedContentCategories is an array as follows.

"includedContentCategories": ["LANDSCAPES","CITYSCAPES"]

includeArchiveMedia is includeArchivedMedia.
Please include includeArchivedMedia in filters.

When above points are reflected to your script, it becomes as follows.
Modified script:
body = {
    # "albumId": album_id,  # <--- removed
    "pageToken": page_token if page_token != "" else "",
    "pageSize": 100,
    "filters": {
        "contentFilter": {
            "includedContentCategories": ["LANDSCAPES", "CITYSCAPES"]
        },
        "includeArchivedMedia": include_archive
    }
}

Reference:

Method: mediaItems.search
Comment: @Hadar Sharvit Thank you for replying. I'm glad your issue was resolved.


Ubuntu keeps freezing (regardless of version)

Question: Recently, I started learning to use Ubuntu. I downloaded the latest version (16.04.1 LTS), and installed it on my PC using a USB stick. (Note: Ubuntu is the only OS currently installed on my PC). It was working fine for about half an hour.
After that, I tried going to my system settings, to change a few things. But suddenly, the screen froze, and got distorted (the screen image broke, basically. It looked like static on a TV).
I rebooted my PC, and I still keep getting the problem quite often.(Not just for system settings, but almost any application I open causes this to happen) I downgraded to 14.04.4, but that also didn't fix it.
What could the problem be? My PC has 2GB of RAM, and 160GB free space on the hard drive.
Comment: Try to install LXDE which is much lighter than unity. See if still you face with problem
Comment: I installed LXDE and tried using it. But, the problem is still there. The same thing happened even while using LXDE :(
Answer: I have experienced the same issue with systems with minimal RAM. If you don't upgrade the RAM try changing the shell to a system such as Gnome.
<code>apt-get install gnome-shell
</code>
using the stock Ubuntu shell does become graphic intense at times.
Comment: Hi, Are you referring to using a different desktop environment which takes less RAM ?
Answer:
the screen image broke, basically. It looked like static on a TV

This could be a hardware error, graphic card with bad soldering or something else wrong with it.
Try with another graphic card if possible to see if that was the problem.
You described that you reinstalled the os several times and different distributions i don't this its os/software relaterad issue.
It can also be a bad RAM memory or motherboard but you got to start somewhere.


How to find the shaded area of a triangle formed by the tangent of a circle?

Question:
Hey guys,
The last question of the chapter has stumped me once again! I need to find the area of part of this triangle. I'm not sure how to attack the question considering that I'm not given the radius of the circle and I'm not sure how the measurement of 4cm will help me?
Thanks,
Scratch Cat
Comment: Since the line is a tangent you know that the triangle is a right triangle. This means $sin(35) = \frac{r}{r+4}$.
Answer: One way is to find the difference in areas of a right-angled triangle and a circular sector.
Finding both areas requires finding the radius of the circle, which may be found through the triangle
$$\begin{align*}
\frac{r}{r+4} &= \sin 35^\circ\\
r &= (r+4)\sin 35^\circ\\
(1-\sin 35^\circ)r &= 4\sin 35^\circ\\
r &= \frac{4\sin 35^\circ}{1-\sin 35^\circ}
\end{align*}$$
Answer: Step 1
Step 1: Using our knowledge that $∠BAC = ∠DAE = 35^o$ and that $∠ADE = 90^o$ (tangentiality), we can calculate section $AD = AE/cos(35) \approx 4.88$
Step 2
Step 2: Using Thales' Theorem, we know that $∠ADF=90^o$.
Thus, we can simply calculate $AF=AD/cos(35) \approx 5.96$
Then, using simple trigonometry again we obtain $AB = AF/cos(35)\approx7.28 $
Step 3
Step 3: Invoking Thales' theorem again, we obtain that $∠ABC = 90^o$.
We then calculate $AC=AB/cos(35)\approx8.88$
Similarly, $FB=AF*tan(35)\approx4.17$
Step 4: The area of ABC is then = $0.5*FB*AC = 18.54$
The radius of the large circle = $8.88-4 \approx 4.88$
The area of the large circle = $\pi*r^2 \approx 74.91$
Step 5: However, we only need to know the part within the triangle. As $∠ABC = 90^o$ and $∠BAC=35^o$, $∠BCA = 55^o$.
Thus, the relevant area $ \approx 55/360*74.91 = 11.44$
Answer: The answer is then $18.54-11.44 = 7.10cm^2$


Can't install package bcmwl-kernel-source package

Question: Need to get my wireless network adapter working on Ubuntu 14.1, but when trying to install the required package bcmwl-kernel-source, the "apt-get install bcmwl-kernel-source" installation command hangs on asking repetitively for a Ubuntu cdrom installation disk mount even after one is provided. Here is the exact terminal output that I am receiving:
$ sudo apt-get install bcmwl-kernel-source
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  bcmwl-kernel-source dkms
0 upgraded, 2 newly installed, 0 to remove and 12 not upgraded.
Need to get 0 B/1,576 kB of archives.
After this operation, 8,386 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Media change: please insert the disc labeled
 'Ubuntu 14.10 _Utopic Unicorn_ - Release amd64 (20141022.1)'
in the drive '/media/cdrom/' and press enter

Media change: please insert the disc labeled
 'Ubuntu 14.10 _Utopic Unicorn_ - Release amd64 (20141022.1)'
in the drive '/media/cdrom/' and press enter

I tried mounting my installation cdrom as requested, but after pressing enter it seems that the installation unmounts the cdrom and loops back to request that I mount it again. Can't get out of this loop. Why does the installation of this package reqest an installation cd? Other packages install fine without requesting this.
Answer: I have solved my problem by disabling the option "Installable from CD-ROM/DVD" under the "Ubuntu Software" tab of the "Software and Applications" update tool.


How to add a PPA which does not include my Ubuntu distribution?

Question: I am trying to add ppa:stevedh/smap to my repository with the following command:
sudo add-apt-repository ppa:stevedh/smap

It gets added. When i sudo do apt-get update I recieve the following message:
W: Failed to fetch
http://ppa.launchpad.net/stevedh/smap/ubuntu/dists/trusty/main/binary-amd64/Packages
404 Not Found

W: Failed to fetch
http://ppa.launchpad.net/stevedh/smap/ubuntu/dists/trusty/main/binary-i386/Packages
404 Not Found

When I browse http://ppa.launchpad.net/stevedh/smap/ubuntu/dists there are 3 dists available:

jaunty
oneiric
precise

Any suggestions?
Answer: In /etc/apt/sources.list.d, open the file that contains the name of the PPA in a text editor. The name will be something like stevedh-smap-trusty.list. Then, after the URL on the first line and the second line, change trusty to precise (since that's the most recent Ubuntu version supported by the PPA). For example:
deb http://ppa.launchpad.net/stevedh/smap/ubuntu precise main
deb-src http://ppa.launchpad.net/stevedh/smap/ubuntu precise main

Save the file and run sudo apt-get update.
That being said, note that because of library updates and packaging changes between Precise and Trusty, there is no guarantee that you'll be able to install the software from that PPA, much less run it.


How to notify list activity that one of its items has been updated in detail activity?

Question: Imagine we want to design G+ application. It has a list activity/fragment and by click on an item then detail activity/fragment will be displayed.
My problem is, I don't understand if user hits plus button in detail activity and click on back button then how its counterpart item in list knows that user has clicked it in detail screen (since it shows number of plus oned as same as detail activity)?
Comment: I guess, Same data is used by List fragment and Detail fragment. When you comeback from Detail fragment to list fragment, notifyDataSetChanged() may update the list fragment incase of any updates in Detail fragment.
Comment: It's not, because based on architecture, list fragment asks database to pass a page of Post items to it. Then fragment will pass the list to adapter. Since, list is in memory then doesn't notify when user get back from detail screen.
Comment: Guess you need to explore Content providers and content observers to achieve this.
Comment: List items come from database. Therefore, by click on +1 button in detail fragment then database will be updated while copy of items are in memory in list fragment.
Comment: Right. By calling ListView adapter's notifyDataSetChanged(), incase of change in Detail fragment, ListView will refresh its contents from DB through its adapter. Isn't it ?
Answer: Though it's bit late, thought of sharing my answer as it might help others who are coming across similar situation. Basically, you need to create an interface in the detail fragment class and implement it in the parent activity and use it to update the master list through notifyDataSetChanged().
You might want to refer to following SOF thread as an implmentation reference - Update ListView in Master/Detail after a form is saved


How to tag test in Postman

Question: I want to classified tests to run them for different purposes. As far as, I search I could not an option to tag some test and run test on demand. I also looked at Chaijs if it has such a feature, but could not be able to find a solution.
What I want to do is add some tag like the following:
@health_check
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

@smoke
pm.test("Product should be correct", function () {
    var jsonData = pm.response.json();
    var product = pm.variables.get("PRODUCT");

    pm.expect(jsonData.meta.appId).to.eql(product);
});

and run it like as following or anyway achieve this:
$ newman run mycollection.json -tag smoke

Answer: That tag type option is not something that's ever been available in the app or in Newman.
You could use the --folder option on the CLI and organise your collections to include requests within those specific folders, that cover those scenarios.
For example:
$ newman run mycollection.json --folder healthCheck --folder smoke
Alternatively, you could use a global variable to act as a switch in the control if specific tests/groups of tests are run.
Wrapping the test in an if statement like this:
if(pm.globals.get('smoke_check') === "runCheck") {
    pm.test("Status code is 200", () => pm.response.to.have.status(200));
}

Then passing in a global variable in the cli using the --global-var flag.
$ newman run mycollection.json --global-var "smoke_check=runCheck"
Comment: @MesutGÜNEŞ I update the answer with a simple example to show this. Hope that helps.
Comment: thanks for the answer, folder option seems good but it needs replication of the requests if we want to assert different things for different purposes.
Comment: Maybe you could control that via a variable? You can pass those in as an arg from the command line, that could act as a switch to run/not run a certain set of tests as part of the run?

How to tag test in Postman


Jenkins + Apache + SSL = no available updates

Question: I have followed this tutorial and many others:
https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache
However, none of my attempts have been successful:

When I go to Plugin Manager -> Available, it says "No updates"
When I go to Plugin Manager -> Advanced -> Check Now, it says "Checking Updates..." and then nothing happens.
Looking at Apache and Tomcat logs, nothing shows up.
Looking at browser console, no errors appear. However, I get warnings like this one:
[blocked] The page at 'https://mywebsite.com/jenkins/pluginManager/checkUpdates' was loaded over HTTPS, but ran insecure content from 'http://updates.jenkins-ci.org/updates/hudson.tools.JDKInstaller.json.html?id=hudson.tools.JDKInstaller&version=1.544': this content should also be loaded over HTTPS.

Looking at this, I realize the plugin manager wasn't designed for https, because it makes ajax requests for non-SSL endpoints.
So what's the right solution to this? Is there an HTTPS endpoint to use for downloading plugins? Do I need to use a different browser?
Thanks.
Answer: There is an HTTPS endpoint to use:
<code>https://updates.jenkins-ci.org/update-center.json
</code>
Comment: I believe this is the relevant Jenkins issue: https://issues.jenkins-ci.org/browse/JENKINS-20641
Comment: While the endpoint is HTTPS, the URLs in the response are not. Thus completely defeating the purpose.
Comment: Ah. Does it still give AJAX warnings when you actually attempt to install a plugin? I didn't test that far.
Comment: Hmm... the file already has SHA1 checksums as Kohsuke suggests in that Jenkins issue. Maybe the updater is already validating the plugin?
Comment: In case of SSL issue you may refer [this](https://stackoverflow.com/a/47709466/1802348)


Why is tqdm only updating after multiple iterations?

Question: I'm using tqdm twice in my script, and the first time it works fine but the second time it only updates after 14 iterations. It's the same if I remove all other print statements. Any idea what might be going wrong?
Program:
for name in tqdm(final_urls):
    print(f"Downloading {name} files...")
    url_list = final_urls[name]
    class_dir = os.path.join("data", name)

    if not os.path.isdir(class_dir):
        os.mkdir(class_dir)

    for idx, url in enumerate(url_list):
        filepath = os.path.join(class_dir, f"audio{idx}.wav")
        if not os.path.isfile(filepath):
            r = requests.get(url)
            with open(filepath, "wb+") as f:
                f.write(r.content)

Output:
Download files...
  0%|                                                                                | 0/32 [00:00<?, ?it/s]Downloading Bearded Seal files...
Downloading Bottlenose Dolphin files...
Downloading Rough-Toothed Dolphin files...
Downloading Common Dolphin files...
Downloading Striped Dolphin files...
Downloading Fin, Finback Whale files...
Downloading Melon Headed Whale files...
Downloading Killer Whale files...
Downloading False Killer Whale files...
Downloading Spinner Dolphin files...
Downloading Ross Seal files...
Downloading Harp Seal files...
Downloading Northern Right Whale files...
Downloading Short-Finned (Pacific) Pilot Whale files...
 44%|██████████████████████████████████████████████▍                                                           | 14/32 [01:34<02:01,  6.74s/it]Downloading White-beaked Dolphin files...
Downloading Narwhal files...
Downloading Humpback Whale files...
Downloading Walrus files...
Downloading Fraser's Dolphin files...
Downloading Beluga, White Whale files...
Downloading Clymene Dolphin files...
Downloading Southern Right Whale files...
Downloading Atlantic Spotted Dolphin files...
Downloading Leopard Seal files...
Downloading Long-Finned Pilot Whale files...
Downloading Grampus, Risso's Dolphin files...
Downloading Sperm Whale files...
Downloading Pantropical Spotted Dolphin files...
Downloading Bowhead Whale files...
Downloading Minke Whale files...
Downloading White-sided Dolphin files...
Downloading Weddell Seal files...
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████| 32/32 [01:34<00:00,  2.95s/it]

Answer: tqdm doesn't, by default, show every single update if the updates happen fast; by default it only updates 10 times per second. You can set the miniters parameter to 1 if you must have the output update on every iteration.
The default is miniters=None, which means it'll dynamically adjust the iteration count based on mininterval, which is set to 0.1 seconds.
You are also using print(), which replaces the bar output. Don't do that, updates will be overwritten and you get very messy output.
The tqdm class has a dedicated tqdm.write() method, use that instead:
for name in tqdm(final_urls):
    tqdm.write(f"Downloading {name} files...")

Using the method lets tqdm take care of how the messages are placed, as per the documentation:

Print a message via tqdm (without overlap with bars).

Quick demo to show the difference, while using miniters=1:
>>> from tqdm import tqdm
>>> from faker import Faker
>>> import time, random
>>> for word in tqdm(Faker().words(10), ncols=40, miniters=1):
...     print(f"Using print: {word}")
...     time.sleep(random.random() * .2)
...
  0%|            | 0/10 [00:00<?, ?it/s]Using print: of
 10%|▍   | 1/10 [00:00<00:01,  5.02it/s]Using print: we
 20%|▊   | 2/10 [00:00<00:01,  5.52it/s]Using print: message
 30%|█▏  | 3/10 [00:00<00:01,  5.83it/s]Using print: win
Using print: seem
 50%|██  | 5/10 [00:00<00:00,  9.12it/s]Using print: especially
 60%|██▍ | 6/10 [00:00<00:00,  8.00it/s]Using print: power
 70%|██▊ | 7/10 [00:00<00:00,  8.42it/s]Using print: material
Using print: both
 90%|███▌| 9/10 [00:01<00:00,  8.27it/s]Using print: single
100%|███| 10/10 [00:01<00:00,  8.09it/s]
>>> for word in tqdm(Faker().words(10), ncols=40, miniters=1):
...     tqdm.write(f"Using tqdm.write: {word}")
...     time.sleep(random.random() * .2)
...
Using tqdm.write: democratic
Using tqdm.write: manage
Using tqdm.write: generation
Using tqdm.write: perhaps
Using tqdm.write: purpose
Using tqdm.write: about
Using tqdm.write: evidence
Using tqdm.write: everything
Using tqdm.write: push
Using tqdm.write: large
100%|███| 10/10 [00:01<00:00,  7.65it/s]

and, still using tqdm.write(), miniters=1 in progress:
Comment: Even without the print statement the bar stays stuck at 0
Comment: @ShreyJoshi: are you *nesting* the tqdm objects?
Comment: no, sorry i forgot to post the earlier part of the script where i used the first tqdm
Comment: @ShreyJoshi: you'll need to give us a proper [mcve] if you want us to diagnose issues properly. Give us something that we can copy and paste to reproduce the issue, please.


Is there any way to label each desktop individually?

Question: I'm usually working with 3x3 Desktops, with the tendency to separate them by active projects or clients for the workday (for example, all consoles going to project A on one desktop, all consoles going to project B on another).
This is fine in most cases, but when there's a lot of stuff going on at once it can quickly become confusing.
Is there some way to label a Desktop? Either on the 3x3 Grid view (when switching around with CTRL+ALT+Arrows), some kind of gnome plugin to just add a Box with a word in it, or a custom background for each desktop?
Maybe there's an obvious solution, but I never really played around with gnome. I still use the defaults.
Gnome Shell: 3.28.4
Ubuntu: 18.04.5 LTS
Comment: You may set a different background image for each desktop, or change interface colors, otherwise just use some kind of note-desktop widget like `sudo apt install xfce4-notes-plugin` and put a note-desktop widget on each of your desktops and set those to `always on top`.
Comment: Gnome uses extensions. Examples: https://extensions.gnome.org/extension/484/workspace-grid/ https://extensions.gnome.org/extension/551/workspace-labels/  both unmaintained though (no idea if those work). 1st link has a list of other possible extensions
Comment: PS you might just use any editor, like _gedit_ and set it to always been shown on top
Comment: @paladin Yeah I'm currently doing something similar, as a makeshift solution - but it's just not very practical long-term :)
Comment: @Rinzwind at this point, since the extension seems to be written with JS (and I'm really looking for something proper) I might end up just writing / maintaining my own solution then. I'll be looking into it, I guess!
Answer: Alright, thanks to the comments and especially Rinzwind, I managed to find a solution:
Turns out, I was already using Workspace Grid. While not obvious on how to do it, the extension offers support for custom labels:

Install and activate the extension.
Configure the extension - you can do this directly on the website (I didn't realize that). Make sure to turn workspace labels ON.

If you see the switcher now, it'll number each Workspace ("Workspace 1, 2, 3, etc"). Unless I memorize the numbers, that's not really useful at all. But there is a way to change the label.

Open a console, type dconf-editor. Navigate to /org/gnome/desktop/wm/preferences/workspace-names. Set "Use default value" to OFF and add an array of labels.

Labels go from left to right, top to bottom. If you have a 3x3 grid, and want to label the bottom left workspace, it's the 7th index in the array. If you want to just remove the default naming "Workspace X" for a particular workspace, just use ' ' (space); an empty string '' won't work.
That's it! Works like a charm, at least if you use workspace-grid. I'm not sure if it's properly supported on later versions of Gnome, as the 1-star comments imply that there are issues.
Additional documentation can be found on https://github.com/zakkak/workspace-grid
Please keep in mind that this extension is no longer in development.
Comment: Thanks for sharing. Do not hesitate to "accept" your own question. This is perfectly fine on this site. Accepting an answer hints users that at least a good solution can be found here. You still have like workspace indicators around - also in this context, your method to "label" these other than "1,2,3,4" is useful.
Comment: @vanadium Yeah I will do so in 2 days, if I don't forget (and no-one else has something better); I have to wait for the timer first. Thanks for reminding me :)
Comment: This solution also works with the (still actively maintained) "Space Bar" extension, _iff_ it's "smart workspace names" are disabled. Adding this here because I had a similar problem using that extension with not wanting to manually rename each workspace after each restart anew.


Loading main XIB makes app crash on iOS 3.0

Question: thank you for taking some time to read my question.
I have this app (In Cydia), which has around 10% of users with iOS 3.0, so I want to support them in my next update .
I tested it with actual devices running, iOS 4.0 and 5.0.1; it worked fine. But on iOS 3.0 it crashes with an exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive (0x4e, 0x49, 0x42, 0x41, 0x72, 0x63, 0x68, 0x69)

apparently when loading the main XIB, here's the backtrace of the exception:
0  0x30016588 in objc_exception_throw ()
1  0x30224026 in +[NSException raise:format:arguments:] ()
2  0x30223fc6 in +[NSException raise:format:] ()
3  0x305564b4 in -[NSKeyedUnarchiver initForReadingWithData:] ()
4  0x3094927c in -[UINib instantiateWithOptions:owner:loadingResourcesFromBundle:] ()
5  0x30949090 in -[NSBundle(NSBundleAdditions) loadNibNamed:owner:options:] ()
6  0x308f131c in -[UIApplication _loadMainNibFile] ()
7  0x308f0f9c in -[UIApplication _runWithURL:sourceBundleID:] ()
8  0x309374b0 in -[UIApplication handleEvent:withNewEvent:] ()
9  0x30936cf0 in -[UIApplication sendEvent:] ()
10 0x3093687c in _UIApplicationHandleEvent ()
11 0x3204696c in PurpleEventCallback ()
12 0x30254a76 in CFRunLoopRunSpecific ()
13 0x3025416a in CFRunLoopRunInMode ()
14 0x308f0354 in -[UIApplication _run] ()
15 0x308eea94 in UIApplicationMain ()
16 0x00003886 in main (argc=1, argv=0x2ffff74c)

I've read and tried this and this. So I have all of my nibs with deployment version set to 3.0 and development to Interface Builder 3.0, still no luck.
Comment: Do you have an old XCode SDK? Have you tried opening the nib with InterfaceBuilder from such sdk?
Comment: Thanks @Peter, there's some progress I think, I followed your suggestion, fortunately I have access to Xcode 3.2, I compiled my project there, and after a few fixes, it works on the device with iOS 3.0, then I copied the exact same project to Xcode 4.2, and I Get the same error from before, I guess it's something about the way the new Xcode compiles the project.
Comment: I'm not 100% sure, but I think I've read somewhere that the xcode 4.2 nibs are backwards compatible only down to iOS 3.2. I'd try setting the minimal required target to 3.2 - or try to use nibs created with old sdk without recompiling them inside of XCode 4.2.
Comment: you're righ @Peter !! according to apple Docs: "iOS 3.2 supports loading unstripped nib files, but iOS releases prior to 3.2 do not. If you choose to build unstripped nib files to support a localization workflow, you should either use ibtool's --strip command to strip nib files after localizing, or temporarily revert the "Flatten Compiled XIB Files" and "Strip NIB Files" build settings to build nib files compatible with previous iOS releases." I tried to use that config. setting, but still wouldn't load the NIB. So I did a kinda hacky solution, but appears to work:
Answer: After reading some docs, it became clear that iOS prior 3.2 won't load NIBs from Xcode 4.2, so I ended up building the project with Xcode 3.2 and copied these NIBs to the package created with Xcode 4.2 under the DerivedData directory, the good part is I still can debug the app with Xcode 4.2, the bad part is, this is kinda hacky, but I hadn't choice. Thank you.
Answer: I second Emanuel's answer above. After many weeks of pulling my hair out I came up with this solution:
Build universal app for iOS 3.0 using Xcode 4.3.x - NSKeyedUnarchiver Exception


convert inputs to selects

Question: I'm looking to convert inputs to selects using Jquery, while taking the value form the input and using it as the selected option. But I've only got half way there so far in the below code. Can anyone see where its going wrong? Or maybe suggest an alternative method.
HTML

<input type="text" id="input01" value="1" name="input01"/>

<input type="text" id="input02" value="4" name="input02"/>

<input type="text" id="input03" value="2" name="input03"/>

<input type="text" id="input04" value="1" name="input04"/>

<input type="text" id="input05" value="4" name="input05"/>

JS
$(".inputDiv input[type=text]").each(function() {
    var qty = $(this).val();
    var currentId = $(this).attr('id');
    alert(qty + " is a Number");
    alert(currentId + " is a ID");
    $(this).replaceWith('<select id="' + currentId + '" name="" class="NewSelect">' +
          '<option value="1">1</option>' +
          '<option value="2">2</option>' +
          '<option value="3">3</option>' +
          '<option value="4">4</option>' +
          '<option value="5">5</option>' +
        '</select>');

        $("option[value=" +this.qty+ "]").attr('selected', 'selected');
});

Comment: id's have to be unique in the dom
Comment: thanks that was accidently copy pasted, edited example code above
Answer:     $(".inputDiv input[type=text]").each(function() {
        var qty = this.value;
        var currentId = this.id;
        var selectbox = $('<select id="'+currentId+'><option value="-1"></select>');
        $(this).replaceWith(selectbox);
        for(var i = 1; i < 6; i++) {
            var option = document.createElement('option');
            option.value = i;
            $(option).text(i);
            if(i==qty) option.setAttribute('selected','selected');
            selectbox.append($(option));

        }

    });

JSFIDDLE
Answer: try this:
$("input[type=text]").each(function() {
    $(this).parent().replaceWith('<option id=' + this.id + ' value='+ this.value + ' name=' + this.name + ">" + this.value +"</option>")
})
$('option').wrapAll('</select>')

DEMO
Answer: do it like this: http://jsfiddle.net/albertjan/heVc6/3/
In the DOM: make the id's unique

<input type="text" id="input01" value="1" name="input01"/>

<input type="text" id="input02" value="4" name="input01"/>

<input type="text" id="input03" value="2" name="input01"/>

<input type="text" id="input04" value="1" name="input01"/>

<input type="text" id="input05" value="4" name="input01"/>

In javascript:
$(".inputDiv input[type=text]").each(function() {
    var qty = $(this).val();
    var currentId = $(this).attr('id');
    alert(qty + " is a Number");
    alert(currentId + " is a ID");
    $(this).replaceWith('<select id="' + currentId + '" name="" class="NewSelect">' +
          '<option value="1">1</option>' +
          '<option value="2">2</option>' +
          '<option value="3">3</option>' +
          '<option value="4">4</option>' +
          '<option value="5">5</option>' +
          '</select>');

  //this qty instead of this.qty
  //search for an option within the current div.
  $("#" + currentId + " option[value=" + qty + "]").attr('selected', 'selected');
});

Comment: Thanks, but i needed the inputs to become select boxes @rsplak had the right idea
Comment: have you even looked at the jsfiddle I posted ?? hehe
Comment: yep, ic moo tools was the default loader, changed it to jquery to see the result. Though option isn't being selected. Cheers

convert inputs to selects


Special kind of specie in Spore?

Question: I was playing Spore and found some kind of special specie, as it had 999 HP and was really big compared to others, also it was pretty aggressive towards everything near it including my specie.
It lived near the 'border' and I couldn't interact with it in a friendly way.
What is it? And why is it there?
Answer: That's an epic creature, a huge variant of regular creatures. It exists to be an obstacle and can't be befriended.
Comment: I didn't know it was called an 'Epic Creature'. Thank you!

Special kind of specie in Spore?


How is standard washing machine "water usage" calculated?

Question: I'm trying to calculate exactly how much water is spent per washing machine use (medium water-level with a soak-wash-rinse-spin cycle).
On the last page of the manual of my washing machine (Samsung - WA6550B9), it states that the "water usage" is 164 litres. However, a tub of water at its "high water level" is only 56 litres:

Why is the "water usage" stated to be 164 litres?
Even if it's a soak-wash-rinse-spin cycle, wouldn't it use approximately two tubs of water? Yet 56 litres × 2 is far from 164 litres.
How do the numbers add up? What exactly is the 164 litres of water usage referring to?
Comment: You might have to contact the company ... I can think of two possibilities : it always uses the same amount for rinsing, therefore the usage would be (164 + load size - displacement) or that because of the displacement of clothes, they just average across all load sizes. ... and in this case, but 'displacement', I mean 'the volume taken by the items being washed'
Comment: I'm sure there's an industry standard for how this is measured. Heck, I'm sure there's a government standard since this would be part of the Energy Star calculations.
Comment: My washer goes through a lot more than just a single rinse cycle ... and it doesn't back fill up the whole way each time.
Comment: @Joe, There's still some oddity with the "water usage" number. It seems to suggest that its fixed and not dependent on the water level or function used. How is this possible? What exactly is the 164 litres of water usage referring to?
Answer: [It's very probably measured on high] edit - nope there's an average of sorts - if you'd like a very tedious read, the (US) government procedure is here, at least for some point in time. Beware, it's govenmentese...CFR-2011-title10-vol3-part430-subpartB-appJ1
It takes considerably more than two tubs of water to wash and rinse. Rinses may be multiple, and there may be water sprayed into the spin portion of the cycle for additional rinsing. In many cases the "clean" clothes will still make suds and or dark water if you run another wash cycle with no new detergent, so even that much water may not really rinse things "clean" other than the sense that we normally accept that when the machine is done, we call the clothes clean...
This is a good quick read about washing machine test standards, but does not really address "what size load do they test on" from what I can see.
My dishwasher actually told use per cycle options, and that made me suspect that there the "normal" option is the one in that standard, as every other cycle used more water.
Comment: Could you summarize some of the information from the links provided, just in case the links ever go bad.


Mysql ERROR 2002 (HY000)

Question: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

i am unable to understand, how to resolve this ?
Comment: Search is your friend. Read [this](http://askubuntu.com/questions/606732/php-fatal-error-uncaught-exception-pdoexception-with-message-sqlstatehy000)
Answer: Solutions for this:
#services mysql start
or
#/etc/init.d/mysql start

Answer: I have similar problem, when i re-installed mysql-5.7 in Ubuntu 16.04 LTS
note) problem appeared after updating from Ubuntu 15 to Ubuntu 16.04, i also had to abandon my existing database. Still no help from Ubuntu.
after uninstallation  and
sudo apt-get --purge remove mysql
sudo apt-get autoremove

sudo rm -rf /var/lib/mysql
sudo rm -rf /etc/mysql
sudo rm -rf /var/log/mysql.*
sudo rm -rf /var/log/mysql
sudo dpkg --force-depends -P `dpkg -l |awk '/mysql/{print $2}'`

i reinstalled with:
sudo apt-get purge mysql-apt-config && sudo apt-get install mysql-server

Mysql ERROR 2002 (HY000) still remain
But following suggestions solve the problem:
sudo apt-get purge dbconfig-mysql

then
sudo apt-get autoremove

then
sudo apt-get install -f

then finally
sudo apt-get install lamp-server^ phpmyadmin

Re-Re-Updating the Ubuntu-kernel(2x) solved the problem.

Mysql ERROR 2002 (HY000)


NavTabs : Call method when TabPane clicked

Question: I'm pretty new to GwtBootstrap3 so don't know much about JavaScript functions but I'm using navtabs with DataGrids in the tabs and looking for a way to call a data loading method whenever the tab is selected as I don't want to call all RPC methods at once when the NavTabs is initialized.
Here's my code:

and for the tabs:

    <gwt:DataGrid bordered="true" condensed="true" striped="true"
        hover="true" height="100%" width="100%" ui:field="profileGrid" />

I've tried using AttachHandler on the tabs which doesn't load the data.
Is there any way to call an RPC method (loadBundlesData()) whenever the Bundles tab is selected and not having to load that in advance with the NavTabs?
Any help/comments appreciated.
Answer: you just need to add a click handler to your TabListItem:
in your ui.xml:

in your .java:
@UiHandler("bundleListItem")
public void onClickBundleListItem(ClickEvent event){
    //do the job here
}

or:
bundleListItem.addClickHandler(new ClickHandler() {
    @Override
    public void onClick(ClickEvent event) {
        // do the job
    }
});

Hope it helps.


SQLite Commands to Store Date and Float values

Question: For Storing Values in SQLite.I wrote the below code in -(void)initWithPrimaryKey method.
<code>self.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(init_statement, 0)];
</code>
this is for string. what should i write if i wanna save date and a float value??
should i write the same thing??
As i Copied this code from a tutorial can someone tell me what that '0' at the last stand for?
Comment: you are retrieving or storing....??
Answer: If you don't wish to work with raw sqlite, the open-source FMDB is a commonly-used Cocoa wrapper for sqlite.
Answer: <code>        use this one
       if insert
        sqlite3_bind_double(init_statement, 1, date);

    if retrieve date then

double Date= sqlite3_column_double(init_statement, 1);
</code>
Comment: it represent your column number from where u insert or retrive date


How to wire 3 Phase for 220V Motor

Question: I have a used 3 Phase motor that can either run in 220V or 440V with 3 Phase power.
I looked at the wiring and there's three sets of wires, each wire has a label W6, U6, V6, etc...
There's a diagram on the inside of the wire casing but it looks like some sort of puzzle from Jonathan Blow The Witness
I was hoping that someone here can help me understand what this image means.
Comment: Possible Duplicate of: [How to wire three phases for 220V?](https://electronics.stackexchange.com/questions/183484/how-to-wire-three-phases-for-220v)
Comment: Could you please zoom in and crop the image. I take it that there is a neutral wire as well, so you have the option of a WYE or DELTA hookup.
Comment: Wye wired motors do not have a neutral.
Answer: You want to use the lower voltage connections at the top the Wye start connections connect w6 to u6 to v6. Next w2 to u2 to v2. Those are the internal field windings to set up low voltage starting now connect u1 to u5- first phase, v1 to v5 -2nd phase and last w1 to w5 -3rd phase the little black lines are the connection points .

How to wire 3 Phase for 220V Motor


I want to obtain the values of reliability != 1 by day in R

Question: I want to know how many values are different from 1 in my dataframe.
My input is like:
simulation, day, reliability
1, 1, 0.999
1, 2, 0.999
1, 3, 0.999
2, 1, 1
2, 2, 0.999
2, 3, 1
3, 1, 0.98
3, 2, 0.98
3, 3, 1

And the output should be like:
day, counter
1, 2
2, 3
3, 1

Many thanks in advance!
Answer: You can take sum of logical values to count how many of them are different than 1 for each day.
In base R :
aggregate(reliability~day, df, function(x) sum(x != 1))

dplyr :
library(dplyr)
df %>%group_by(day) %>% summarise(counter = sum(reliability != 1))

and data.table:
library(data.table)
setDT(df)[, .(counter = sum(reliability != 1)), day]

Answer: Though Ronak has already provided an exhaustive answer, still an alternative way
library(dplyr)
df %>% filter(reliability != 1) %>% group_by(day) %>% summarise(counter = n())


Regular expression to extract based on capital letters

Question: Hi please can someone help with a C# regex to split into just two words as follows:
"SetTable" ->> ["Set", "Table"]
"GetForeignKey" ->> ["Get", "ForeignKey"]  //No split on Key!

Comment: What exactly are you trying to do? Arey you always only trying to separate the first "word" (i.e., always splitting only on the first uppercase character _inside_ the string)?
Comment: I am just going to throw this at your feet: `var myArray = Regex.Split(myString, "(?<!^|([A-Z].*){2})(?=[A-Z])");`. If you want to know how it works (why wouldn't you?), there are plenty of Regex tutorials/guides out there that will tell you in detail what those symbols in in this regex pattern mean...
Comment: Thanks! Yes Basically split verb / noun. First word is very, everything that follows is Noun.
Answer: This can be solved in different ways; one method is the following
string source = "GetForeignKey";

var result = Regex.Matches(source, "[A-Z]").OfType<Match>().Select(x => x.Index).ToArray();
string a, b;
if (result.Length > 1)
{
    a = source.Substring(0, result[1]);
    b = source.Substring(result[1]);
}

Answer: Try the regex below
(?![A-Z][a-z]+Key)[A-Z][a-z]+|[A-Z][a-z]+Key

c# code
var matches = Regex.Matches(input, @"(?![A-Z][a-z]+Key)[A-Z][a-z]+|[A-Z][a-z]+Key");
        foreach (Match match in  matches)
            match.Groups[0].Value.Dump();

for Splitting
matches.OfType<Match>().Select(x => x.Value).ToArray().Dump();

Fiddle
Comment: Now lets try it with something like `"SetAccessDate"` ;-)
Comment: I see exactly the same as you would when using "SetAccessDate". That you would not see the same as me would be really, really surprising since it only involves setting the input string in your fiddle accordingly (on a side note, providing a fiddle is commendable, even if your answer is only working for a few limited words and not generally doing what OP is asking for). And what i saw -- and what you would see if you only would try -- is not the outcome OP is asking for.
Comment: I believe that what you are doing right now is misleading, I put one sample data, If you put `SetAccessDate` it splits it to `Set, Access, Date`. Tell me a string which does not satisfy what OP is asking for?
Comment: So much leg-pullery here... Or do you really believe OP is really only asking about just the two specific string _examples_ in their question?
Comment: Again I am asking you do you have any string/pattern example which fails? I really would like to see my mistake. Please provide me an example


How to add Cross mark inside input to clear text using ZURB css?

Question: We need to add a cross mark inside the input text box, its purpose will be to clear text from the input box.
I have added but its not showing inside input box. I am using zurb's css framework foundation.

.search-input {
    background-image: url(/assets/img/icons/search-icon.svg);
    background-size: 1.25rem;
    background-repeat: no-repeat;
    background-position: left 0.75rem center;
    text-indent: 1.8rem;
}
.input-wrapper-outer input, .input-wrapper-outer .button {
    margin-bottom: 0;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation-essential/6.2.2/css/foundation.min.css" rel="stylesheet"/>

            <form class="input-wrapper">
              <input
                class="search-input"
                data-checkval
                name="query"
                placeholder="Search ID"
                type="tel"
                pattern="[0-9]*"
              >
              <button
                title="Click me to clear the input field"
                type="reset"
                class="is-active"
              >
                x
              </button>
            </form>

Answer: Give it a position absolute and apply positioning;

.search-input {
    background-image: url(/assets/img/icons/search-icon.svg);
    background-size: 1.25rem;
    background-repeat: no-repeat;
    background-position: left 0.75rem center;
    text-indent: 1.8rem;
}
.input-wrapper-outer input, .input-wrapper-outer .button {
    margin-bottom: 0;
}

.input-wrapper{ position: relative; }

.is-active{
position: absolute;
    top: 0;
    height: 100%;
    right: 10px;
    font-size: 24px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation-essential/6.2.2/css/foundation.min.css" rel="stylesheet"/>

            <form class="input-wrapper">
              <input
                class="search-input"
                data-checkval
                name="query"
                placeholder="Search Fabric ID"
                type="tel"
                pattern="[0-9]*"
              >
              <button
                title="Click me to clear the input field"
                type="reset"
                onclick="alert('Clear')"
                class="is-active"
              >
                x
              </button>
            </form>


How do I breed Pokemon for their Hidden Abilities?

Question: I want to legitimately breed a competitive team, but I don't know how to breed for hidden abilities unless I just breed two Pokemon who have their normal ability(s) together until I breed one with a hidden ability. Does someone know a useful trick or item I could use?
Answer: Breeding two pokemon with normal abilities will never result in a pokemon with a hidden ability.
To breed a pokemon with a hidden ability, the female pokemon (or a male/genderless pokemon being bred with a ditto) must have its hidden ability. It will have a 60% chance of passing on the hidden ability.
This does, unfortunately, mean you'll need to catch or trade for a pokemon of the right species with the hidden ability to begin with.
Comment: Although not directly related to the original question, in ORAS players now have access to the DexNav which significantly helps in catching a Pokemon with a hidden ability.
The more encounters with a Pokemon, the more information the DexNav will give you, including ability and IVs.
This is a good way to get started with your HA breeding, though be mindful of natures and egg moves also.
Unfortunately I'm at work and without links to helpful resources.
Comment: @AtomPulse - If this answer helped you, you should mark it as your 'accepted answer' by clicking the checkmark under the vote count. This will award Studoku (and yourself!) with some bonus rep points :).
Comment: Thanks. What if I get a hacked pokemon? Would I still be able to breed it?
Comment: @AtomPulse - yes, although do remember that some Pokemon have unreleased hidden abilities and therefore would not be 'legal' until that HA was released
Answer: As Phil D. commented, here's some info about catching Hidden ability Pokemon with DexNav (from Bulbapedia):

At a minimum, the Hidden Pokémon screen will always show the Search Level of the target hidden Pokémon. If the player has owned the Pokémon, its type will also be displayed. When the player is close enough to the Pokémon, its silhouette and level will also be shown. Other information, such as the Pokémon's first move, Ability, held item, and potential may also be displayed, depending on the species' Search Level. If the Pokémon has a special move, Hidden Ability, high level, or high potential, an exclamation mark will appear next to that datum on the screen.
As a species' Search Level increases, it becomes possible to encounter Pokémon of that species with certain attributes, and the DexNav displays more information about hidden Pokémon of that species.

As you can see in this table, with a Search level of at least 10, and at least 2 stars potential, you can encounter a Pokemon with its Hidden Ability.

At Search Levels 5, 10, 25, 50, and 100, the chances of a hidden Pokémon having high IVs, knowing an Egg move, or having its Hidden Ability increase. Below is an approximation of these chances based on observed hidden Pokémon encounters. As these values are based on observations, the true chances may be somewhat higher or lower.


What 2 block tall mob in Minecraft drops the most xp?

Question: I've been wanting to know what 2 block tall mob in Minecraft drops the most XP can someone tell me the answer I'm trying to make a mob spawner XP farm on Minecraft
Comment: The wiki is your friend.
Answer: Blazes give the most xp.
Try this design if you dont hv much resources

But to be honest, spawner farms dont give u much xp, try build a pigmen farm if you rlly wanna grind xp


Using ExecuteSqlCommand and SavesChanges within same transaction with EntityFramework Core

Question: I am chasing an issue with MySql / EF Core where I randomly have an exception thrown saying Nested transactions are not supported. This exception does not occur when my system is only used by one user. But when I run my tests in parallel or when I have multiple users, the exception occurs. I looked at all the code and their is nothing that could create nested transactions.
The only piece of codes that scares me so far is something like the following:
using (var transaction = _context.Database.BeginTransaction())
{
    // Create a few entities and add them to the EF context
    ...

    // Insert the rows: hopefully at this point, my transaction is not commited yet.
    _context.SaveChanges();

    // I then want to update a few rows with a raw sql statement without
    // having to load the entities in memory.
    _context.Database.ExecuteSqlCommand("UPDATE ...");

    // Now that I have inserted and inserted some data, I want to commit all these
    // changes atomically.
    transaction.Commit();
}

Is this safe? Am I guaranteed that my SaveChanges and ExecuteSqlCommand will be executed on the same MySqlConnection? I have the feeling that when I call SaveChanges, it closes my connection and puts it back on the connection pool. Then, my ExecuteSqlCommand takes a new connection from the pool (it may be the same one or another one). So my initial connection (the one where I opened the transaction) is put back in the pool and it could be reused by another thread.
This is just a hunch and I am totally not sure if this could cause the problem.
My real question in the end is:

is it safe to use SaveChanges and ExecuteSqlCommand within a transaction?
Comment: Rather than guessing, use the EF Core [Logging](https://learn.microsoft.com/en-us/ef/core/miscellaneous/logging) and you'll see what's going on. But yes, you are guaranteed (or should be - in case there is no implementation bug), otherwise the whole purpose of `BeginTransaction` /  `UseTransaction` makes no sense.
Answer: I upgraded from MySql.Data.EntityFrameworkCore/MySql.Data 6.10.1-beta to 6.10.3-rc and it looks like the problem is gone. Since the problem was random I can't be totally sure that the problem is indeed fixed, but so far so good.
EDIT:
3 years later, the problem was never observed anymore.


Bounded linear operators that commute with translation

Question: I'm trying to read Elias Stein's "Singular Integrals" book, and in the beginning of the second chapter, he states two results classifying bounded linear operators that commute (on $L^1$ and $L^2$ respectively).
The first one reads:
Let $T: L^1(\mathbb{R}^n) \to L^1(\mathbb{R}^n)$ be a bounded linear transformation. Then $T$ commutes with translations if and only if there exists a measure $\mu$ in the dual of $C_0(\mathbb{R}^n)$ (continuous functions vanishing at infinity), s.t. $T(f) = f \ast \mu$ for every $f \in L^1(\mathbb{R}^n)$. It is also true that $\|T\|=\|\mu\|$.
The second one says:
Let $T:L^2(\mathbb{R}^n) \to L^2(\mathbb{R}^n)$ be bounded and linear. Then $T$ commutes with translation if and only if there exists a bounded measurable function $m(y)$ so that $(T\hat{f})(y) = m(y) \hat{f}(y)$ for all $f \in L^2(\mathbb{R}^n)$. It is also true that $\|T\|=\|m\|_\infty$.
I was wondering if anyone had a reference to a proof of these two results or could explain why they are true.
Comment: Here is a hint for the first part. Let $\phi_\epsilon(x)=\phi(x/\epsilon)/\epsilon^n$ where $$\phi(x)=\left\{\begin{array}{cl}e^{|x|^2/(|x|^2-1)}&\text{if }|x|<1\\0&\text{if }|x|\ge1\end{array}\right.$$ $\|T\phi_\epsilon\|_{L^1}$ is bounded as $\epsilon\to0$, so there is a sequence $\{\epsilon_k\}$ and a measure $\mu$ so that $T\phi_{\epsilon_k}\to\mu$ weakly in $L^1$.
Comment: @robjohn: it may be worth pointing out that the only thing you need is that you have an approximate unit in in the convolution algebra $L^1$ consisting of continuous functions of compact support. Making it explicit doesn't help much, I think. But it's a great hint!
Comment: @Theo: Yes, you are right. There is nothing special about the $\phi$ I gave, other than it is positive, has compact support, and is in $L^1$. Originally, I started out writing up a proof using this $\phi$, but due to time constraints, I posted a hint instead.  When I get time later, I may finish the proof.
Comment: Great book. For a reference check out Grafakos' "Classical Fourier Analysis". (It is not quite what you want but it is a similar result).
Comment: For the second one the definition should be $(Tf)^\wedge=m\hat{f}$ (otherwise $T$ is just multiplication by $m$ rather than a Fourier multiplier operator).
Answer: For the first one:
Let $\phi_\epsilon(x)=\phi(x/\epsilon)/\epsilon^n$ where
$$
\phi(x)=\left\{\begin{array}{cl}c\;e^{|x|^2/(|x|^2-1)}&\text{if }|x|<1\\0&\text{if }|x|\ge1\end{array}\right.
$$
and $c$ is chosen so that $\int_{\mathbb{R}^n}\phi(x)\;\mathrm{d}x=1$.
$\|T\phi_\epsilon\|_{L^1}$ is bounded as $\epsilon\to0$, so there is a sequence $\{\epsilon_k\}$ and a measure $\mu$ so that $T\phi_{\epsilon_k}\to\mu$ weakly in $L^1$.
Since $T$ is continuous, linear, and commutes with translation,
$$
\begin{align}
f*\mu(x)
&=\lim_{k\to\infty}\;\int_{\mathbb{R}^n}f(y)\;T\phi_{\epsilon_k}(x-y)\;\mathrm{d}y\\
&=\lim_{k\to\infty}\;\int_{\mathbb{R}^n}f(y)\;T(\phi_{\epsilon_k}(x-y))\;\mathrm{d}y\\
&=\lim_{k\to\infty}\;\int_{\mathbb{R}^n}T(f(y)\;\phi_{\epsilon_k}(x-y))\;\mathrm{d}y\\
&=\lim_{k\to\infty}\;T\left(\int_{\mathbb{R}^n}f(y)\;\phi_{\epsilon_k}(x-y)\;\mathrm{d}y\right)\\
&=T\left(\lim_{k\to\infty}\;\int_{\mathbb{R}^n}f(y)\;\phi_{\epsilon_k}(x-y)\;\mathrm{d}y\right)\\
&=Tf(x)
\end{align}
$$
For the second one the definition should be $(Tf)^\wedge=m\hat{f}$ (otherwise $T$ is just multiplication by $m$ rather than a Fourier multiplier operator). Let $\psi(x)=e^{-\pi x^2}$ so that $\hat{\psi}=\psi$.
$$
\begin{align}
\psi(\xi)\;(Tf)^\wedge(\xi)
&=(\psi*Tf)^\wedge(\xi)\\
&=\left(\int_{\mathbb{R}^n}\psi(x-y)\;Tf(y)\;\mathrm{d}y\right)^\wedge(\xi)\\
&=\left(\int_{\mathbb{R}^n}\psi(y)\;Tf(x-y)\;\mathrm{d}y\right)^\wedge(\xi)\\
&=\left(\int_{\mathbb{R}^n}T^{\;*}\psi(y)\;f(x-y)\;\mathrm{d}y\right)^\wedge(\xi)\\
&=(T^{\;*}\psi)^\wedge(\xi)\hat{f}(\xi)
\end{align}
$$
Let $m(\xi)=(T^{\;*}\psi)^\wedge(\xi)/\psi(\xi)$, then we have
$$
(Tf)^\wedge(\xi)=m(\xi)\hat{f}(\xi)
$$
and therefore, $\|m\|_{L^\infty}=\|T\|_{L^2}$.
Comment: Why $\left\|m\right\|_{\infty}=\left\|T\right\|_{L^2}$?
Comment: $$ \int_{\mathbb{R}^n}\frac{\phi(x/\epsilon)}{\epsilon^n}\,\mathrm{d}x = \int_{\mathbb{R}^n}\phi(x)\,\mathrm{d}x $$
Comment: Please read my last two comments. All of the $\phi_{\epsilon_k}$ have **the same** $L^1$ norm; so, yes, the limit is $\lt\infty$.
Comment: The [Internet Archive Wayback Machine](https://web.archive.org/) has it at [weak-convergence.pdf](https://web.archive.org/web/20130512112622/http://jpmandallena.pagesperso-orange.fr/weak-convergence.pdf)
Comment: [Approximation of the Identity](https://en.m.wikipedia.org/wiki/Dirac_delta_function#nascent_delta_function)
Comment: I have two simple questions here: 1. Isn't the argument rather that you have a sequence $\phi_{\epsilon_k}$ that converges weak$^{\ast}$ in $(C_0)^{\ast}$ and do your computation for $f$ continuous with compact support first and then extend the equality $f \ast \mu = Tf$ for $f \in C_c$ to all of $L^1$ by continuity of both sides? 2. You say "so there is a sequence ... and a measure $\mu$ such that $\phi_{\epsilon_k} \to \mu$ weakly in $L^1$". What result do you have in mind here? I've never seen such a statement and re-proved variants by hand as needed. Could you give me a reference, please?
Comment: @robjohn: I was going to ask the same question as Theo. Also, how do you go from $\int f(y) T(\phi_{\epsilon_k}(x-y)) dy = \int T(f(y)) \phi_{\epsilon_k}(x-y) dy$? Wouldnt it be $T^*$?
Comment: @Theo: $L^1$ is a subset of the signed Radon measures, $\mathcal{M}$, which is the dual of $C_c$. $\mathcal{M}$ is weakly-* compact in that any bounded sequence $\{\mu_k\}$ in $\mathcal{M}$ contains a subsequence which converges weakly-* to some $\mu\in\mathcal{M}$ (that is when tested against any $f\in C_c$). One reference is [Weak and weak star convergences](http://jpmandallena.pagesperso-orange.fr/weak-convergence.pdf).
Comment: @user1736: your parentheses do not match mine. I am simply using the linearity and translation invariance of $T$ (that is, $T$ is operating on $x$, and $y$ is just translation that can be moved outside $T$).
Comment: @robjohn: Thanks for the reference, but you're essentially saying the same as I did in my comment. However, you want to take the dual of $C_0$ (functions vanishing at infinity) not of $C_c$ (functions of compact support--which you usually don't equip with the sup-norm but with a different topology). By the way, Theorem 7.1 in the linked notes is wrong in that the space $C_c$ is *not* complete wrt the sup-norm. I do object to your usage of "converges weakly in $L^1$", then (which would involve duality with $L^\infty$). But it's merely a technical detail and I'm happy with your argument.
Comment: @Theo: I had originally written $C_0$, but the reference I cited used $C_c$, so I thought that perhaps I had misremembered. Of course you are correct, and $C_c$ should be changed to $C_0$ in my last comment. My weak vs weak-* notation was a little sloppy, too.
Comment: @robjohn: Oh, I think I can see what you mean. So you're also just using linearity to pull $T$ outside of the integral, and to pull the limit inside then, right?
Comment: @user1736: linearity to pull $T$ outside, and continuity to pull the limit inside. Yes.
Comment: @robjohn Does your solution for part (ii) show both directions?
Comment: @user412674: my answer shows that if $T$ is a bounded linear operator on $L^2$ that commutes with translations, then $T$ is a Fourier multiplier operator with a bounded measurable function. The other direction follows pretty easily by [Plancherel's Theorem](https://en.wikipedia.org/wiki/Plancherel_theorem).
Comment: $|T\varphi_{e_k}|_{L^1}\leq C|\varphi_{e_k}|_{L^1}$
now, why $\varphi_{e_k}$ is bounded in $L^1$?
Comment: Each $\varphi_{\epsilon_k}$ has the same $L^1$ norm by the dilation properties of that norm.
Comment: I have this: $|Tϕϵ|L1≤C|ϕϵ|L1$ because $T$ is bounded. $|Tϕϵ|L1$ is bounded when $ϵ→0$ if$ |ϕϵ|L1$ is bounded when $ϵ→0.$ Now, |ϕ_e|_{L1}=∫|x|<1ce|x/ϵ|2/(|x/ϵ|2−1)endx . Then limϵ→0 $\int_{|x|<1} \frac{ce^{{|x/\epsilon|^2}/{(|x/\epsilon|^2-1)}}dx<\infty?$ –
Comment: Thank you. I have already understood that part.
Of course, there are other parts that I still don't understand ...
Will you by chance have the reference of the star convergence that was in the link above? (the link is down)
Comment: Thanks.
At what step did you use that the linear transformation T is invariant under translations? I can't see where it's used.
I know that T invariant traslation if $\tau_{h}T=T\tau_{h}$ for every $\tau_{h}$ traslation.
Comment: $f(x)=\lim_{k\to \infty} \int f(y)\phi_{e_{k}}(x-y)dy$ It is a result of a theorem?
Comment: thanks but Is there a result similar to theorem 7.12 of the link https://web.archive.org/web/20130512112622/http://jpmandallena.pagesperso-orange.fr/weak-convergence.pdf, with $C_ {0}$ instead of $C_ {cc}$?
Comment: The dual space of $C_{cc}$ is contained in dual space of $C_{0}$?
Ask this then, the statement says that there is a measure in the dual space of $C_0$. But, theorem 7.12 of the link above says that there is a measure in the space of measures of positive Radon, which is dual of $C_ {cc}$.
In this way, I want to see that given a measure $\mu\in (C_ {cc})^ {\ast})$ then $\mu \in (C_ {0})^{\ast}$ which I don't know if it's true ...
$C_{0}\subset C_{cc}$ implies $(C_{cc})^{\ast}\subset (C_{0})^{\ast}$?
Answer: Let me just give a literature reference, in case that's what you are interested in. The classical paper on translation invariant operators on Lebesgue spaces is Hormander's 1960 Acta paper "Estimates for translation invariant operators in $L^p$ spaces". If you have access to MathSciNet, here's the mref.
Answer: A bounded linear operator $ T: L^2 \to L^2$ and commutes with translation
Known result from Riesz Representation theorem see here:$\int Tf(s)u(s) ds=\int f(s)T^*u(s)ds$ written as $<Tf,u>=<f,T^*u>$, where $ T^*$ is the linear adjoint operator of $ T $ , $ u \in L^2$
now for $f(s)$ translated  by $x$ ,$f(s+x)$
we have $\int Tf(s+x)u(s)ds=\int f(s+x)T^*u(s)ds$
Now take Let $u_{\epsilon}=\phi_\epsilon(s)=\phi(s/\epsilon)\epsilon^{-1}$ where
$\phi(s)$ is normalized gaussian function with zero mean.
$\int Tf(s+x)u_{\epsilon}(-s) ds=\int Tf(s+x)u_{\epsilon}(s)ds=\int f(s+x)T^*u_{\epsilon}(s)ds$
$H(s)=Tf(s)$ , by translation commutation $H(s+x)=Tf(s+x)$
$R(-s)=T^*u_{\epsilon}$
we have $\lim_{\epsilon \to 0} H* u_{\epsilon}=\lim_{\epsilon \to 0} f*R$
$\lim_{\epsilon \to 0} H*u_{\epsilon}=H(x)$ ae
for $u \in L^1$ function, we have the following theorem regarding fourier transform:
$v(x)=g*u=\int g(s)u(x-s) ds$
for $g \in L^2$ , define $\hat{g}=lim_{n \to \infty}\int_{n}^{-n}g(s)e^{2i\pi x z} dx$ the limit exists in the sense of $L^2$. If $u \in L^1$ and $\int |g(s)||u(x-s)| ds \le P$ where $P$ is a non negative integrable function in $L^2$ then $\hat{v}=\hat{g}\hat{u}$
Proof : $g_n=g1_{[-n,n]},v_n=g_n*u$
it's known that $\hat{v_n}=\hat{g_n}\hat{u}$
By dominated convergence theorem $lim_{n \to \infty} ||v-v_n||^2=0$
and by Plancherel theorem $lim_{n \to \infty} ||v-v_m||^2= lim_{n \to \infty} ||\hat{v}-\hat{v_n}||^2=0$
This implies $lim_{n \to \infty} \hat{v_n}=\hat{v}$
Now from our equation when $u$ is a normalized  Gaussian we have $|H|* |u_{\epsilon}| \le MH(x)$ where $MH(x)$ is the Hardy Littlewood Maximal function (also $ ||MH(x)||^2 \le ||H(x)||^2$)
using Fourier transform $\hat{H}(z)\hat{u_{\epsilon}}(z)=\hat{f}(z)G(z)$ where $G(z)=\hat{R}$
$\lim_{\epsilon \to 0}\hat{ u_{\epsilon}}=1$
$\lim_{\epsilon \to 0}G=m(z)$
consequently we have $\hat{Hf}(z)=m(z)\hat{f}(z)$


C# - Try/Catch Log and Rethrow is a bad practice?

Question: I can see several post where importance of handling exception at central location or at process boundary been emphasized as a good practice rather than littering every code block around try/catch. I strongly believe that most of us understand the importance of it however i see people still ending up with catch-log-rethrow anti pattern mainly because to ease out troubleshooting during any exception, they want to log more context specific information (example : method parameters passed) and the way is to wrap method around try/catch/log/rethrow.
Is there right way to achieve this while still maintaining exception handling good practice ? I heard of AOP framework like PostSharp for this but would like to know if there is any downside or major performance cost associated with these AOP frameworks.
Thanks!!
Answer: After little search here and there, I consider answering it myself:
Try/Catch/throw/log littered across methods and code is not a good practice. You should ask below questions when you think of this :
What specifically you going to do with that exception ? If answer is swallow, I would say you need to think twice. If state is corrupted because of swallowing exception in a catch block, then some method higher up in call stack might again throw exception - And now what to do with this exception ? Again same cycle ? It will lead you to a bigger mess soon.
You might sparingly want to follow the pattern of catching exception immediately when you really know you can do something with it (like swallow and retry in case of sql timeout exception) Also you might want to catch exception immediately in case when you want to capture more context specific details in log. In that case catch and re throw new exception wrapping original exception as inner exception.
So in short - its good to have exception handling/logging at application root level or service boundary level.
Having said that - at centralized location you can also configure what to do with specific types of exception. For example :
Bad Request exception thrown as part of data validation in business layer would simply return 400 bad request (in case of web application)
In case exception is of type SqlException - throw generic Exception to client with some tracking ID and log detailed exception to eventlog/db/application insight etc.
In case of any exception from external system in business layer - again send generic exception to client and send notification email to system providing external service.
These are just few examples and good practice around exception handling also implicitly promotes good design. For example: why not to have a safe guard to ensure argument passed to method is not null and throw ArgumentNullException rather than catching NullReferenceException and then capturing arguments value by having try/catch/log at method level.
I posted question around exception handling and logging good practices here. Please check it has good debate and discussion with various suggestions and good practices.


Empty variable in for-loop

Question: I have this one-liner which works entirely fine.
import random
from string import ascii_letters, digits

def pwd_generator(pwd):

    password = "".join([random.choice(ascii_letters + digits) for i in range(pwd)])
    print(password)

I wanted to translate that now into a 'normal' for-loop.
def pwd_generator(pwd):
    password = ''
    for i in range(pwd):
        password.join([random.choice(ascii_letters + digits)])

    print(password)

In this scenario however, password is empty.
Why is the variable empty when I try to write it in a 'proper' for-loop?
Comment: you are not _assigning_ the value from join to anything - so it's return is lost ...
Comment: you're doing 2 different things. `join` returns a value and you're doing nothing with it in the 2nd example.
Answer: Strings are immutable so password.join returns a string but doesn't save it to password. Instead you should be saving your strings in a list and joining them at the end:
password = []
for i in range(pwd):
    password.append(random.choice(ascii_letters + digits)

return "".join(password)

Comment: Thanks, that worked. I first tried to append the string, or join it to the list but not to append to a list.

Empty variable in for-loop


GWT Catching exception thrown by HttpServlet

Question: From the server Code (in an HttpServlet) I'm throwing an exception if the file is too large:
 public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
 ...
 // Check if the blob has correct size, otherwise delete it
 final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
 long size = blobInfo.getSize();
 if(size > 0 && size <= BasicConstants.maxImageSize){
    res.sendRedirect("/download?blob-key=" + blobKey.getKeyString());
 } else { // size not allowed
    bs.delete(blobKey);
    throw new RuntimeException(BasicConstants.fileTooLarge);
 }

From the client code I'm missing to successfully  catch the exception with this snippet:
try {
    uploadForm.submit(); // send file to BlobStore, where the doPost method is executed
} catch (Exception ex) {
    GWT.log(ex.toString());
}

However, from this other client code snippet I'm somehow detecting when the exception was thrown with an ugly workaround that I don't trust at all:
uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

    @Override
public void onSubmitComplete(SubmitCompleteEvent event) {
// This is what gets the result back - the content-type *must* be
// text-html
String imageUrl =event.getResults();

    // This ugly workaround apparently manages to detect when the server threw the exception
if (imageUrl.length() == 0) { // file is too large
  uploadFooter.setText(BasicConstants.fileTooLarge);
} else { // file was successfully uploaded
       ...
    }

The Development Mode view in Eclipse reports an error of type "uncaught exception", which suggests that I'm really doing a bad job at detecting it.
Can anyone tell me how to properly catch the exception, and if the workaround I'm using makes any sense?
Thanks!
Comment: @george_h If you're talking about GWT-RPC, that doesn't work for file uploads.
Comment: You are not using the standard GWT servlets? Usually those have asynchronous callbacks that return any exceptions thrown by the servlet.
Answer: Your first attempt
try {
    uploadForm.submit(); // send file to BlobStore, where the doPost method is executed
} catch (Exception ex) {
    GWT.log(ex.toString());
}

doesn't work, because submit() doesn't wait until the browser receives the response (it's an asynchronous call).
uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

  @Override
  public void onSubmitComplete(SubmitCompleteEvent event) {
    ...

Here you actually receive the response from the server. But it's a form submission, not a GWT-RPC call, so the result is just plain text, not GWT Java Objects.
When you throw a RuntimeException in a Servlet, the server will simply send a response with an error code (probably '500', but ideally use the "Network" tab in Firebug or Chrome Developer Tools to see the actual response and response code.) So in the success case you'll  get the URL, otherwise the response is empty.
Possible solution
You can catch Exceptions on the server side, and send better descriptions explicitly:
public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

  try {

      ...
      if (...) {
        throw new MyTooLargeException();
      } else {
          ...
        res.getWriter().write("ok " + ...);
      }

  } catch (MyTooLargeException e) {
     res.getWriter().write("upload_size_exceeded"); // just an example string
                                                    // (use your own)

     res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
  }
}

Then, on the client, check for
"upload_size_exceeded".equals(event.getResults()).

Comment: Thanks Chris, I like your solution.
Comment: @Chris Lercher What if the server disconnected,due to network issues ??I am unable to handle this exception.Why i am asking this is I just started uploading a file.So put a mask on client,Network gone,It never comes to `onSubmitComplete` handler.Can you please help me out?


Spot light LED bulbs (MR16) flash once when turned on. If I put 1 normal halogen in then it solves the problem. Why?

Question: I have 5 spot light bulbs in my bathroom. All use MR16 connection. I replaced them all with 5w LEDs and when I turn on the switch they flash once then go off. If I remove one so there's only 4 then the same thing happens. However, if I put one of the old halogen 20w bulbs in then all the LED bulbs stay on and everything is fine.
Why is this happening? And what can I do to get rid of that last halogen and replace it with an LED?
Comment: Its a normal switch. Like stated in my question, if I put 1 halogen back in then the 4 LED bulbs hold their light. Seems like a halogen needs to be in there to draw enough power to the circuit or something?
Comment: Can you check the voltage on your halogens. There are some light fixtures that run off a lower voltage (a ballast or transformer may be in the fixture).
Comment: @EdBeal I would reword to "check the voltage in the sockets" just to be clear :-) .
Comment: I would check both the voltage of the lamp that works and the voltage supplied. There are 120V lamps if this style and 12 or 24v. if the lamp has 12v or 24v stamped on it there should be a transformer.
Comment: Are these on a dimmer? some dimmers will not work with LED's. What happens if you put 1 halogen in place of one of the LED's
Comment: If it was (just) a transformer, he wouldn't be having this problem.
Answer: This symptom is impossible without silicon electronics being involved in the delivery of power. Passive wires and windings are not capable of causing this.  Common problems are common, and my first take is usually correct - a series connected old-style smart device.
But Carl Witthoft has an interesting theory: these are probably low voltage bulbs.  We know voltage is right because the LEDs do work properly when power is available.  That's not surprising, since many LED products use constant current power supplies in switch mode, which can easily accommodate a range of voltage.
Most low voltage power supplies are passive, or at least well behaved.  So I normally don't think about them.  It would certainly explain everything if you had one that was "too smart for its own good".  The five LEDs should draw power comparable to one halogen (at least on half the AC cycle... since the D stands for "diode"). So there's clearly something a little more sophisticated going on.  I could see some power supply designer thinking himself oh, so clever for adding a protective circuit that shuts the supply off if it doesn't detect any halogens.  To be fair, LED lighting is a very new concept.
For reference, the usual cause - and my first guess - and the one to apply if this proves to be 120VAC circuit -- relates to dimmers, sensors and other smart devices designed to substitute for an old switch in a "switch loop", where there is no neutral.  These devices place themselves in series with the bulb, and power themselves by letting some current flow through the circuit when the light is "off".  This depends on particular characteristics of incandescent (and halogen) bulbs.  It often doesn't play well with fluorescents and LEDs.  This is why Code now requires neutral in switch loops - so a new generation of these devices can power themselves directly off hot and neutral.  For this, the answer can be to roll back to a plain switch - unless neutral happens to be in the box, in which case use a modern device.
Comment: the same thing happens. It seems as if the circuit requires a halogen in there to draw enough power.... as if a minimum amount is required.

e.g.
1 - 5 LEDs - flashes once.
1 - 4 LED & 1 halogen - both light up and stay lit
Comment: It is already a human operated switch. Not a dimmer. just a standard switch.
Comment: Bizarre!  There's got to be something. LEDs don't do that by themselves.  Longshot it's some sort of interaction between LEDs, what happens if only a single LED is plugged in?
Comment: not accurate or true.
Answer: According to any number of help pages, e.g.  this one, MR16 sockets  and bulbs are designed for 5 to 24 V operation.  It's highly likely that's what you've got here.  So the question becomes: what is your current operating voltage, and what is the voltage requirement for the LED bulbs you bought?  If there's a mismatch, that's why things don't work.
Comment: Nope.  The LEDs work fine when the upstream electronics decide to turn the power on.  Ergo voltage is correct and may be 120V.  This symptom is impossible without electronics involved somehow, and your low-voltage theory does explain how that might be.   And this... is how the hivemind works.  We both have a chunk of the problem and are both part right and part wrong.
Comment: I have a very similar problem with 12VAC halogen track fixtures on a 120VAC track. Replacing the halogen bulbs with LED ones, results in the LED flashing at power-on and then going dark. The behaviour is the same regardless of whether one or all of the halogen bulbs are replaced with LEDs. I disassembled one of the track fixtures and found a 120VAC to 12VAC step down coil feeding the bulb. The coil and at least one capacitor are sunk in resin inside the fixture. So I think I either need a smarter fixture, or to bypass the analogue circuit w/my own digital one.


Concrete foundation crack

Question: Two storey home, 14yrs old.  Concrete foundation.  Ground is mostly clay.  Steel I beam crossing the middle of the basement ceiling to distribute load.  The I beam is inset into the top of the concrete foundation.  The outside foundation wall appears to be failing where it meets the steel beam, but just on one end of the house.  However, the inside appears non-stressed.  How much trouble am I in (if any)?  Is this just cosmetic?
Pleasesayyes.
Outside view

https://drive.google.com/file/d/0Bxo3SkpN46OaV28wZHkyNlpaVG8/view?usp=docslist_api
Inside view (no visible cracks)

(I have more pics, but it wouldn't let me post more than 2)
3 months later...
Just for closure... I followed the given answer and seem to have had success.
@Jason Hutchinson  that would've been a good idea, but I ended up using a 5 pound sledge and busted out all the loose concrete which was pribald for the best.  It looked sandy inside the like the concrete may have had a nugget of unmixed sand or something clumped at that spot.  After the loose concrete was removed it exposed some rebar I was able to wrap wire around and bind in some huge metal spikes and long bolts I had on hand to give my planned patchwork more to hold to.  I bought a 80lb bag of fiber-laced anti-crack concrete mix, and a piece of melamine shelving from lowes to act as the outside form and give the smoothest finish.  Drilled some holes in the melamine.  Rigged up some of the wire around the rebar work and poked it though the holes... and used the wire though the holes to draw the melamine tight to the wall (twisting the wire around more bolts on the outside of the melamine till it tightened up).  It finished well.  Dark at first, but it has now lightened to (mostly) match the surrounding concrete. I think an inspector will pass it by.
Answer: Seems that steel beam is sitting on a wall which is sitting on a footing so at best I would think you want to mix up some mortar and cover that crack so the inspector does not see it because it seems to be cosmetic to me. It looks like the house settled and you need to keep water out now
Comment: So, I am guessing the beam has shifted over some small amount, just enough to "pop" out the thin concrete covering that end.  Would it be better to fill the crack?  Or would it "look" better if I cleared out the cracked area that is loose and go for a smooth-to-the-wall solution?  (What is currently there is almost 1" proud of the surface and may be noticed if just the cracks are filled.)  Good catch on the inspector thing.  We are looking to sell soon.  :)
Comment: You can use an angle grinder with a diamond cup wheel to smooth out the area before you fill it in to make it appear to be smoother.

Concrete foundation crack


How to create a layout?

Question: I am trying to display the triangle with nodes similar to this picture in my Android app

And I have only two drawables. First is of circle and second one is of line.
I have searched a lot on internet but not getting any solution to which layout I should use and how I can achieve display this triangle on Android.
I cannot take an entire image of this triangle as in the place of nodes that would be some dynamic data displayed at run time.
Comment: Why not using custom views?
Answer: Use a custom view with the help of Android Canvas and its methods drawLines() and drawCircle()
Here is how to create Custom Views and here is a very nice, short tutorial on how to use these methods to draw any shape.
Sample
// somewhere in the constructor, call this
private void init() {
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setColor(Color.RED);
    mPaint.setStyle(Paint.Style.STROKE);
    // mPaint.setStrokeWidth(SOME_VALUE);
    ...
}

// override onSizeChanged() to make your measurements.
// if you need 'finer' control, override onMeasure(), but be careful with that one
// (read its javadocs before you override it).
// measurements include shape and text locations and sizes, etc.
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    mTriangleVertices[0] = 0.2  * w; // x0
    mTriangleVertices[1] = 0.15 * h; // y0

    mTriangleVertices[2] = 0.5  * w; // x1
    mTriangleVertices[3] = 0.85 * h; // y1

    mTriangleVertices[4] = 0.8  * w; // x2
    mTriangleVertices[5] = 0.15 * h; // y2
    // other calculations...
}

// after you save your measurements to some fields, override onDraw().
// use all the tools you created and the info you gathers above here.
// avoid creating objects at all cost. read the docs for more info.
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas); // include this first, last or you can even omit it sometimes

    canvas.drawLines(mTriangleVertices, 0, mTriangleVertices.length, mPaint);

    // canvas.drawCircle(); canvas.drawOval(); etc..
}

How to create a layout?


TypeError : 'NoneType' object not callable when using split in Python with BeautifulSoup

Question: I was playing around with the BeautifulSoup and Requests APIs today. So I thought I would write a simple scraper that would follow links to a depth of 2(if that makes sense). All the links in the webpage that i am scraping are relative. (For eg: ) So to make them absolute I thought I would join the page url with the relative links using urljoin.
To do this I had to first extract the href value from the  tags and for that I thought I would use split:
#!/bin/python
#crawl.py
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin

html_source=requests.get("http://www.flipkart.com/books")
soup=BeautifulSoup(html_source.content)
links=soup.find_all("a")
temp=links[0].split('"')

This gives the following error:
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    temp=links[0].split('"')
TypeError: 'NoneType' object is not callable

Having dived in before properly going through the documentation, I realize that this is probably not the best way to achieve my objective but why is there a TypeError?
Answer: links[0] is not a string, it's a bs4.element.Tag. When you try to look up split in it, it does its magic and tries to find a subelement named split, but there is none. You are calling that None.
In [10]: l = links[0]

In [11]: type(l)
Out[11]: bs4.element.Tag

In [17]: print l.split
None

In [18]: None()   # :)

TypeError: 'NoneType' object is not callable

Use indexing to look up HTML attributes:
In [21]: links[0]['href']
Out[21]: '/?ref=1591d2c3-5613-4592-a245-ca34cbd29008&_pop=brdcrumb'

Or get if there is a danger of nonexisting attributes:
In [24]: links[0].get('href')
Out[24]: '/?ref=1591d2c3-5613-4592-a245-ca34cbd29008&_pop=brdcrumb'

In [26]: print links[0].get('wharrgarbl')
None

In [27]: print links[0]['wharrgarbl']

KeyError: 'wharrgarbl'

Answer: Because the Tag class uses proxying to access attributes (as Pavel points out - this is used to access child elements where possible), so where it's not found the None default is returned.
convoluted example:
>>> print soup.find_all('a')[0].bob
None
>>> print soup.find_all('a')[0].foobar
None
>>> print soup.find_all('a')[0].split
None

You need to use:
soup.find_all('a')[0].get('href')

Where:
>>> print soup.find_all('a')[0].get
<bound method Tag.get of >

Comment: Child elements, not attributes.
Answer: I just encountered the same error - so for what it's worth four years later: if you need to split up the soup element you can also use str() on it before you split it. In your case that would be:
    temp = str(links).split('"')