Gatling - Log body of request in simulation.log or console

Question: I would like to see what is in the body of the post that I am sending in my script. In fact, I would like to see the request, request body and response. From looking at the docs and the forums, I see that I can uncomment a line in logback-test.xml which I did as shown below

<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
    <resetJUL>true</resetJUL>
</contextListener>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
        <immediateFlush>false</immediateFlush>
    </encoder>
</appender>

<logger name="io.gatling.http" level="TRACE" />

<root level="DEBUG">
    <appender-ref ref="CONSOLE" />
</root>

The simulation.log file nor the console shows me the request, response etc. After a bit of googling and reading documentation, I saw that I could do this -
.extraInfoExtractor(extraInfo => List(extraInfo.request, extraInfo.response,extraInfo.session))

This provides me with pretty much everything except the request body. How do I get the request body? I am trying to debug an issue where I am sure the body that is getting sent is not what I actually want.
Answer: Add this to your logback.xml
<logger name="io.gatling.http.ahc" level="DEBUG" />

This will print following details for each failure -

Request url
Request header
Request body
Response header
Gatling session data
Comment: Weirdly I'm getting success requests being logged as well
Comment: DEBUG did not work for me, but TRACE did:
Answer: <?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
            <immediateFlush>false</immediateFlush>
        </encoder>
    </appender>

    <timestamp key="timestamp" datePattern="yyyy-MM-dd'T'HH:mm:ss"/>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/test_${timestamp}.log</file>
        <append>true</append>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
        </encoder>
    </appender>

    <logger name="io.gatling.http.engine.response" level="TRACE" />

    <root level="INFO">
        <appender-ref ref="FILE" />
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>

Comment: works for gatling 3. just edit the line ``
Comment: This works for Gatling 3.6 in windows server to log in a file
Comment: I tired this but log file is not getting created on the fly is there any thing else needs to be done.           ch.qos.logback.core.FileAppender[FILE] - openFile(logs/app_2022-01-06T16:06:11.log,false) call failed. java.io.FileNotFoundException: logs\app_2022-01-06T16:06:11.log (The filename, directory name, or volume
label syntax is incorrect)
Answer: Uncommenting only TRACE and leaving DEBUG commented helped.
Answer: An update with Gatling 3.x, the comment in logback.xml is quite self-explain

After uncomment the above config we can get the request url, request header, response etc in the log or IDE'S console. That's very helpful to verify the dynamic feeder value used in request url or body, and it's the way to debug the failed requests.
Answer: Just choose the root level as DEBUG

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
    </encoder>
    <immediateFlush>false</immediateFlush>
</appender>

<logger name="io.gatling.http.engine.response" level="DEBUG" />

<root level="DEBUG">
    <appender-ref ref="CONSOLE" />
</root>

Comment: @TomerShetah
No, there is an example with

that is important and

io.gatling.http.engine.response
Comment: @Kozak, isn't that the same answer as provided by Bhushan Bhangale at https://stackoverflow.com/a/35381270/2359227?
Answer: If you want to see logging of all HTTP requests and responses plus Session contents in your console output you can do the following:

Add or uncomment the following lines in your logger file:

<logger name="io.gatling.http.ahc" level="TRACE" />
<logger name="io.gatling.http.response" level="TRACE" />

Set root level as TRACE:

<root level="TRACE">
    <appender-ref ref="CONSOLE" />
</root>


I have some problems,related to title() method in python

Question: we know that title() method capitalizes the first letter of a string but if my string starts with a digit e.g. "I     love to watch   3d movies". My expected output for this string is "I     Love To Watch   3d Movies".The title method is capitalizing also the letter "d", how can I solve this problem
s=input()
p=s.title()
print(p)

Comment: you can loop throught the string and check if the first char is not a number. if not then capitalize it and if not then don't. to implement this you have to loop throught s.split() and then make your check
Answer: This is not a bug, it is a feature!
Let me cite the documentation:

The algorithm uses a simple language-independent definition of a word
  as groups of consecutive letters. The definition works in many
  contexts but it means that apostrophes in contractions and possessives
  form word boundaries, which may not be the desired result

In short - you are welcome to improve the implementation and raise a merge request to the Python standard library code.
Answer: I tried using the capitalize function and seems that it does what you want to achieve:
s = "i love watching 3d movies"
res = ""
for t in s.split():   # loop through your string
    res += t.capitalize()+ " "   # capitalize the first word

print(res)    # I Love Watching 3d Movies

so if you need the spaces to stay there you have to do it manually. you can check the index or make a counter where exactly you need those spaces and then just add spaces when i=1 or when i=4 for example. But if you just want to change the "D" to "d" this can be easily replaced with the replace method:
s = "i    love watching     3d movies"

result = s.title().replace("D", "d")

another solution is you can check for the index of the numbers in your string:
def get_numbers_index(strng):
    for i in range(len(strng)):
        try:
            int(strng[i])
            return i
        except:
            pass

i = get_numbers_index(s)   # get the index of the number in your str
s1 = s.title()   # Capitalize your str
res = s1.replace(s1[i+1], s[i+1])  # replace the character after the number with the lower value of the first string
print(res)    # I    Love Watching     3d Movies

Comment: Thanks for your feedback but there are some spaces between "I" and "love", also between "watch" and "3d"
Comment: so you don't need spaces ? or what exactly is the expected output ?
Comment: Yeah I need those spaces
Comment: well apparently you have to do it manually. I ll post a solution on to make it manually
Comment: Okay but I can't do it  manually.What if my inputs are random!
Comment: @SunjareeIbnZulfiker you can make a function to return the index of the number in your string and then replace the character next to it
Comment: @SunjareeIbnZulfiker it should now work as you expected.
Comment: @SunjareeIbnZulfiker did that worked for you or did you encounter another problem?
Comment: @SunjareeIbnZulfiker can you please accept the answer so that it will be closed ?


Query access variable outside query based on condition in NodeJS and MongoDB

Question: I have a schema like below:
[
  {
    "_id": 1,
    "showResult": true,
    "subject": "History",
  },
  {
    "_id": 2,
    "showResult": false,
    "subject": "Math",
  }
]

and an object in JS like below:
result = {
 "History": 22,
 "Math": 18
}

I am using aggregate to process query, in between i need to find score based on subject field in the document if showResult field is true i.e to access result variable inside query as map result[$subject]
My query:
db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      "score":{$cond: { if: { $eq: [ "$showResult", true ] }, then: subjectObj[$subject], else: null }}

    }
  }
])

can this be done in MongoDB, i want result like below:
{
 _id: 1,
 score: 22
}

Comment: my next aggregation pipeline depends on the result form this part
Answer: I think query is little costly than JS code, but i am adding the query if it will help you as per your question,

$match showResult is true
$project to show required fields, $reduce to iterate loop of result after converting from object to array using $objectToArray, check condition if subject match then return matching score

let result = {
 "History": 22,
 "Math": 18
};
db.collection.aggregate([
  { $match: { showResult: true } },
  {
    $project: {
      _id: 1,
      score: {
        $reduce: {
          input: { $objectToArray: result },
          initialValue: 0,
          in: {
            $cond: [{ $eq: ["$$this.k", "$subject"] }, "$$this.v", "$$value"]
          }
        }
      }
    }
  }
])

Playground


Google Cloud Datastore / Mobile Backend Starter - Permissions failure on update/updateAll calls

Question: Using the Mobile Backend Starter (MBS) Android classes (those distributed as a sample project when creating a new project in Google Dev Console and demoed at Google I/O 2013) I'm able to insert new entities to the cloud datastore via calls to CloudBackendMessaging.insertAll or .updateAll.  The latter will create entities if none exist so seems functionally identical to insert for new records.
The insertion/creation works fine.  However when I attempt to update existing entries in the datastore, I received permissions errors e.g.  (from the backend log)

Method: mobilebackend.endpointV1.updateAll
Error Code: 401
Reason: required
Message: Insuffient permission for updating a CloudEntity: XXXXXX by: USER: YYYYYYY

which results in a matching access error in the logcat client side.
In all cases I am using Secured access authenticating with a valid Google account (my own).
The entities being inserted are thus showing as "owned" by my user ID with "updated by" and "created by" showing my Google account's email address.
However when the update of the existing record is made, using exactly the same CloudBackendMessenger object and thus same credentials etc. the backend is telling me I can't update due to permissions issues.  But surely if I just made the entity with the same credentials this can't be correct? Looking at the documentation it appears that I should be able to edit entities owned by the same user ID in all cases (regardless of the KindName and whether it is prepended [public], [private] or nothing).
Can anyone who has received permissions errors on UPDATES via Mobile Backend Starter for Datascore please shed any light?  I have been banging my head over this for most of today.
Comment: It seems a workaround on this is to query i.e. get the CloudEntity you want to update e.g. via a list() call, and then update it via an update() call.  However it would be nice / more efficient if you could directly execute an update on an Entity (specified via it's UID i.e. setId()) without having to get it first.
Comment: Did you also try using "transactions" to update a single entity?https://developers.google.com/appengine/docs/java/datastore/transactions
Comment: @Franz Noel.  That's interesting - could you please elaborate on how transactions can be used with MBS on the mobile/client side with a CloudEntity in this way perhaps with a code snippet?
Answer: I've faced the similar error "Insuffient permission for updating a CloudEntity" when using cloudBackendAsync.update(cloudEntity). I resolved it by making sure the cloudEntity has it's createdAt field set. createdAt is autogenerated and I think I am not supposed to touch it. But it worked for me. In my case I am first obtaining list of cloud entities. This is when I get createdAt field of cloud entities. Then when I am updating I setting the createdAt field from previously obtained entities.
Edit: Had to do similar thing for owner field also.
Comment: You can check createdAt format from google dev console. Go to your app console -> cloud datastore ->Query -> select kind and you can see your entities listed.
Comment: That's very interesting - and probably explains why if I "get" i.e. list the record and then update with it, then I can actually perform the update without permissions issues.  I wonder if there is a way to set the createdAt field to the correct value without actually getting the record first (for performance reasons - I have a lot of updates to make).  Do you know how that field is formatted / can be synthesised?
Comment: Ok I will give it a shot.  Many thanks for the tip, who knew creation date would give a permissions error ?
Comment: I had to do the same thing for owner field also. Entity was getting updated successfully but owner field was missing which is also originally autogenerated.
Answer: Similar to one of the comments above, I successfully got around this by getting the original CloudEntity before doing the insert/update/delete function.
<code>    CloudQuery cq = new CloudQuery("datastoretype");
    cq.setLimit(1);
    cq.setFilter(Filter.eq("_id",id));

    cloudEntity.setId(id);
    mProcessingFragment.getCloudBackend().get(cloudEntity, handler);
</code>
Thereafter it was trivial to do the following:
<code>    mProcessingFragment.getCloudBackend().update(cloudEntity, handler);
</code>
The docs definitely ought to be more clear on this, whether it is a strict requirement or bug.
Comment: I am trying to follow your code but I can't see how you have used the cloudquery in your update. I also get an error when trying your filter. So would you be able to post your full code here?
Answer: The answers posted so far work around the problem if you don't mind all users being able to access the entity you are trying to update. However, a better solution that retains the access permissions is detailed by google here - https://cloud.google.com/cloud/samples/mbs/authentication

If you want to pass the user's Google Account info to the backend on
  each call, use the CloudBackend#setCredential() method (also available
  on the subclasses, CloudBackendAsync and CloudBackendMessaging) to set
  a GoogleAccountCredential object before calling any Mobile Backend
  methods.

