80 Matching Annotations
  1. Mar 2024
  2. Jan 2024
    1. Instance methods Instances of Models are documents. Documents have many of their own built-in instance methods. We may also define our own custom document instance methods. // define a schema const animalSchema = new Schema({ name: String, type: String }, { // Assign a function to the "methods" object of our animalSchema through schema options. // By following this approach, there is no need to create a separate TS type to define the type of the instance functions. methods: { findSimilarTypes(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); } } }); // Or, assign a function to the "methods" object of our animalSchema animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); }; Now all of our animal instances have a findSimilarTypes method available to them. const Animal = mongoose.model('Animal', animalSchema); const dog = new Animal({ type: 'dog' }); dog.findSimilarTypes((err, dogs) => { console.log(dogs); // woof }); Overwriting a default mongoose document method may lead to unpredictable results. See this for more details. The example above uses the Schema.methods object directly to save an instance method. You can also use the Schema.method() helper as described here. Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.

      Certainly! Let's break down the provided code snippets:

      1. What is it and why is it used?

      In Mongoose, a schema is a blueprint for defining the structure of documents within a collection. When you define a schema, you can also attach methods to it. These methods become instance methods, meaning they are available on the individual documents (instances) created from that schema.

      Instance methods are useful for encapsulating functionality related to a specific document or model instance. They allow you to define custom behavior that can be executed on a specific document. In the given example, the findSimilarTypes method is added to instances of the Animal model, making it easy to find other animals of the same type.

      2. Syntax:

      Using methods object directly in the schema options:

      javascript const animalSchema = new Schema( { name: String, type: String }, { methods: { findSimilarTypes(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); } } } );

      Using methods object directly in the schema:

      javascript animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); };

      Using Schema.method() helper:

      javascript animalSchema.method('findSimilarTypes', function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); });

      3. Explanation in Simple Words with Examples:

      Why it's Used:

      Imagine you have a collection of animals in your database, and you want to find other animals of the same type. Instead of writing the same logic repeatedly, you can define a method that can be called on each animal instance to find similar types. This helps in keeping your code DRY (Don't Repeat Yourself) and makes it easier to maintain.

      Example:

      ```javascript const mongoose = require('mongoose'); const { Schema } = mongoose;

      // Define a schema with a custom instance method const animalSchema = new Schema({ name: String, type: String });

      // Add a custom instance method to find similar types animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); };

      // Create the Animal model using the schema const Animal = mongoose.model('Animal', animalSchema);

      // Create an instance of Animal const dog = new Animal({ type: 'dog', name: 'Buddy' });

      // Use the custom method to find similar types dog.findSimilarTypes((err, similarAnimals) => { console.log(similarAnimals); }); ```

      In this example, findSimilarTypes is a custom instance method added to the Animal schema. When you create an instance of the Animal model (e.g., a dog), you can then call findSimilarTypes on that instance to find other animals with the same type. The method uses the this.type property, which refers to the type of the current animal instance. This allows you to easily reuse the logic for finding similar types across different instances of the Animal model.

      Certainly! Let's go through each part and explain it in simple terms: ### 1. `this` in Mongoose: - **What is `this`?** In JavaScript, `this` refers to the current context or object. In Mongoose, particularly within methods and middleware functions, `this` represents the instance (document) the function is currently operating on. - **Why is it used?** `this` is used to access and modify the properties of the current document. For example, in a Mongoose method, `this` allows you to refer to the fields of the specific document the method is called on. ### 2. Example: Let's use the `userSchema.pre("save", ...)`, which is a Mongoose middleware, as an example: ```javascript userSchema.pre("save", async function (next) { if (!this.isModified("password")) { next(); } else { this.password = await bcrypt.hash(this.password, 10); next(); } }); ``` - **Explanation in Simple Words:** - Imagine you have a system where users can sign up and set their password. - Before saving a new user to the database, you want to ensure that the password is securely encrypted (hashed) using a library like `bcrypt`. - The `userSchema.pre("save", ...)` is a special function that runs automatically before saving a user to the database. - In this function: - `this.isModified("password")`: Checks if the password field of the current user has been changed. - If the password is not modified, it means the user is not updating their password, so it just moves on to the next operation (saving the user). - If the password is modified, it means a new password is set or the existing one is changed. In this case, it uses `bcrypt.hash` to encrypt (hash) the password before saving it to the database. - The use of `this` here is crucial because it allows you to refer to the specific user document that's being saved. It ensures that the correct password is hashed for the current user being processed. In summary, `this` in Mongoose is a way to refer to the current document or instance, and it's commonly used to access and modify the properties of that document, especially in middleware functions like the one demonstrated here for password encryption before saving to the database.

    Tags

    Annotators

    URL

  3. Dec 2023
    1. I disagree. What is expressed is an attempt to solve X by making something that should maybe be agnostic of time asynchronous. The problem is related to design: time taints code. You have a choice: either you make the surface area of async code grow and grow or you treat it as impure code and you lift pure synchronous logic in an async context. Without more information on the surrounding algorithm, we don't know if the design decision to make SymbolTable async was the best decision and we can't propose an alternative. This question was handled superficially and carelessly by the community.

      superficially and carelessly?

  4. Sep 2023
    1. Many mnemonists often recommend that one should understand an idea fully before committing it to memory, usually because it is much easier to memorize if it's fully understood first.

      suggested by: https://hypothes.is/a/Jme3bFmlEe6_VYfaZGQf9Q

    1. "Surrendering" by Ocean Vuong

      1. He moved into United State when he was age of five. He first came to United State when he started kindergarten. Seven of them live in the apartment one bedroom and bathroom to share the whole. He learned ABC song and alphabet. He knows the ABC that he forgot the letter is M comes before N.

      2. He went to the library since he was on the recess. He was in the library hiding from the bully. The bully just came in the library doing the slight frame and soft voice in front of the kid where he sit. He left the library, he walked to the middle of the schoolyard started calling him the pansy and fairy. He knows the American flag that he recognize on the microphone against the backdrop.

  5. Jun 2023
    1. Using Time.now (which returns the wall-clock time) as base-lines has a couple of issues which can result in unexpected behavior. This is caused by the fact that the wallclock time is subject to changes like inserted leap-seconds or time slewing to adjust the local time to a reference time. If there is e.g. a leap second inserted during measurement, it will be off by a second. Similarly, depending on local system conditions, you might have to deal with daylight-saving-times, quicker or slower running clocks, or the clock even jumping back in time, resulting in a negative duration, and many other issues. A solution to this issue is to use a different time of clock: a monotonic clock.
  6. Mar 2023
    1. If the ego is mentally constituted by this dualistic way of thinking, the ego should be able to die without physical death.

      -In Other Words - Die before you die -Paraphrase - If the ego is mentally constituted by this dualistic way of thinking, - the ego should be able to die without physical death. - That is precisely the claim of Buddhism: - the sense of self can disappear, - but there remains something else - that cannot die, - because it was never born. - Anatma is the "middle way" - between - the extremes of eternalism (the self survives death) and - annihilationism (the self is destroyed at death). - Buddhism resolves the problem of life-and-death - by deconstructing it. - The evaporation of it is dualistic way of thinking - reveals what is prior to it, - which has many names, - the most common being "the unborn."

  7. Feb 2023
    1. I find it very tiring haha. As I said in another comment, processing a single chapter can take me a full day or two. However, I keep reminding myself that I would rather spend a day processing a chapter well, and have literature notes to serve me a lifetime (potentially, at least), rather than reading a chapter in two hours and not remember a single thing the next day. When I REALLY need a reminder of this, I just look at my "Backlog" folder which contains old "notes" that are now pretty much useless: I didn't use a reference manager consistently during my first two years of PhD so there are a lot of citations which are unreliable; I didn't really summarise texts, I only read them and highlighted; I didn't use the cloud for a long time, so I lost a lot of notes; and I didn't have Obsidian, so a lot of my notes are just contained within the context of the place I read them, rather than being connected. Seeing three years worth of useless materials, and knowing that I read a couple hundred of articles/chapters but I have nothing to show for it, that makes me more patient when writing my literature notes now. However I also find it very exciting that I can future-proof some of my notes. I feel like I'm working for my future self.

      A partial answer to note taking why.

  8. Dec 2022
    1. Email addresses sometimes get reassigned to a different person. For example, employment changes at a company can cause an address used for an ex-employee to be assigned to a new employee, or a mail service provider (MSP) might expire an account and then let someone else register for the local-part that was previously used. Those who sent mail to the previous owner of an address might not know that it has been reassigned. This can lead to the sending of email to the correct address but the wrong recipient. This situation is of particular concern with transactional mail related to purchases, online accounts, and the like.
  9. Jun 2022
    1. 18. The success of the referendum orga nized by Uber and Lyft to preserve their ex-tremely precarious model in California in 2020 illustrates the limits of an idyllic visionof direct democracy, as well as the need to reconceive a salarial status that makes it pos-sible to reconcile protection and autonomy.
  10. May 2022
    1. "I didn't fully understand it at the time, but throughout my time as a freshman at Boston College I've realized that I have the power to alter myself for the better and broaden my perspective on life. For most of my high school experience, I was holding to antiquated thoughts that had an impact on the majority of my daily interactions. Throughout my life, growing up as a single child has affected the way am in social interactions. This was evident in high school class discussions, as I did not yet have the confidence to be talkative and participate even up until the spring term of my senior year."

  11. Apr 2022
    1. Today, many web developers are even using JavaScript's native module syntax, but combining it with bare import specifiers, thus making their code unable to run on the web without per-application, ahead-of-time modification. We'd like to solve that, and bring these benefits to the web.
    1. Making one Comment query per Post is too expensive; it’s N+1 queries (one to fetch the posts, N to fetch the comments). You could use includes to preload all the comments for all the posts, but that requires hydrating hundreds of thousands of records, even though you only need a few hundred for your front page. What you want is some kind of GROUP BY with a LIMIT on each group — but that doesn’t exist, either in Activerecord nor even in postgres. Postgres has a different solution for this problem: the LATERAL JOIN.
  12. Jan 2022
  13. Dec 2021
    1. Our notion that everyone is equal before the law,for instance, originally traces back to the idea that everyone is equalbefore the king, or emperor: since if one man is invested withabsolute power, then obviously everyone else is equal incomparison.
  14. Aug 2021
  15. May 2021
  16. Apr 2021
    1. At first you feel confused because usual pipe constructions such as: $ echo luser && echo TopSecret | telnet foo.bar.com fail you and the problem which seemed so plain on the face of it grows into “mission impossible”.
  17. Mar 2021
    1. here is my set of best practices.I review libraries before adding them to my project. This involves skimming the code or reading it in its entirety if short, skimming the list of its dependencies, and making some quality judgements on liveliness, reliability, and maintainability in case I need to fix things myself. Note that length isn't a factor on its own, but may figure into some of these other estimates. I have on occasion pasted short modules directly into my code because I didn't think their recursive dependencies were justified.I then pin the library version and all of its dependencies with npm-shrinkwrap.Periodically, or when I need specific changes, I use npm-check to review updates. Here, I actually do look at all the changes since my pinned version, through a combination of change and commit logs. I make the call on whether the fixes and improvements outweigh the risk of updating; usually the changes are trivial and the answer is yes, so I update, shrinkwrap, skim the diff, done.I prefer not to pull in dependencies at deploy time, since I don't need the headache of github or npm being down when I need to deploy, and production machines may not have external internet access, let alone toolchains for compiling binary modules. Npm-pack followed by npm-install of the tarball is your friend here, and gets you pretty close to 100% reproducible deploys and rollbacks.This list intentionally has lots of judgement calls and few absolute rules. I don't follow all of them for all of my projects, but it is what I would consider a reasonable process for things that matter.
  18. Feb 2021
    1. This can be useful in cases like multistep registration. Previously in # rails we used to stick all of the validations in the class and then we're # stuck validating them all everytime
  19. Jan 2021
    1. Personally, I think you are perhaps blowing up a fairly medium-sized (and fixable) bug discovered during routine testing into extreme-case hyperbole. Again, engagement and participation will get the bug fixed faster. The entire point of testing is to discover and fix precisely these kinds of pain points before release.
  20. Dec 2020
    1. This is an opportunity to fix a bug: if you're on a page that redirects to a login page if there's no user object, or otherwise preloads data specific to that user, then logging out won't automatically update the page — you could easily end up with a page like HOME ABOUT LOG IN ----------------------------------------------------------------------------------------- Secret, user-specific data that shouldn't be visible alongside a 'log in' button:
  21. Nov 2020
    1. So, how does an SPA work? JavaScript loads in the browser and loads data from an API. Most of the rendering is done on the client Side. But search engine bots have a hard time indexing the page because it doesn't have much without JS.
    1. This scenario demonstrates one drawback of CSS: With all the style rules that need to be applied to multiple elements on multiple pages, things can get pretty redundant. And redundancy can eat up your time and cause friction whenever you need to change a color, font, or any other style aspect across your site.
    1. In Rust, we use the "No New Rationale" rule, which says that the decision to merge (or not merge) an RFC is based only on rationale that was presented and debated in public. This avoids accidents where the community feels blindsided by a decision.
    2. I'd like to go with an RFC-based governance model (similar to Rust, Ember or Swift) that looks something like this: new features go through a public RFC that describes the motivation for the change, a detailed implementation description, a description on how to document or teach the change (for kpm, that would roughly be focused around how it affected the usual workflows), any drawbacks or alternatives, and any open questions that should be addressed before merging. the change is discussed until all of the relevant arguments have been debated and the arguments are starting to become repetitive (they "reach a steady state") the RFC goes into "final comment period", allowing people who weren't paying close attention to every proposal to have a chance to weigh in with new arguments. assuming no new arguments are presented, the RFC is merged by consensus of the core team and the feature is implemented. All changes, regardless of their source, go through this process, giving active community members who aren't on the core team an opportunity to participate directly in the future direction of the project. (both because of proposals they submit and ones from the core team that they contribute to)
  22. Oct 2020
    1. You can see that behaviour in this example. Select a range of text and hit the tab key. Because the <textarea> value changes, the current selection is cleared and the cursor jumps, annoyingly, to the end.
    1. Just like elements can have children... <div> <p>I'm a child of the div</p> </div>...so can components. Before a component can accept children, though, it needs to know where to put them. We do this with the <slot> element.
    1. The primary motivation behind virtual-dom is to allow us to write code independent of previous state. So when our application state changes we will generate a new VTree. The diff function creates a set of DOM patches that, based on the difference between the previous VTree and the current VTree, will update the previous DOM tree to match the new VTree.

      annotation meta: may need new tag: for: "code independent of previous state."

      annotation meta: may need new tag: for: diffs other than source/text code diffs (in this case diffs between virtual DOM trees)

    2. Manual DOM manipulation is messy and keeping track of the previous DOM state is hard. A solution to this problem is to write your code as if you were recreating the entire DOM whenever state changes. Of course, if you actually recreated the entire DOM every time your application state changed, your app would be very slow and your input fields would lose focus.
  23. mdxjs.com mdxjs.com
    1. Before MDX, some of the benefits of writing Markdown were lost when integrating with JSX. Implementations were often template string-based which required lots of escaping and cumbersome syntax.
  24. Sep 2020
    1. It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  25. Aug 2020
    1. We've stated what's required multiple times now: #14540 (comment) #14540 (comment), and the follow up arguments weren't convincing. Follow Rafael's advice in new smaller PRs to advance this or it'll simply stay closed
    1. Altig, D., Baker, S. R., Barrero, J. M., Bloom, N., Bunn, P., Chen, S., Davis, S. J., Leather, J., Meyer, B. H., Mihaylov, E., Mizen, P., Parker, N. B., Renault, T., Smietanka, P., & Thwaites, G. (2020). Economic Uncertainty Before and During the COVID-19 Pandemic (Working Paper No. 27418; Working Paper Series). National Bureau of Economic Research. https://doi.org/10.3386/w27418

  26. Jul 2020
  27. Jun 2020
  28. May 2020
  29. Apr 2020
  30. Mar 2020
    1. However imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as: <?php$format = 'The %s contains %d monkeys';echo sprintf($format, $num, $location);?> We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead: <?php$format = 'The %2$s contains %1$d monkeys';echo sprintf($format, $num, $location);?> An added benefit is that placeholders can be repeated without adding more arguments in the code.
    2. $format = 'There are %d monkeys in the %s';

      Compared to below:

      $format = 'The %s contains %d monkeys'
      
    1. Poedit and other tools can scan your .php files for references of __(), _e(), _n() and so on, and grab those strings for translation, which is awesome, because otherwise you’d have to manually add every single string. Now, when these tools come across _n() in our sources, they know it’s a plural thing, because of a special keyword setting which looks something like _n:1,2, meaning _n() takes at least two arguments, where the first argument is the singular, and the second argument is a the plural, so it grabs both strings. Let’s take a look at how Poedit and other tools will parse our function above: Hello there _n() on line 3! I’m supposed to grab two of your arguments because I have this smart keyword setting, but none of these arguments are strings, so I’ll just skip to the next match
  31. Feb 2020
    1. Collaboration is not consensus When collaborating it is always important to stay above radar and work transparently, but collaboration is not consensus. You don't need to ask people for their input, and they shouldn't ask you "Why didn't you ask me?" You don't have to wait for people to provide input, if you did ask them. We believe in permissionless innovation- you don't need to involve people but everyone can contribute. This is core to how we iterate, since we want smaller teams moving quickly rather than large teams achieving consensus slowly.
    1. Nix helps you make sure that package dependency specifications are complete. In general, when you’re making a package for a package management system like RPM, you have to specify for each package what its dependencies are, but there are no guarantees that this specification is complete. If you forget a dependency, then the component will build and work correctly on your machine if you have the dependency installed, but not on the end user's machine if it's not there.
  32. Jan 2020
    1. You might be thinking––"a tool that allows me to write semantic and reusable queries? Sounds like Active Record". It's absolutley true that Active Record already provides a powerful query tool kit. But what happens when even simple queries stretch the bounds of Active Record's capabilities?
    1. Such verbose. Much code. Very bloat. Wow. We've lost all the awesome association introspection that ActiveRecord would otherwise have given us.
  33. Dec 2019
    1. But it's not easy to open todo.txt, make a change, and save it—especially on your touchscreen device and at the command line. Todo.txt apps solve that problem.
    1. Sometimes cronjobs fail to run successfully because a required server (like a database or ftp server) is temporarily unavailable due to power failures, hardware failures, software failures, network outages, choice of operating system, pilot error, and the like. Typically, this results in someone being forced to examine crontabs and error reports, determine which cronjobs really need to be run, and then run them manually. This happened to me twice in one week. I don't want it to happen again. Cronjobs are meant to be automated and I want them to stay that way. This is the rationale for noexcuses.
    1. An ssh public key in a ~/.ssh/authorized_keys file can have a command="" option which forces a particular command to be executed when the key is used to authenticate an ssh connection. This is a security control that mitigates against private key compromise. This is great when you only need to execute a single command. But if you need to perform multiple tasks, you would normally need to create and install a separate key pair for each command, or just not bother making use of forced commands and allow the key to be used to execute any command.
    1. However, these benefits only accrue to outbound connections made from the local system to ssh servers elsewhere: once logged into a remote server, connecting from there to yet a third server requires either password access, or setting up the user's private key on the intermediate system to pass to the third. Having agent support on the local system is certainly an improvement, but many of us working remotely often must copy files from one remote system to another. Without installing and initializing an agent on the first remote system, the scp operation will require a password or passphrase every time. In a sense, this just pushes the tedium back one link down the ssh chain.
  34. Nov 2019
    1. You might want developers building projects with this CMS to be able to change the behaviour of some UIs, or to be able to provide new components that can be consumed by the CMS. Those components can't easily be included in the JS bundle for the CMS, as it would require recompiling the shipped code with outside references.
    1. However, again you would have to lift state up to the App component in order to pass the amount to the currency components. As you can see, the component composition on its own doesn't help us to solve the problem. That's the point where React's render props pattern comes into play which enhances React's component composition with an important ingredient: a render function.
  35. Oct 2019
  36. Nov 2016
    1. the forsythia bush

      Another thing in a certain place in the neighborhood where she lived. Now I think the poem's first 2 1/2 lines were purposely provocative. They keep you guessing, and make you keep reading.

    2. under the back porch

      Oh. I guess she's listing things and places in her life.

    3. I am from clothespins, from Clorox and carbon-tetrachloride.

      What? How can you be from clothespins?

    1. deeply symbolic choice, since salt was used by nearly everyone in India, to replace the salt lost by sweating in India's tropical climate. An item of daily use could resonate more with all classes of citizens than an abstract demand for greater political rights.[19] The salt tax represented 8.2% of the British Raj tax revenue, and hurt the poorest Indians the most significantly.

      Gandhi's reasons

    2. The Viceroy himself, Lord Irwin, did not take the threat of a salt protest seriously, writing to London, "At present the prospect of a salt campaign does not keep me awake at night."[18]

      The British was not disturbed at first

    3. Gandhi's choice of the salt tax was met with incredulity by the Working Committee of the Congress,[15] Jawaharlal Nehru and Dibyalochan Sahoo were ambivalent; Sardar Patel suggested a land revenue boycott instead.

      Gandhi pushed the salt march... But they first declined it

    4. At midnight on 31 December 1929, the Indian National Congress raised the tricolour flag of India on the banks of the Ravi at Lahore.

      Declaration of Sovereignty and self rule

  37. Nov 2015
    1. Does the Espionage Act violate the First Amendment guarantee of free speech?

      I think that this is not the legal issue that is targeted in the book on this case? I concluded that it is more about whether this pamphlet and political expression is protected under the First Amendments rights of the Constitution for the defendant. Or whether obstruction of war time ideals and peace is a crime in a state of unrest?