<code>GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(this, "<Web Client ID>");
credential.setSelectedAccountName("<Google Account Name>");
cloudBackend.setCredential(credential);
</code>

Setting credientials enables the client to operate when the backend is
  in "Secured by Client ID" mode and also sets createdBy/updatedBy/owner
  properties of CloudEntity automatically.
Comment: It seems I spoke too soon as I have since tried to implement this myself and have run in to problems - http://stackoverflow.com/questions/26306006/cloudbackend-setcredential-not-setting-createdby-updatedby-owner-properties-of-c


T9 Torx Screw Thread diameter in Metric System

Question: Helllo,
I have to design a part that will have screws that can be taken apart with a T9 Torx Screwdriver. These are the screws that are taken apart first thing here.
What is the thread diameter of the screw that mates with the T9 torx screw in the Metric System?
On this website they mention "point-to-point" dimensions. But I am unable to understand what that refers to.
Comment: "I want to find out the thread diameter of the screws that are on that engine". Then this is the question you should be asking, and you should probably ask in the comments section of the video, or look for a support forum for that particular car and ask there. Thread pitch/diameter are _not_ determined by the head of the screw, the head of the screw is determined by the thread diameter.
Comment: If not mistaken most screwdriver sizes will fit a range of screw sizes/diameters, instead of being specific to one size only.  Seems like a bad way to design a part to be based on screwdriver size.
Comment: "T9" tells you about the *head* of the screw. It tells you nothing about the *threads*.
Comment: There are ways to check the thread size of a screw.  If you ask that question here you'll get an answer.     You should explain a little more about what you are trying to achieve.  Where are you and where are you going?  It seems unlikely that you don't know the difference between a screw head and its thread, and yet you are designing replacement parts for jet engines.
Comment: @jay613 A bachelor's course in aerospace engineering probably fits this bill. I remember ordering my first set of M10 bolts without specifying length for example... I got a box of 10mm ones.
Comment: If for an engine, jet engine as a comment mention, knowing the size is the least you want to know about the screw.  Those screws also have specific strength and composition demands.  You usually don't pick them up at the local hardware store.
Comment: T9 is a funny size, not at all common. An M2 is usually a T6, M2.5 a T8, M3 a T10… these are not absolutes, but having had a toolkit full of them for 15 years, that's kind of what you expect for general purpose. I can't even find a bolt supplier with T9 heads listed. It's going to be something pretty specialist, funny size makes it so you need a very precise spec, can't just pick them up in B&Q. You're going to need an M2.75 [which I just made up on the spot] Point to point, btw, is the measurement between two opposite points in the 'star'.
Comment: Ah! Well the thing is that I want to find out the thread diameter of the screws that are on that engine shown in the video. The information I have available is that they can be loosened by a T9 screw driver
Comment: Ah, I did find a list of all the M sizes, in intricate detail. https://www.engineersedge.com/hardware/metric-external-thread-sizes1.htm Still not going to tell you what torx driver to use, but there is a spec for M2.6, no 2.75, so that might be your guy.
Answer: The T9 is the type of screwdriver you'll need to remove/install the screw. It's similar to saying a slotted screw or a Phillips screw. It has no bearing on the thread size. If you need the thread size, you'll have to find a blueprint of the engine or a parts list on their website.
Answer: There is NO standard for wrench size vs screw size in metric.
I checked, because it kept coming up.
In point of fact, T9 is a real oddball, there's no earthly reason they couldn't have stepped down to the more common T8, or up to the extremely common, and part of every set T10.  They are doing that on purpose, to make the device non-user-serviceable.
For that matter, who's to say the machine screws are even metric?  I see what looks like a Starbucks coffee, and that's definitely an L14-20 or -30 twist-lock socket in frame. That plus the accent tells me we're probably in the United States, and the screws might be standard.
Standard generally follows SAE guidelines, which do specify head size for bolt size. Show me a 1/4" bolt I'll show you a 7/16" hex. I don't think they delve into Torx, but  SAE definitely would not approve of oddball sizes like T9 when a common size like T10 is right next door.
Comment: @manassehkatz-Moving2Codidact - I was always 'middle ground' - multimedia installations, service & maintenance, for retail stores. Nothing huge, nothing tiny. Lots of M3 & 4 bolts… & wing nuts, for some godforsaken reason ;) …and we seemed to have a deal with some factory who made self-drillers. Killer-drillers, go through anything, usually making it non-saleable as it went through the guts of 'demo models' which were often real products destroyed by fixing them into demo stands.
Comment: +1 I even checked the Chinese suppliers who make *'everything'* including M2.6 which I've never even seen in real life - & they still jump from T8 to T10.
Comment: @Tetsujin My Chinese cheap tools are better than yours :-) I've got T3/T4/T5/T6/T7/T8/T9/T0/T15/T20 in my latest little toolkit. But I agree it is an oddball.
Comment: @manassehkatz-Moving2Codidact - LOL. I tend to use Wiha bits, because they need replacing about once a decade or so, but they don't include the low, odd numbers, odds start at 15. ;) The bits themselves are relatively easy to find, but bolts to match them, another kettle of raspberries entirely...
Comment: @Tetsujin My tools are split between the heavy duty stuff (just checked my set of DeWalt bits - also made in China, but decent quality - and they start at T15) and *lots* of small tools for phones/laptops/etc. (which is closer to what I actually do for a living).


AngularJS app not running correctly

Question: I'm new to AngularJS.  I'm trying to run a simple example from a book, but it's not working correctly, and I can't figure out why.
This code runs fine:

    <meta charset="UTF-8">
    <title>Angular </title>

        <input ng-model="greeting.text"/>

{{greeting.text}}, World!

But this is the code I'm having problems with

    <title>Shopping Cart</title>

Your Order

        {{item.title}}
        <input ng-model="item.quantity">
        {{item.price| currency}}
        {{item.price * item.quantity| currency}}
        <button ng-click="remove($index)">Remove</button>

Expecting this output:

But getting this output:

I don't understand why I'm not getting the data output, and why it's not repeating.  Basically, why the example is not running.  I copy and paste the code straight from the book.
Comment: What are you including angular.js twice?
Comment: Remove the app name from `ng-app`, or run a `.configure` statement before your controller. Also, check your console, there's most likely a nice descriptive error there.
Comment: move the controller code out of the controller
Comment: @Richard Dalton Forgot to remove that from the code. That doesn't fix the problem though.
Answer: When you write ng-app='myApp' you are saying to angular that exists a module named myApp somewhere.
Just add this line before your controllers definition:
var myApp = angular.module('myApp',[]);
You can see the docs here and here
Answer: You should define your myApp module:

    <title>Your Shopping Cart</title>

Your Order

        {{item.title}}
        <input ng-model='item.quantity'>
        {{item.price | currency}}
        {{item.price * item.quantity | currency}}
        <button ng-click="remove($index)">Remove</button>

Comment: I'm not sure, but including `angular.js` only once could help, too.
Answer: Or you can also add the namespace:

Even though, adding the module is the best way.
Answer: Give the name of app as html ng-app="myapp" in html file  and then add/define the module into the controller as
var myapp = angular.module('myapp', []);
Answer: Even I faced this problem, resolved it by invoking module creation scope before controller js . Also ensure module is created in script or js file.
Answer: I fixed.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>

Your order

    {{item.title}}
    <input ng-model="item.quantity" />
    {{item.price | currency}}
    {{item.price * item.quantity | currency}}
    <button ng-click="remove($index)">Remove</button>

AngularJS app not running correctly


Can I replace an improperly supported tub easily?

Question: I have a fiberglass garden tub in the home I just bought that wasn't installed right. The far side has no support under the lip and as a result it likes to loose its seal to the tiles above. My current solution has been to recaulk it every time it cracks but this has gotten rather annoying over the past few months.
Is it possible for me to rip out the tub and either replace it or fix the supports without redoing the whole shower area? (ie tile and plumbing). Does anyone have any recommendations on howto do it?
Answer: The tub should be supported underneath where it sits on the subfloor, not just at the lip. Usually the manufacturer specifies that the tub be set into a bed of thinset mortar to make sure it's well supported across the entire bottom surface.  We have a tub that's doing the same thing.
The easy fix is to remove all the caulk around the edges, then fill the tub with water before recaulking, only draining the tub after the caulk has had time to dry fully.  This ensures that the caulk seam stays mostly in compression even when the tub is full of water and people, reducing the chance that it will get pulled apart.  I've done this to ours and it's lasted well so far (granted, it's only been a few months now -- we just moved here in April).
What I'd eventually like to do, as our fiberglass tub still creaks when you walk in it, is to open up the adjacent wall and try to get thinset mortar underneath the tub.  My plan is to gently pry the base of the tub upward with shims, then slather mortar underneath as much as possible, and then remove the shims so that the tub settles into the mortar.  This might be an option for you, but it might involve some tile work depending on where you can get access to the subfloor under the tub.
I know this doesn't do much to answer your specific question about the feasibility of removing and replacing your tub.  That's difficult to answer without knowing exactly how your tub is installed.  I have to think that's going to be a big job though, no matter how it's installed.
Comment: If all you used were a "few screws", then you're going to be glad you've made it easily replaceable in a couple of years.  It's true that some manufacturers don't specify bedding the tub in thinset, but many do.  It just occurred to me -- do you think I'm talking about setting the tub into a tub-sized pool of mortar?  That would be completely idiotic.  I'm talking about a 1/2" layer underneath the tub to fill any gaps between the tub & floor.  It's easy to remove a tub from a bed like this if it ever does need to be replaced.
Comment: What?  That's overkill. My tub I screwed in a few screws along the lip and it was good.  And that's all the manufacturer called for.  If you mortor in your tun you will never be able to replace it.
Comment: Thanks for the tip! I'm going to try that when it cracks next time. (Before I take the plunge to replace the tub.)


How to re-wire coax through floor

Question: First, thanks for reading and please know I'm on mobile asking, where I'm not the best at coherency.
I bought a house that has holes to run coax cable through an upstairs wall down to a hole in a closet underneath. This hole is about 3 feet below the ceiling of the closet.
I'm trying to feed coax cable through the hole upstairs down, but am struggling to thread the cable through the downstairs hole.
Most tutorials online are to either install electrical wiring or install plates - neither of which fit my scenario.
Any thoughts? Should I try a bent hanger?
Comment: Why do the wall plates not fit your scenario?  Got a sketch?
Answer: By all means try a bent coat hanger. What do you have to lose?
Comment: I can't tell if this is sarcastic or not...I'm pretty sure any wires in the walls would be grounded, but that would be my concern lol
Comment: It **might** work to get some stout string, tie a plastic grocery shopping bag to the end and use a shop vac on the lower hole,.  Feed the bag/w string into the upper hole.  I use this trick all the time, but it's on conduit.   If you have too many air leaks in your route, it probably won't work,  But IMHO, it's worth a try.   You may need to enlarge the holes.
Comment: @EricHorodyski   Coax would not be grounded in the walls.
Comment: @EricHorodyski  Electric wires in a wall will have insulation.  Unless you grind a point on the hanger and start jabbing it into stuff it should be safe.
Answer: A basic wire hanger certainly makes for a valid and budget fishing tool. I would suggest however to ignore the coax for the moment and  use whatever fishing tool you come up with and attach some light twine rope. With the twine run through either end of wall/floor then attach the coax to that. The extra step will save a great deal of headache and time while pulling it through.
For any wall outlets I'd recommend using low voltage receptacle boxes. Minimal extra cost for a tidier end product and rather than basic hole and grommet. Would be a good time to run some ethernet also. Even if not needed now will save another headache later.

How to re-wire coax through floor


Minecraft loot table 1.14.4

Question: I am in need to the answers to the following questions about loot tables in 1.14.4.

What is the command to spawn in your custom loot table chest
Wheres the directory to put the custom loot table in the .minecraft folder
A working loot table generator for the latest version of Minecraft

p.s If I have got the wrong tags or theres another question on going that can
    help. I am truly sorry
Answer:
/give @p chest{BlockEntityTag:{LootTable:"custom_namespace:loot_table.json"}} or /setblock ~ ~ ~ chest{LootTable:"custom_namespace:loot_table.json"}
.minecraft/saves/nameOfWorld/datapacks/datapack_name/data/custom_namespace/loot_tables
Loot Table Generator for Minecraft

You need to create a custom namespace for your loot table (the above assumes its custom_namespace) and also create a pack.mcmeta file in the "datapack_name" folder. The command is for a loot table called loot_table.json. To specify a loot table in a folder, use custom_namespace:folder/loot_table.json.
More information: Loot table
Comment: Hi, I have tried that even keeping everything the same from your example but am still getting an empty chest and i don't know why I have my .json file in the loot_tables folder after the ".minecraft/saves/nameOfWorld/datapacks/data/customNamespace/loot_tables"  but it still happens.
Comment: @MatthewSmith Is the loot table's path `...customNamespace/loot_tables/loot_table.json` or `...customNamespace/loot_tables/loot_tables/loot_table.json`? From your comment, it seems like you've put the json file in another loot_tables folder inside the existing one.
Comment: Note that if you are in survival the chest you place down won't have any items in it. It only works if you are in creative and place it down, or if you use the setblock command instead.
Comment: Also, @cherryblossom, it seems like you skipped a portion of the directory and used improper casing. Did you actually test this yourself? You actually need to create a folder in between "datapacks" and "data" designating the name of the datapack, and it needs to have both the "data" folder in it as well as a "pack.mcmeta" file.
Comment: @ZachK I actually don't own Java Editon, so I couldn't test it. Thanks for fixing it!
Comment: So I have my folders and it goes `.minecraft/saves/MYMAP/datapacks/demo/data/custom_namespace/loot_tables` I have my loot_tablew.json inside the loot_tables folder and the pack.mcmeta in demo is this correct? @ZachK @cherryblossom
Comment: @MatthewSmith Yes, that is correct. Note you also need a pack.mcmeta file inside your "demo" folder. Type `/reload` and `/datapack list` in your world when you are done with your datapack. You should see "[demo]" show up in chat. Finally, you can check if the loot table has loaded correctly by using the `/loot` command.

Minecraft loot table 1.14.4


How to fix a dripping part in toilet?

Question: This part in my toilet slowly drips water:

It's not a big problem but I still want to fix it.  I already tried to screw the part as tightly as possible but it did not change.
Comment: I am a little curious on what the heck that black wire/line is coming up from behind the toilet on the right.
Comment: @B Mitch:  That's the "Zapper", if your on the toilet too long 120VAC up the keister is a good way to persuade you to hurry up.
Answer: Should be an easy fix.  Shutoff the water at the valve on the wall.  Unscrew the leaking joint.  Try cleaning or replacing the washer.  And then reattach.
If that doesn't work, replace the hose.  They are sold with the plumbing supplies with the other toilet parts.  The only part that is throwing me off is the white plastic angled piece in the hose.  So if you need that, and can't find an exact match in the hardware store, you're better off just fixing the washer.
Edit: looking at the picture again, I'm guessing the white plastic is the inside of the hose and the metal braiding is pulling back from the end.  If that's the case, I'd replace the whole hose with something a little longer.  I'm pretty sure they come in several lengths in the store, and you could use an extra 6" to make a better curve in the line.

How to fix a dripping part in toilet?


Prevent full table scan for query with multiple where clauses

Question: A while ago I posted a message about optimizing a query in MySQL. I have since ported the data and query to PostgreSQL, but now PostgreSQL has the same problem. The solution in MySQL was to force the optimizer to not optimize using STRAIGHT_JOIN. PostgreSQL offers no such option.
Update Revised
I have isolated the part of the query that fixes the problem (d.month_ref_id = 1):
select
  d.*
from
  daily d
join month_ref m on m.id = d.month_ref_id
join year_ref y on y.id = m.year_ref_id
where
  m.category_id = '001' and
  d.month_ref_id = 1

However, I can't hard-code a month reference to 1. The query that produces a full table scan is:
select
  d.*
from
  daily d
join month_ref m on m.id = d.month_ref_id
join year_ref y on y.id = m.year_ref_id
where
  m.category_id = '001'

The index on daily.month_ref_id is:
CREATE INDEX daily_month_ref_idx
  ON climate.daily
  USING btree
  (month_ref_id);

Why is the query performing a full table scan and what can be done to avoid it?
Thank you!
Answer:
Even though it might not make much a performance difference, I would use Join clauses for join the tables instead of cross joins and the Where clause.
You are calling a function in the Where clause which will cause the system to do a table scan. It will not matter what database you use, this is going to be true.
Why the Left Join on City? Do you know for a fact that the given Id will exist (in this case 10663? If so, you should use an inner join.
You might be able to given the compiler hints about how to formulate the query using parenthesis (I'm not sure if Postgres will honor them).

Select  avg(d.amount) AS amount,  y.year
From (station s
        Left Join city c -- You want to cross join on city? Why not use an Inner join?
            On c.id = 10663
                And 6371.009
                  * SQRT(
                        POW(RADIANS(c.latitude_decimal - s.latitude_decimal), 2)
                        + (
                            COS(RADIANS(c.latitude_decimal + s.latitude_decimal) / 2)
                            * POW(RADIANS(c.longitude_decimal - s.longitude_decimal), 2)
                            )
                        ) <= 50)
    Join station_district sd
        On sd.Id = s.station_district_id
    Join year_ref y
        On y.station_district_id = sd.id
    Join month_ref m
        On m.year_ref_id = y.id
    Join daily d
        On d.month_ref_id = m.id
Where s.elevation Between 0 And 2000
    And y.year Between 1980 And 2000
    And m.month = 12
    And m.category_id = '001'
    And d.daily_flag_id <> 'M'
Group By y.year
Since you are not using the station, station_district nor city table in the results, you might be able to move those to an exists statement:
Select  avg(d.amount) AS amount,  y.year
From year_ref y
    Join month_ref m
        On m.year_ref_id = y.id
    Join daily d
        On d.month_ref_id = m.id
Where y.year Between 1980 And 2000
    And m.month = 12
    And m.category_id = '001'
    And d.daily_flag_id <> 'M'
    And Exist   (
                Select 1
                From station s1
                    Join city c1
                        On c1.id = 10663
                Where 6371.009
                      * SQRT(
                            POW(RADIANS(c1.latitude_decimal - s1.latitude_decimal), 2)
                            + (
                                COS(RADIANS(c1.latitude_decimal + s1.latitude_decimal) / 2)
                                * POW(RADIANS(c1.longitude_decimal - s1.longitude_decimal), 2)
                                )
                            ) <= 50
                    And S1.station_district_id = y.station_district_id
                )
Group By y.year
Comment: @Dave Jarvis - I had a typo in the query in that I had the station_district table in the inner query. I've corrected that. Btw, another solution would be a derived table (akin to a subquery in the From clause) that isolates the mathematical calculation and forces the compiler to execute separately.
Comment: @Dave Jarvis - If the month_ref and daily tables are the largest and will benefit the most from filtering, then you might try putting those into a derived table with their criteria.
Comment: @Dave Jarvis - If you comment out the Exists statement, do you still get a table scan? If so, then either there isn't an index on daily_flag_id or given the criteria, the compiler thinks that doing a table scan is more efficient for some reason. RE: Query parameter, I do not see why you couldn't use your parameter. The real question whether you can avoid a scan under optimal circumstances using static values.
Answer: I don't know what other variations of the query you've tried, but the JOIN on City seems a little strange - have you tried replacing that with a WHERE clause? Also, the relationships between the various tables are currently in the WHERE clause - these are probably best implemented as an INNER JOIN.
Disclaimer: I don't know PostreSQL specifically.
EDIT: Here's a link that describes changing WHERE clauses to JOINs to influence join order, and discusses the join_collapse_limit to force the optimizer to use your specified join order.
http://www.postgresql.org/docs/8.2/static/explicit-joins.html
EDIT2: Another alternative is to nest SELECT statements, which may also force the optimizer to construct the query in the (reverse) nesting order you specify.
Comment: What about moving the WHERE clasues as joins? See my edit - using joins seems to be the way to go to provide a hint about join order.
Answer: I think the FTS is occurring because of the way you have parameterized your query / joins. By this, I mean that you have two parameters, one is being compared against a column in the 'daily' table, and another is being compared against a column in the 'month-ref' table. However, both of these values can be used to filter rows in a single table 'month-ref'. Make that table the primary table in your query and re-write your query as follows:
select
  d.*
from month_ref m
join daily d on d.month_ref_id = m.id
join year_ref y on y.id = m.year_ref_id
where
  m.category_id = '001' and
  m.id = 1

This way, the database can easily locate all the necessary rows in the month-ref table based solely on the input parameter values, and rows in the daily table can be easily located over the specified join using the index you described.
Depending on the number of rows might be found in the month-ref table, and whether either of the columns referenced above contain distinct values, you may need to create an index on the month-ref table.


how does ethereum web3js imports "crypto-js"?

Question: I am a bit confused by the syntax used in the web3.js file of the ethereum repository, although there is no file named crypto-js nor any npm or yarn, how is this import is being done? https://github.com/ethereum/go-ethereum/blob/master/internal/jsre/deps/web3.js#L1828
Comment: You are looking minified source. I suggest you look original source files.
Comment: You do not need geth Ethereum console. If you want to to run JavaScript, you can just execute web3.js and make it connect whatever Go Ethereum node you are running over HTTP or IPC JSON-RPC.
Comment: this is the built in version that is used inside ethereum console, I want to modify it @MikkoOhtamaa
Comment: is there a way to change the unminified web3 and then inject it  in the ethereum? @MikkoOhtamaa
Comment: Not sure exactly, I do see an npm module [crypto-js](https://github.com/brix/crypto-js) which is being used in ethereum, also [sha3](https://github.com/brix/crypto-js/blob/develop/src/sha3.js). Am I missing something here?
Answer: The javascript file you're looking at (web3.js) is the result of web3's build, i.e., a browserify bundle of the whole web3 project and its dependencies. The entire crypto-js library from npm is bundled in that file - that's why there's no other references to crypto-js within the go-ethereum project. Let's take a look at the object containing the code you've linked, which looks something like this:
{
    //...
    19: [
        function(require, module, exports) {
            //...
            var CryptoJS = require('crypto-js');
            var sha3 = require('crypto-js/sha3');
            //...
        },
        {
            "crypto-js": 59,
            "crypto-js/sha3": 80
        }
    ]
    //...
}

This key/value pair represents a module. The key 19 is an ID for the module within the bundle. The value is an array with two elements: (1) the module code and (2) the module's dependencies. The dependencies are given as an object with module name keys and module ID values. Thus, the crypto-js module can be found in the same object under key 59, and likewise crypto-js/sha3 under key 80.
Modifying web3.js can be done by obtaining the source and rebuilding it. The version in the go-ethereum repo seems to be 0.20.1, which corresponds to commit 996148d3 in the web3 repository. Building this version is somewhat of a pain, as back then web3 did not commit package-lock.json. I was able to build it by forcing the use of gulp 3.9 and node 10. As for replacing crypto-js, you can edit lib/utils/sha3.js and replace it with a different sha3 implementation.
After rebuilding web3, copy dist/web3-light.js to internals/jsre/deps/web3.js in the go-ethereum repo and run go generate to regenerate internals/jsre/deps/bindata.go. Finally, build geth.
Putting this all together:
# Clone web3
git clone https://github.com/ChainSafe/web3.js
cd web3.js
git switch -c replace-crypto-js 996148d356570745ef20630b499bce37f8484920

# Edit the sha3 implementation
vim lib/utils/sha3.js

# Build using gulp 3.9 and node 10
sed -i 's/"gulp": ">=3.9.0"/"gulp": "^3.9.0"/' package.json
npm install
npm --no-save install node@10
PATH=./node_modules/.bin gulp

# Clone go-ethereum
cd ..
git clone https://github.com/ethereum/go-ethereum.git
cd go-ethereum

# Copy new web3 and regenerate bindata.go
cp ../web3.js/dist/web3-light.js internal/jsre/deps/web3.js
make devtools
PATH=$PATH:$(go env GOPATH)/bin go generate internal/jsre/deps/deps.go

# Build geth and test out changes in console
make geth
./build/bin/geth console


Ruby: If last variable was saved more than 3 hours ago

Question: I have a ruby form to submit reports for an exercise on my app.  An exercise has_many reports.  I want to create an if statement that makes this form only appear if the last report from that exercise was saved more than 3 hours ago.
So far I have:
But this is creating a NoMethodError saying undefined method 'report' for #<Exercise:0x007f9c892f48b0>.
It's being displayed on my workouts#show page (a workout has_many exercises, in case it helps), so I believe this is the reigning controller:
class WorkoutsController < ApplicationController
  def index
    @workouts = Workout.all
  end

  def show
    @workout = Workout.find(params[:id])
    @exercise = Exercise.new
    @report = Report.new
  end

  def new
    @workout = Workout.new
    @workout.user_id = current_user
  end

  def create
    @workout = Workout.new(workout_params)
    @workout.user = current_user

    if @workout.save
      flash[:notice] = "Workout was saved successfully."
      redirect_to @workout
    else
      flash.now[:alert] = "Error creating workout. Please try again."
      render :new
    end
  end

  def edit
    @workout = Workout.find(params[:id])
  end

  def update
    @workout = Workout.find(params[:id])

    @workout.name = params[:workout][:name]
    @workout.workout_type = params[:workout][:workout_type]
    @workout.teaser = params[:workout][:teaser]
    @workout.description = params[:workout][:description]
    @workout.video = params[:workout][:video]
    @workout.difficulty = params[:workout][:difficulty]
    @workout.trainer = params[:workout][:trainer]
    @workout.user_id = params[:workout][:user_id]

    if @workout.save
       flash[:notice] = "Workout was updated successfully."
      redirect_to @workout
    else
      flash.now[:alert] = "Error saving workout. Please try again."
      render :edit
    end
  end

  def destroy
    @workout = Workout.find(params[:id])

    if @workout.destroy
      flash[:notice] = "\"#{@workout.name}\" was deleted successfully."
      redirect_to action: :index
    else
      flash.now[:alert] = "There was an error deleting the workout."
      render :show
    end
  end

  private
  def workout_params
    params.require(:workout).permit(:name, :workout_type, :teaser, :description, :video, :difficulty, :trainer, :user_id)
  end
end

Any ideas where I'm going wrong?
ADDITIONAL INFORMATION:
This bit is technically on my workouts#show page:
<% if @workout.exercises.count == 0 %>

Looks like you get a freebie for this one!  No score report today.  Rest up and drink some water.  It ain't always that easy...

      <% else %>
        <% @workout.exercises.each do |exercise| %>
          <%= render 'reports/form', report: @report, exercise: exercise %>
          <% if current_user.admin? %>

<%= link_to "Delete #{exercise.name}", [exercise], method: :delete, data: { confirm: 'Are you sure?' } %>

          <% end %>

        <% end %>

But here is the partial it renders, where the code in question actually lies:
<% if exercise.report.last != nil && exercise.report.last.created_at < ( DateTime.now - (3/24.0)) %>

<%= form_for report,
  :url => { :controller => "reports",
  :action => :create,
  :exercise_id => exercise.id } do |f| %>

...

Comment: Can you paste the code from your show view? It seems like you might be calling `@exercise.report` which does not exist?
Comment: Whats in yr show html page ?
Answer: It seems you calling singularized report instead of reports.
if exercise.report.last

If reports relates to exercise as has_many you need to call it with exercise.reports.last
Also, you mentioned results in your question, but calling reports in your view.

An exercise has_many results.

...

exercise.report.last

Please be sure you calling appropriate pluralize method reports or results
Comment: Those darn plurals!  Thank you.
Comment: Yeah, indeed. Welcome :)


Eigenspace decomposition for semisimple module

Question: Let's start with a prime $p$ and a group $\Delta$ of order prime to $p$. Let $M$ be a finite $\mathbb{F}_p[\Delta]$-module of order a power of $p$. I want to find a decomposition into eigenspaces according to the action of $\Delta$ on $M$.
I know that it is easy to find such a decomposition as $\mathbb{Z}$-modules into cyclic modules (as in the theorem of finitely generated abelian groups), however, I'm having trouble showing that those cyclic modules are invariant under the action of $\Delta$.
I know that $M$ is semisimple, but is the non-canonical decomposition of $M$ into simple $\Delta$-modules invariant under the action of $\Delta$?
Thank you so much for your help! :)
Comment: Ok, Maschke's theorem gives an decomposition of $M$ into simple $\mathbb{F}_p[\Delta]$-modules which are in fact invariant under the action of $\Delta$.
Answer: Maschke's Theorem is the key fact here. For the detailed answer, look here


How do I customize the length of the token generated in :token_authenticatable in devise - Rails 3?

Question: My token generated seems to be about 20 characters, how do I change the length to something else ?
I checked the devise.rb file and tried both:
config.token_authentication_key = :access_key
config.token_authenticatable.length = 40

produced this error:
config/initializers/devise.rb:110:in `block in <top (required)>': undefined method `token_authenticatable' for Devise:Module (NoMethodError)

and
config.token_authentication_key = :access_key
config.token_authentication_key.length = 40

produced this error:
/config/initializers/devise.rb:110:in `block in <top (required)>': undefined method `length=' for :access_key:Symbol (NoMethodError)

and both gave me errors when I tried to run the console.
Is there anyway to do this ?
Answer: Devise does not provide a functionality to set the length of this token. You would have to override the generate_token method on your model to change the outcome of this token.
Answer: I achieved changing the reset_token_password length overriding the friendly_token method. For example:

module Devise
  def self.friendly_token(_length = 20)
    SecureRandom.urlsafe_base64(5).tr('lIO0', 'sxyz')
  end
end

(Remember that the tokens are hashed in the db so even though you successfully set a shorter code if you do user.reset_password_token you will see a long code which is the hashed token, not the real one.)


No WiFi adapter found Ubuntu 18.04

Question: my WiFi adapter Qualcomm Atheros QCA9565/AR9565 Wireless Network Adapter.doesn't work or even appear in the system settings.I'm using ubuntu 18.04 with a dual boot with windows 10.the WiFi adapter works in windows.
output of lspci -knn | grep Net -A3:
03:00.0 Network controller [0280]: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter [168c:0036] (rev 01)
Subsystem: Lite-On Communications Inc QCA9565 / AR9565 Wireless Network Adapter [11ad:0803]
Kernel modules: ath9k

lspci -knn | grep Net -A2
03:00.0 Network controller [0280]: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter [168c:0036] (rev 01)
Subsystem: Lite-On Communications Inc QCA9565 / AR9565 Wireless Network Adapter [11ad:0803]
Kernel modules: ath9k

sudo rfkill list
0: hci0: Bluetooth
Soft blocked: no
Hard blocked: no

sudo lshw -C network
*-network

   description: Ethernet interface
   product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
   vendor: Realtek Semiconductor Co., Ltd.
   physical id: 0
   bus info: pci@0000:02:00.0
   logical name: enp2s0
   version: 15
   serial: 1c:39:47:53:6c:4b
   size: 10Mbit/s
   capacity: 1Gbit/s
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
   configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=rtl8168h-2_0.0.2 02/26/15 latency=0 link=no multicast=yes port=MII speed=10Mbit/s
   resources: irq:-2147483648 ioport:3000(size=256) memory:c1104000-c1104fff memory:c1100000-c1103fff
 *-network UNCLAIMED
   description: Network controller
   product: QCA9565 / AR9565 Wireless Network Adapter
   vendor: Qualcomm Atheros
   physical id: 0
   bus info: pci@0000:03:00.0
   version: 01
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress cap_list
   configuration: latency=0
   resources: memory:c1000000-c107ffff memory:c1080000-c108ffff
 *-network
   description: Ethernet interface
   physical id: 1
   logical name: enp0s20u1
   serial: 76:f5:dc:14:1d:16
   capabilities: ethernet physical
   configuration: broadcast=yes driver=rndis_host driverversion=22-Aug-2005 firmware=RNDIS device ip=192.168.42.239 link=yes multicast=yes

dmesg | grep ath9k
[   21.252360] ath9k 0000:03:00.0: PCI INT A: not connected
[   21.252404] ath9k 0000:03:00.0: request_irq failed
[   21.252423] ath9k: probe of 0000:03:00.0 failed with error -107

Comment: Please [edit] your question and add output of `lspci -knn | grep Net -A3` terminal command.
Comment: It is not the full output.
Comment: it is the acer e5 573 laptop
Comment: The `-A3` should show the module in use or some other device.
Comment: i'm sorry pilot6  i don't understand what you mean
Comment: I mean that we need the full output of `lspci -knn | grep Net -A3 `
Comment: it only shows this      03:00.0 Network controller [0280]: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter [168c:0036] (rev 01)
 Subsystem: Lite-On Communications Inc QCA9565 / AR9565 Wireless Network Adapter [11ad:0803]
 Kernel modules: ath9k
Comment: here is the output of the script a user from Ubuntu forums told me to use http://paste.ubuntu.com/p/dHC8F3Gby9/
Answer: Pay you attention command lspci -knn | grep Net -A2 output contains no line Kernel driver in use. Just do
sudo modprobe ath9k

Next check the wireless module for soft and hard block
sudo rfkill list

As your laptop is Acer, try
echo blacklist acer-wmi | sudo tee -a /etc/modprobe.d/blacklist-acer-wmi.conf

Reboot the laptop and try lspci -knn | grep Net -A2 and sudo rfkill list again.
If nothing helps try No Wifi on Acer Aspire E5 573 on any Linux Platform.
And finally try solution from post #22 from here.
ADDENDUM
Do
cd
sudo apt update
sudo apt install git
git clone https://github.com/kvalo/ath10k-firmware.git
sudo rm -rf /lib/firmware/ath10k
sudo cp -r ath10k-firmware/ /lib/firmware/ath10k/
sudo mv /lib/firmware/ath10k/QCA6174/hw2.1/firmware-5.bin_SW_RM.1.1.1-00157-QCARMSWPZ-1 /lib/firmware/ath10k/QCA6174/hw2.1/firmware-5.bin
sudo chmod +x /lib/firmware/ath10k/QCA6174/hw2.1/*
sudo chmod +x /lib/firmware/ath10k/QCA6174/hw2.1/firmware-5.bin

Reboot laptop.
ADDENDUM #2
Try
sudo apt install --reinstall linux-firmware

Reboot laptop.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/79960/discussion-on-answer-by-wiking-no-wifi-adapter-found-ubuntu-18-04).
Answer: I had the same problem with ubuntu 17 and i solved following the below steps.
First of all, I tried to download the network kernel from site --> https://ubuntu.pkgs.org/17.10/ubuntu-restricted-amd64/bcmwl-kernel-source_22.214.171.1241+bdcom-0ubuntu3_amd64.deb.html
If your architecture is x64,
sudo dpkg -i bcmwl-kernel-source_18.104.22.1681+bdcom-0ubuntu3_amd64.deb
sudo apt install -f

Then, I saw the configuration of network service
 cat /etc/NetworkManager/NetworkManager.conf

By default, there are
 [main]`
 plugins=ifupdown,keyfile

 [ifupdown]
 managed=false

 [device]
 wifi.scan-rand-mac-address=no

if it is different of yours, change it.
Then, you need to restart the kernel configuration.
  sudo service network-manager restart

Reboot the computer.
On bios, change the boot secure:
boot secure: disabled   ->    boot secure: enabled

And ok.
Works in ubuntu 17, Positivo Stilo XCi7660.
bye
Answer: As I had problems with the WiFi network and Atheros driver on ubuntu I asked for advice also on askubunt. The laptop did not show a WiFi network. On the internet, tips like installing drivers for a WiFi adapter didn't help.
I solved the problem by simply resetting the router. So it was not a problem in the laptop or ubuntu but the router. Try resetting the router or resetting the router to factory settings.
Also if you've installed linux on your laptop multiple times you've probably made a mess with secure boot and maybe that's why you can't have WiFi on ubuntu if secure boot is enabled. Therefore, before a clean new installation of ubuntu, reset the BIOS / UEFI secure boot to factory settings and reinstall ubuntu.  At least that's how it is on an acer laptop.
Admin sorry I followed up on an old topic but it might help someone.

No WiFi adapter found Ubuntu 18.04


How can I tag files and search them later based on the tag?

Question: Running Ubuntu Gnome.
I have a lot of PDF and other documents and I will like to tag them. And search them later based on these tags. Even if I move the files to different folders (so, the tags stick to the files).
I searched but Files and Documents do not provide this options.
Am I doing something wrong? How can I tag files so I can search them based on tags later?
Comment: For only the adding tags to PDF documents part of the question (but not the searching tags part of the question) see [this answer](http://askubuntu.com/questions/401114/which-is-the-best-pdf-metadata-viewer-for-ubuntu/401350#401350)
Comment: Would you consider "bookmarking" a file as option  instead of tagging ?
Comment: @Serg I'm not clear. Can you explain a bit? Can these bookmarks have tags like Firefox bookmarks? Will they remain even if I move the file?
Comment: @deshmukh  Here's what I've done before: http://askubuntu.com/q/803644/295286  Basically it creates a symlink to file inside a folder. On the other hand,  I could implement  sort of  list of tags, and for each tag there would be list of files.  Currently I'm somewhat busy, so it takes me forever to respond, but I will try to   put out the answer ASAP. Would it be possible to put the bounty again once this one times out ?
Comment: @Serg I am not rich enough to offer another bounty :) But if this one goes without anybody winning it (is that even possible?) and if your answer (when it comes) is the best, sure, I will offer the bounty to you :) :)
Comment: Answer is on the way , will post within an hour. It consists of two python scripts. If you know how to deal with the scripts, grab tag_file.py and read_tags.py from https://github.com/SergKolo/nautilus_scripts   Otherwise, feel free to wait for full answer with the installation instructions
Comment: @Serg Maybe it would b better if the tags modify the notes tag in the metadata and you can mod the script to handle that instead. It would need a private directory to write the database to., but at least the metadata is permanent across OSs and you dont have to worry about symlinks.
Comment: @jargonjunkie  I'll look into that, but `gvfs-info` doesn't show any appropriate field to add notes there.
Comment: Linux commands like `mv` and `cp` will not move the tags with the files. The tagging software alone would have to be responsible for moving files. Seems insurmountable. Related question: https://askubuntu.com/questions/774103/selecting-files-from-different-folders/906042#906042
Answer: Contents:

Introduction
Installation
Usage
Source code

1. Introduction
This solution consists of two scripts - one for tagging, one for reading the list of files under specific tag. Both have to live in ~/.local/share/nautilus/scripts and activated via right-click in Nautilus file manager on any file, and navigating to Scripts submenu. The source code for each script is provided here as well as on GitHub
2. Installation
Both scripts have to be saved to ~/.local/share/nautilus/scripts , where ~ is user's home directory, and made executable with chmod +x filename. For easy installation, use the following bash script:
#!/bin/bash

N_SCRIPTS="$HOME/.local/share/nautilus/scripts"
cd /tmp
rm master.zip*
rm -rf nautilus_scripts-master
wget https://github.com/SergKolo/nautilus_scripts/archive/master.zip
unzip master.zip
install nautilus_scripts-master/tag_file.py "$N_SCRIPTS/tag_file.py"
install nautilus_scripts-master/read_tags.py "$N_SCRIPTS/read_tags.py"

3. Usage:
Tagging files:
Select files in Nautilus file manager, right click on them, and navigate to Scripts submenu. Select  tag_file.py. Hit Enter

First time you run this script, there will be no configuration file, so you will see this:

Next time, when you already have some files tagged, you will see a popup that allows you to select a tag and/or add new one ( this way you can record files under multiple tags). Hit OK to add files to this tag. Note:Avoid having "|" symbol in the tag name.

The script records everything in ~/.tagged_files. That file is essentially a json dictionary ( which is not something regular users should care about, but it's convenient for programmers :) ). The format of that file is as so:
{
    "Important Screenshots": [
        "/home/xieerqi/\u56fe\u7247/Screenshot from 2016-10-01 09-15-46.png",
        "/home/xieerqi/\u56fe\u7247/Screenshot from 2016-09-30 18-47-12.png",
        "/home/xieerqi/\u56fe\u7247/Screenshot from 2016-09-30 18-46-46.png",
        "/home/xieerqi/\u56fe\u7247/Screenshot from 2016-09-30 17-35-32.png"
    ],
    "Translation Docs": [
        "/home/xieerqi/Downloads/908173 - \u7ffb\u8bd1.doc",
        "/home/xieerqi/Downloads/911683\u7ffb\u8bd1.docx",
        "/home/xieerqi/Downloads/914549 -\u7ffb\u8bd1.txt"
    ]
}

If you ever want to "untag" some file, just delete an entry from that list. Mind the format and commas.
Searching by tag:
Now that you have a nice ~/.tagged_files database of files, you can either read that file, or use read_tags.py script.
Right click on any file in Nautilus ( really doesn't matter which ).Select read_tags.py. Hit Enter

You will see a popup asking you what tag you want to search:

Select one, click OK. You will see a list dialog showing you want files are there for the tag you selected. You can select any single file and it will open with a default program assigned to that file type.

4. Source code:
tag_file.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Author: Serg Kolo
# Date: Oct 1st, 2016
# Description: tag_file.py, script for
#    recording paths to files under
#    specific , user-defined tag
#    in ~/.tagged_files
# Written for: http://askubuntu.com/q/827701/295286
# Tested on : Ubuntu ( Unity ) 16.04

from __future__ import print_function
import subprocess
import json
import os
import sys

def show_error(string):
    subprocess.call(['zenity','--error',
                     '--title',__file__,
                     '--text',string
    ])
    sys.exit(1)

def run_cmd(cmdlist):
    """ Reusable function for running external commands """
    new_env = dict(os.environ)
    new_env['LC_ALL'] = 'C'
    try:
        stdout = subprocess.check_output(cmdlist, env=new_env)
    except subprocess.CalledProcessError:
        pass
    else:
        if stdout:
            return stdout

def write_to_file(conf_file,tag,path_list):

    # if config file exists , read it
    data = {}
    if os.path.exists(conf_file):
        with open(conf_file) as f:
            data = json.load(f)

    if tag in data:
        for path in path_list:
            if path in data[tag]:
               continue
            data[tag].append(path)
    else:
        data[tag] = path_list

    with open(conf_file,'w') as f:
        json.dump(data,f,indent=4,sort_keys=True)

def get_tags(conf_file):

    if os.path.exists(conf_file):
       with open(conf_file) as f:
            data = json.load(f)
            return '|'.join(data.keys())

def main():

    user_home = os.path.expanduser('~')
    config = '.tagged_files'
    conf_path = os.path.join(user_home,config)
    file_paths = [ os.path.abspath(f) for f in sys.argv[1:] ]
    tags = None

    try:
        tags = get_tags(conf_path)
    except Exception as e:
        show_error(e)

    command = [ 'zenity','--forms','--title',
                'Tag the File'
    ]

    if tags:
       combo = ['--add-combo','Existing Tags',
                '--combo-values',tags
       ]

       command = command + combo

    command = command + ['--add-entry','New Tag']

    result = run_cmd(command)
    if not result: sys.exit(1)
    result = result.decode().strip().split('|')
    for tag in result:
        if tag == '':
           continue
        write_to_file(conf_path,tag,file_paths)

if __name__ == '__main__':
     main()

read_tags.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Author: Serg Kolo
# Date: Oct 1st, 2016
# Description: read_tags.py, script for
#    reading  paths to files under
#    specific , user-defined tag
#    in ~/.tagged_files
# Written for: http://askubuntu.com/q/827701/295286
# Tested on : Ubuntu ( Unity ) 16.04

import subprocess
import json
import sys
import os

def run_cmd(cmdlist):
    """ Reusable function for running external commands """
    new_env = dict(os.environ)
    new_env['LC_ALL'] = 'C'
    try:
        stdout = subprocess.check_output(cmdlist, env=new_env)
    except subprocess.CalledProcessError as e:
        print(str(e))
    else:
        if stdout:
            return stdout

def show_error(string):
    subprocess.call(['zenity','--error',
                     '--title',__file__,
                     '--text',string
    ])
    sys.exit(1)

def read_tags_file(file,tag):

    if os.path.exists(file):
       with open(file) as f:
            data = json.load(f)
            if tag in data.keys():
                return data[tag]
            else:
                show_error('No such tag')
    else:
       show_error('Config file doesnt exist')

def get_tags(conf_file):
    """ read the tags file, return
        a string joined with | for
        further processing """
    if os.path.exists(conf_file):
       with open(conf_file) as f:
            data = json.load(f)
            return '|'.join(data.keys())

def main():

    user_home = os.path.expanduser('~')
    config = '.tagged_files'
    conf_path = os.path.join(user_home,config)

    tags = get_tags(conf_path)
    command = ['zenity','--forms','--add-combo',
               'Which tag ?', '--combo-values',tags
    ]

    tag = run_cmd(command)

    if not tag:
       sys.exit(0)

    tag = tag.decode().strip()
    file_list = read_tags_file(conf_path,tag)
    command = ['zenity', '--list',
               '--text','Select a file to open',
               '--column', 'File paths'
    ]
    selected = run_cmd(command + file_list)
    if selected:
       selected = selected.decode().strip()
       run_cmd(['xdg-open',selected])

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        show_error(str(e))

Comment: this is cool. you always have the most interesting solutions.
Comment: @Serg this is wonderful. Will the tags stick when I move the files? Or when I delete the files, will they still show in the search results?
Comment: @deshmukh No, the tags don't stick if you move the files, and deleted files do show up. I could implement checking for deleted files ( quite easily actually, it's just a few lines ). Essentially you have a database of tags and their files, ans this database has to be maintained
Comment: @Serg we are so near yet so far. Because unless the tags kind of 'stick' to the files (so they remain even after moving the file around), it is as good or as bad as a hierarchical directory structure except that one file can have multiple tags. I am not, even for a moment, belittling your excellent work. I am only saying that it still does not address my (may be, crazy) needs.

Also, as jargonjunkie said in a separate comment, may be tagging the files directly could be the solution (like we tag photographs or bookmarks). But these are words of a novice.
Comment: @deshmukh I agree, tagging files directly would be ideal. I simply haven't found a way to do so , not yet at least. I've tried a few approaches, but they didn't yield any results. I could potentially make a script that periodically checks if all files are in place, but that's the best i can do, qnd it would be highly inefficient if the number of files grows large in the config file. I hope this can be useful to some, but i agree - this isn't exactly a solution you're seeking
Comment: @Serg I thought any 'modern' filesystem would give that option out of the box. If not the filesystem, at least the desktop environment. If not that, at least, the file manager.
Comment: Bug report: https://askubuntu.com/questions/1006646/tagging-files-using-scripts
Answer: I have found a way to do this.
Open a terminal (CTRL+ALT+T) and then run this command:
sudo add-apt-repository ppa:tracker-team/tracker
Enter your password, and when Prompted, press enter, then run
sudo apt-get update
then
sudo apt-get install tracker tracker-gui
Don't worry if it says it's already the latest version.
Now open Nautilus/Files and right click the document you want to add tags to. Select properties, then select the tab that says "Tags". Enter a tag into the text box and press enter or click the Add button to add it. You can also click a tag you have already added and select the Remove button to remove a tag. Please note that tags are case sensitive. The tags you create will be persistent throughout the system, so you can easily put a check next to a tag you already created to mark the file instead of manually typig it again.
After tagging the items wanted, you can now search for them, but not in Files. Go to activities, and search for the app Desktop Search. Launch it, and look at the options at the top. At the top left side of the Window, click the folder icon with the tool tip "Display results by files in a list". Now you have more options. Select the option just to the left of the search box with the tool tip "Find search criteria in file tags only". Now you can search tags!
To use this, enter the tags you want to search, seperated by commas and press enter. For example:
Important, September, Presentation
This will only show files which have all three tags: "Important", "September", and "Presentation".
By double clicking one, it will open the file in the default program, and by right clicking and selecting "Show Parent Directory", it will open it's location in Nautilus.
In Desktop Search, you can also click the second button from the right at the top of the window (usually a star or heart) to edit tags in the app itself!
There you have it! Hope this helps. If you have any more questions, let me know.
Answer: Short answer: This is not possible natively in Ubuntu. You need some extension or a document database, as suggested by the other answers.
Another option I can recommend is to use the app TagSpaces. This app may save tags in the filename, which makes tagging durable and portable. You may edit the filename in Nautilus or within your Cloud-Storage and the tag will appear in TagSpaces and vice versa.
Answer: Apple implements this in its Journaling File System.
For Linux, this is not the case, as of yet.
Of course, there needs to be a DB to keep the associations.
So, 2 recommendations:

If the file is a plain text file, use Evernote instead, or any another note taking app that supports tagging. Evernote is awesome, I've been using it for years. The searches are lightning fast and the tags are so easy to maintain (from the left sidebar).
If you do not want to install some other half-baked app as suggested above (kudos for suggesting it, though), then just put the tags at the top or bottom of the file, on a single line, and comma-separate them. That way, you will be able to search for them in CSV mannner, as long as you remember the sequence, or just by including single tags followed or preceded by a comma, like so: "shoes," ",shirts". I know this second solution is a bit ghetto, but it would be workable on a small scale - limited number of tags applied to a limited number of files :)


Finding the coordinates of a perpendicular bisector

Question: Okay, so in the question, I think I understood part $a$ and $b$ (although I'm not sure) and for part $c$ I'm getting a bit confused.
Question:
The line 1(1) passes through the points $P (−1, 5)$ and $Q(11, 11)$.
(a) Find an equation for $11$ in the form $y = mx + b$ where $m$ and $c$ are constants.
The line L(2) passes through the point $R(9, 0)$ and is perpendicular to $11$ . The lines 1(1) and 1(2) intersect at the point $S$.
(b) Calculate the coordinates of S.
(c) Show that the length of $RS$ is $\sqrt{80}$.
Okay, so for part a I got: $2y=x+5$ part b: the gradient will be $-2$ then $y-0=-2(x-9)$, giving me $y=−2x+18$, giving me the coordinates $(9, 18)$ part c: for this part, would I just get the point $R$ and point $S$ and use the equation of the distance of a line?
I think I know the theory but for some reason I can't get it right. Can you explain please? It would be greatly appreciated. Thanks!
Comment: Perpendicular to 11?
Comment: the 1(1) is a way of typing L1 or L2
Comment: it says 11 instead of your intended 1(1)? I have worked the first three, where are you stuck?
Answer: @Debby
Your part a) is wrong, please check your calculations.
$ y=\frac{x+11}{2} $
for the equation that passes through the points. Can you get m and b?
Use the slope from the last question and get the negative reciprocal of it. The equation that passes through (9,0) and is perpendicular to the first one is:
$ y=-2 x+18$
The point of intersection of those two equations is done by solving them simultaneously you will get (5,8). Please work through that on your own.
For c)
You use the distance formula, you will get:
$ 4 \sqrt{5} = \sqrt{80}$


Background missing in region sections of Firefox OS Building Blocks

Question: i am about to write my personal "Hello World Firefox OS App". To be consistent with the system's style guide, I want to use the Building Blocks provided by Mozilla.
Since I want to have a possibility to set some preferences, I decided to copy the drawer example.
While the example code works fine on buildingfirefoxos.com, my own code is missing some white background with a closed sidebar. I think, I'm struggling to use the Building Blocks properly.
This is my source code:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no" />
        <title>
            some simple app
        </title>
        <link rel="stylesheet" href="./css/util.css" />
        <link href="./style/headers.css" rel="stylesheet" type="text/css">
        <link href="./style_unstable/progress_activity.css" rel="stylesheet" type="text/css">
        <link href="./style_unstable/drawer.css" rel="stylesheet" type="text/css">

                <menu type="toolbar">
                    add
                </menu>

Title (9)

label

label

label

label

Subtitle

label

label

label larger label than the

label

                hide sidebar
                show sidebar

Title

            <progress value="80" max="100"></progress>

Subtitle

                1234

Here you can see, that the main section is overlapping with the sidebar (as expected), but is missing a background or something, that is hiding the sidebar.

Do I have to change some CSS? I would like to use only Building Blocks, since this would help me to reduce time to spend on updates, when the Building Blocks are adapted to new style guides ...
thx in advance : )
Answer: I had this same problem. The solution that worked for me was to make sure that I was including more of the tags that were in the source so that the CSS knows what it needs to act on.

    ...

Make sure that you have the above tags in there and in the right place (don't forget the end tags). You can look at the Building Blocks source to see where these go.


Should a Carousel hide visibly hidden content from screen readers

Question: There's a carousel on the site I am on which does as most accessible carousels, visibly hidden items are also hidden from screen readers (in this case using aria-hidden). This seems to be the normal suggestion for all carousels which strikes me as weird.
First off the elements in the carousel are statically present in the DOM, so it is just a list of elements that could be read sequentially.
Second of all the display of carousel items is done using css transforms, meaning that from a screen readers viewpoint I don't think you end up with anything actually changing position in reading order, so you shouldn't lose the context of where you are - example transform:
transform: translate3d(-200%, 0px, 0px);

Should the Screen reader still be forced to treat this as a carousel, or can it just read it as a list of content in a region?
Answer: No, carousel content shouldn't be hidden for screenreaders.
Carousels are an entirely visual solution to reducing the amount of visual-noise on a page while still being able to access that content. Visual noise is not a problem screen-reader users suffer from.
Provided the content is marked up sufficiently so that the screenreader user can choose to skip the whole section, or jump between items within it easily (for instance if each slide heading is a separate H3 inside the main H2 of the carousel, or if each item is a separate list item) then leave it up to the user how they wish to interact with that element. Don't hide the content from them purely to try to replicate the experience of a sighted user. Because they're two different users who consume the content in very different ways.
Comment: "Because they're two different users who consume the content in very different ways." I tend to disagree. There is a big part of screen reader users who still can see (if impaired), so they use their eyes and the screen reader at the same time.
Answer: ~24% use a screen reader while also looking at the site visually. Hence, consistency between the visual and the read becomes important.
So generally speaking, visually hidden contents should also be hidden from screen readers, which might seem counter-intuitive.
This does not count for text alternatives, of course.


Binding error when using two same User Controls on one parent Window

Question: I have a User Control defined like this:
XAML:
<UserControl>
<Grid x:Name="LayoutRoot">
    <TabControl x:Name="TabControl" ItemsSource="{Binding Products}" >
        <TabControl.ContentTemplate>
            <DataTemplate>
                <Grid>
                    <ListView ItemsSource="{Binding Features}" Name="FeaturesListView">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn x:Name="FeatureHeader" DisplayMemberBinding="{Binding Name}"  />
                                <GridViewColumn x:Name="CounterHeader" DisplayMemberBinding="{Binding Counter}" />
                                <GridViewColumn x:Name="ExpireDateHeader"  DisplayMemberBinding="{Binding ExpireDate}" />
                            </GridView>
                        </ListView.View>
                    </ListView>
                </Grid>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

code behind:
public partial class LicenseInfoControl : UserControl
{
    public LicenseInfoControl(ShowableLicense license)
    {
        InitializeComponent();
        DataContext = license;
    }
}

So, if I use one User Control for one Window:
<Window>
    <Grid>
        <local:LicenseInfoControl x:Name="LicenseInfoControl"/>
    </Grid>
</Window>

it works great. But if I use two of them:
<Window>
    <Grid>
        <local:LicenseInfoControl x:Name="FileLicenseInfoControl"/>
        <local:LicenseInfoControl x:Name="SamLicenseInfoControl"/>
    </Grid>
</Window>

Both ListViews are empty. What am I doing wrong?
Comment: What is the Binding Error you're getting that you mentioned in your question title?
Comment: @Rachel Both of ListViews are empty if I use 2 User Controls. Other bindings works well in both cases.
Comment: What happens if you set the DataContext of each LicenseInfoControl from code-behind?
Comment: I do it this way already (I just do not have enough space in question ;))
            `InitializeComponent();
            FileLicenseInfoControl.Initilize(fileLic);
            SamLicenseInfoControl.Initilize(samLic);`
Answer: Binding worked well. The problem was that if TabControl has one TabItem - it get selected when window loaded and data exposes into it. But if TabControl has two TabItems - no one of the get selected and there's a feeling that binding hasn't worked. But if you select one of Tab Items - data exposes immediately.
So the decision is set SelectedIndexes at a constructor of window with two User controls (LicenseInfoControl in my case):
FileLicenseInfoControl.ProductTabControl.SelectedIndex = 0;
SamLicenseInfoControl.ProductTabControl.SelectedIndex = 0;


What does Maven want?

Question: After I completed the quest for the Thieves' Guild to deal with business at Goldenglow Estate, Brynjolf informed me that Maven Black-Briar wants to speak with me. But when I headed over to her place she had nothing to say to me except her usual stuff about how annoying I am and how important she is. I don't have a quest to talk to her either. What gives? Did she really want to talk to me or is Brynjolf just winding me up?
Comment: Located Mercer, he told me to go away.
Comment: hmm, sounds like a glitch then.  Have you tried talking to Mercer?
Comment: is the quest arrow point to maven?  It may be you have to talk to Brynjolf for some more conversation before Maven speaks to you.
Comment: Brynjolf has nothing more to say to me. He just keeps asking me how it's going. I don't have a quest involving Maven or Brynjolf or the Thieves' Guild.
Comment: I can't find him :/
Comment: Mercer should be in the main cistern area (the area you enter if you take the secret entrance through the graveyard)
Comment: Oh yeah, I've searched around there a million times, but I haven't seen him. Now when I talk to Brynjolf he says he's got important business to do and can't talk. Mavern still won't talk to me. I'm sad :(
Comment: I have the same problem. I thought it might be because I haven't performed any small quests for Delvin and Vex, so I'm trying to do them, but I really don't know. Perhaps it might stem from you have too many ongoing quests? I'm not sure...
Comment: I have this same problem. Did you find out what to do?
Comment: I made a new character and started again. I flagged this bc it's not an answer.
Comment: So if you did happen to break into honningbrew, can you not go any further with the thieves guild quests? Is there a way to skip it and go to the next one or is it just the side jobs from here on...?
Comment: If you are on the PC you can probably use the console to skip forwards
Answer: Seems like it's a bug affecting other players: http://www.ps3trophies.org/forum/elder-scrolls-v-skyrim/134891-thieves-guild-dampened-spirits-quest-bug.html
Anyone know where I can report bugs? I hope a patch fixes thiss
Comment: looks like your best bet, if you don't want to wait for the patch, is to find the quest id via the console and set the stage to something appropriate.
Comment: I'm playing on xbox.
Comment: then I'm afraid you are out of luck, hopefully it'll be in next week's patch
Answer: You can't take this quest if you have previously broken into the Honningbrew Meadery.
Answer: When I spoke to Maven for the next part of the quest chain, I spoke with her on the second floor of the inn.  Try turning on your quest tracking only for that quest (clear the rest) and follow the arrows.
Comment: I don't have a quest, that's the problem.

What does Maven want?


Why is getFilter() for ListView Search Throwing NullPointer?

Question: I am a noob to android development and I am having trouble implementing searchable ListView.  I started by using this android hive tutorial and I made my custom adapter Filterable and overrided the getFilter method as explained by the SO questions here & here.   However, when i run my application as is it crashes due to a null pointer exception. Any help would be greatly appreciated.
Main Activity
public class StoresActivity extends SherlockActivity /*implements OnQueryTextListener*/ {
 ArrayList<HashMap<String, String>> storeList;
 ListView list;
 LazyAdapter adapter;
 EditText inputSearch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stores);

    storeList = new ArrayList<HashMap<String, String>>();
    list=(ListView)findViewById(R.id.list);
    SharedPreferences preferences = getSharedPreferences("Oleref", 2);

    String employee = preferences.getString("employee", null);
    ActionBar bar = getSupportActionBar();
    bar.setDisplayHomeAsUpEnabled(true);
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "http://www.bhfd.com"+ employee});
    try {
        storeList = task.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    adapter=new LazyAdapter(this, storeList);
    list.setAdapter(adapter);
    list.setItemsCanFocus(true);

    //Search Bar for Listview
    inputSearch = (EditText) findViewById(R.id.inputSearch); //<--search bar
    if(adapter!=null){
    }
     inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                StoresActivity.this.adapter.getFilter().filter(cs);  //<--NullPointer here

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });

}

Custom Adapter
public class LazyAdapter extends BaseAdapter implements Filterable {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public String sn;
StoresActivity storesActivity;
HashMap<String, String> stores;
HashMap<String, String> storedata;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return data.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
     View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.store_row, null);

        TextView store = (TextView)vi.findViewById(R.id.storeText); // title
        TextView store_num = (TextView)vi.findViewById(R.id.store_num); // artist name
        TextView street = (TextView)vi.findViewById(R.id.address);
        TextView city = (TextView)vi.findViewById(R.id.city);
        Button newbutton=(Button)vi.findViewById(R.id.newser);
        Button historybutton=(Button)vi.findViewById(R.id.history);
        storedata = new HashMap<String, String>();
        storedata = data.get(position);
        newbutton.setTag(position);
         newbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent chart = new Intent();
                  chart.setClass(v.getContext(), SectionActivity.class);
                 storedata = data.get((Integer)v.getTag());
                  sn = storedata.get("Store_Num");
                  String store = storedata.get("Store");
                  chart.putExtra("sn", sn);
                  chart.putExtra("store", store);
                  chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

                  v.getContext().startActivity(chart);
            }
        });

         historybutton.setTag(position);
         historybutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                     Intent chart = new Intent();
                      chart.setClass(v.getContext(), HistoryList.class);
                     storedata = data.get((Integer)v.getTag());
                      sn = storedata.get("Store_Num");
                      String store = storedata.get("Store");
                      chart.putExtra("sn", sn);
                      chart.putExtra("store", store);
                      chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

                      v.getContext().startActivity(chart);
                }
            });

        // Setting all values in listview
        store.setText(storedata.get("Store"));
        store_num.setText(storedata.get("Store_Num"));
        street.setText(storedata.get("Address"));
        city.setText(storedata.get("City") + " " + storedata.get("State") + " " + storedata.get("Zip"));

        return vi;
}
public boolean onLoadClass(Class arg0) {
    // TODO Auto-generated method stub
    return false;
}

//Added for search BJR 5-16-2013
public android.widget.Filter getFilter() {
    return null;
}

}

LOGCAT
05-16 15:37:04.281: E/AndroidRuntime(26232): FATAL EXCEPTION: main
05-16 15:37:04.281: E/AndroidRuntime(26232): java.lang.NullPointerException
05-16 15:37:04.281: E/AndroidRuntime(26232):    at com.tpssquared.ole.StoresActivity$1.onTextChanged(StoresActivity.java:89)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.widget.TextView.sendOnTextChanged(TextView.java:7875)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.widget.TextView.handleTextChanged(TextView.java:7922)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:8285)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:892)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:266)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:443)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:420)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:29)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:725)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:201)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:154)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:279)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.os.Looper.loop(Looper.java:137)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at android.app.ActivityThread.main(ActivityThread.java:4722)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at java.lang.reflect.Method.invokeNative(Native Method)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at java.lang.reflect.Method.invoke(Method.java:511)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
05-16 15:37:04.281: E/AndroidRuntime(26232):    at dalvik.system.NativeStart.main(Native Method)

Comment: Post the stack trace so we can see what line is crashing.  It would be nice if you could comment it as well.
Comment: just posted my logcat.
Answer: //Added for search BJR 5-16-2013
public android.widget.Filter getFilter() {
    return null;
}

Yet you call getFilter.filter().  I think you forgot to implement something


Is there any penalty for being vote kicked?

Question: I've been playing a lot of Rainbow Six Siege lately, and I was wondering if there is any punishment for being vote kicked too often?
Answer: The only penalty I can think of, your nick will become recognizable and you will be kicked as soon as someone connects the dots. Otherwise, there is no system implemented which would punish you for being kicked often.


Get *all* CSS attributes with jQuery

Question: Here's how you get one css attribute using jQuery:
$('someObject').css('attribute')
How do you get them all?  (without specifying and preferably in the following format so it can be reapplied with jQuery later):
    cssObj = {
        'overflow':'hidden',
        'height':'100%',
        'position':'absolute',
    }

Thanks!!
EDIT
The methods I'm trying to get are declared in a style sheet (they are not inline).  Sorry for not specifying.
Comment: +1 I thought of asking the same question few days ago
Comment: possible duplicate of [Can jQuery get all CSS styles associated with an element?](http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element)
Comment: So what you're saying is, **Gotta Catch 'Em All**?
Answer: See this live example using the jQuery attribute selector
$(document).ready(function() {
    alert($("#stylediv").attr('style'));
});

Comment: @Avinash - So? `.css()` wouldn't pick that up either: http://www.jsfiddle.net/kGkrX/ ---- And this question is trying to get all the CSS properties that would be picked up by `.css()`. --- Getting all the applied styles is a completely different question with a much more difficult answer (Firebug can do it ;) )
Comment: `$('#stylediv').prop('style')` that's all ;)
Comment: Yep, that's why i made the comment below. I thought the OP wanted all the CSS attributes (non-inline) applied to an element, in which case neither of these answers would work. But yes, these answers are the equivalent of .css *.
Comment: @peter `You can get all the css properties declared in an element's style tag` what does it mean ? you mean `style attribute`. BTW, I'm not too specific about declaring css properties only in a style Tag. I mean declaring  other than `inline-style` :)
Comment: @peter I'm just trying to say, we just can't get all css properties [ declared in a style tag ], of an element  using  style attribute
Comment: @Avinash - The example you point out are not in a style tag. You can get all the css properties declared in an element's style tag using these methods. You cannot get all the css styles applied to an element using these methods.
Comment: .css('attribute') grabs the attribute from off of the style sheet even if it's not defined inline.  .attr('style') returns 'undefined' for all definitions in the stylesheet.  I might be confused, but I need to grab what's in my stylesheet.
Comment: @Avinash - Yeah. I do mean the `style` attribute when I say `style tag`... my bad. --- I see what you want, but the OP is not formatted to include that, since it specifically mentions the functionality of `.css()`.
Answer: What about something like this:
jQuery CSS plugin that returns computed style of element to pseudo clone that element?
It is ugly, but it appeared to work for the poster...
This also may be of interest:
https://developer.mozilla.org/en/DOM:window.getComputedStyle
Comment: oh wow that is fugly +1 :)  This is probably the answer unless someone has a way that doesn't iterate through all the attributes (which I doubt, considering the discussion on that SO question).  Thanks for the heads up on getComputedStyle as well!
Answer: Not sure how cross-browser this one is, but it works in Chrome -
https://gist.github.com/carymrobbins/223de0b98504ac9bd654
var getCss = function(el) {
    var style = window.getComputedStyle(el);
    return Object.keys(style).reduce(function(acc, k) {
        var name = style[k],
            value = style.getPropertyValue(name);
        if (value !== null) {
            acc[name] = value;
        }
        return acc;
    }, {});
};

Answer:
window.getComputedStyle(element);

// For example
var element = document.getElementById('header');
window.getComputedStyle(element);

Comment: *NOTE* This will return an object element.
Answer: For a platform (the name is subject to nondisclosure) where the Chrome or Safari DevTools/WebInspector are not available, and  you need to dump the styles to the log.
  dumpCssFromId (id) {
    const el = document.getElementById(id);
    const styles = window.getComputedStyle(el);
    return Object.keys(styles).forEach((index) => {
      const value = styles.getPropertyValue(index);
      if (value !== null  && value.length > 0) {
        console.log(`style dump for ${id} - ${index}: ${value}`);
      }
    }, {});
  }

Get *all* CSS attributes with jQuery


How to connect wiring for ceiling fan?

Question: I'm trying to install a ceiling fan. There used to be one at this location which is now controlled by a wall switch. The ceiling box where the fan goes only has 2 black wires going down to the wall switch. It appears it was a white and black wire but only the black wire was spliced to the switch. How do I hook the fan up ?
Comment: "Spliced out"? What does that mean? The only question here is of polarity. Black to black, white to white.
Comment: I mean that there is only one wire that has a black and a white wire in it , and the black wire has been cut into and white one left together
Answer: Did you already remove the other fan?
If there is another fan already there then just replace it using the same wiring configuration if it worked the way you wanted it to.
The new fan may have a light kit (you didn't mention that) and it sounds like you only have one switch so you will have to decide if you want the wall switch to turn on the fan or the light. The other one you will have to operate with the pull chain.
Happy New Year!
Comment: Or the wall switch can control power to both, with pullchains setting te overall behavior... which is a common way to wire these when putting them in as retrofits, since it keeps the convenience of being able to turn the whoke thing on and off from tne doorway..
Comment: Yes the fan was already removed . An electrician told me that one of the black wires was hot and the other neutral so I'm gonna try hooking up fan both ways black to black and then black to white
Comment: The wires should be black and white but may have discolored with age. The black wire (power wire) should go through the switch. The neutral (normally a white wire) should be connected to another white wire in the box with a wire nut.
Comment: My electrician used 3 conductor wire and replaced the single switch with a double switch so we can work the fan separate from the light when entering the room.

How to connect wiring for ceiling fan?