Encrypts using AES GCM for data with limited visibility and long rest

This is the third iteration of my venture on creating an encryption/decryption solution. I asked a question here, which led to this question here, which led to this answer here, which led me to introducing Bouncy Castle into my solution to gain better security under the circumstances and application requirements.

Requirements: To encrypt and decrypt a string using AES 256 with a password/key (stored in web.config) in an ASP.net application.

History: If you follow the above links you’ll find that I originally tried to stick with the core .net provided solutions without the inclusion of any additional libraries. This requirement has changed and I’ve added Bouncy Castle to my solution.

Thanks to @SEJPM regularly pointing me in the right direction I decided to implement AES GCM and ditch my previous attempts.

I found this example here from @jbtule who seems to have a pretty good handle on things, and honestly I didn’t change a thing other than convert it to VB. However, based on previous suggestions given to me to use Argon2, I read that Bouncy Castle supports this now but I’m currently uncertain as how to properly implement it.

Although my code is essentially a copy @jbtule’s original post on CodeReview, that was 6 years ago.

So based on the fact that I pull the encryption key/pass from web.config and I need simple encrypt/decrypt, how does this solution stack up?

Usage:

Dim password = RetrieveFromWebConfig() Dim plainText = "Hello World" Dim encrypted = SimpleEncryptWithPassword(plainText, password) Dim decrypted = SimpleDecryptWithPassword(encrypted, password) 

Code:

Imports System Imports System.IO Imports System.Text Imports Org.BouncyCastle.Crypto Imports Org.BouncyCastle.Crypto.Engines Imports Org.BouncyCastle.Crypto.Generators Imports Org.BouncyCastle.Crypto.Modes Imports Org.BouncyCastle.Crypto.Parameters Imports Org.BouncyCastle.Security  Namespace Utilities.Encryption     Public Class Aesgcm         Public Shared ReadOnly Random As SecureRandom = New SecureRandom()         Public Shared ReadOnly NonceBitSize As Integer = 128         Public Shared ReadOnly MacBitSize As Integer = 128         Public Shared ReadOnly KeyBitSize As Integer = 256         Public Shared ReadOnly SaltBitSize As Integer = 128         Public Shared ReadOnly Iterations As Integer = 10000         Public Shared ReadOnly MinPasswordLength As Integer = 12           Shared Function SimpleEncryptWithPassword(secretMessage As String, password As String, ByVal Optional nonSecretPayload As Byte() = Nothing) As String             If String.IsNullOrEmpty(secretMessage) Then Throw New ArgumentException("Secret Message Required!", "secretMessage")             Dim plainText = Encoding.UTF8.GetBytes(secretMessage)             Dim cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload)             Return Convert.ToBase64String(cipherText)         End Function          Shared Function SimpleDecryptWithPassword(encryptedMessage As String, password As String, ByVal Optional nonSecretPayloadLength As Integer = 0) As String             If String.IsNullOrWhiteSpace(encryptedMessage) Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage")             Dim cipherText = Convert.FromBase64String(encryptedMessage)             Dim plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength)             Return If(plainText Is Nothing, Nothing, Encoding.UTF8.GetString(plainText))         End Function          Shared Function SimpleEncrypt(secretMessage As Byte(), key As Byte(), ByVal Optional nonSecretPayload As Byte() = Nothing) As Byte()             If key Is Nothing OrElse key.Length <> KeyBitSize / 8 Then Throw New ArgumentException($  "Key needs to be {KeyBitSize} bit!", "key")             If secretMessage Is Nothing OrElse secretMessage.Length = 0 Then Throw New ArgumentException("Secret Message Required!", "secretMessage")             nonSecretPayload = If(nonSecretPayload, New Byte() {})             Dim nonce = New Byte(CInt(NonceBitSize / 8 - 1)) {}             Random.NextBytes(nonce, 0, nonce.Length)             Dim cipher = New GcmBlockCipher(New AesEngine())             Dim parameters = New AeadParameters(New KeyParameter(key), MacBitSize, nonce, nonSecretPayload)             cipher.Init(True, parameters)             Dim cipherText = New Byte(cipher.GetOutputSize(secretMessage.Length) - 1) {}             Dim len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0)             cipher.DoFinal(cipherText, len)              Using combinedStream = New MemoryStream()                  Using binaryWriter = New BinaryWriter(combinedStream)                     binaryWriter.Write(nonSecretPayload)                     binaryWriter.Write(nonce)                     binaryWriter.Write(cipherText)                 End Using                  Return combinedStream.ToArray()             End Using         End Function          Shared Function SimpleDecrypt(encryptedMessage As Byte(), key As Byte(), ByVal Optional nonSecretPayloadLength As Integer = 0) As Byte()             If key Is Nothing OrElse key.Length <> KeyBitSize / 8 Then Throw New ArgumentException($  "Key needs to be {KeyBitSize} bit!", "key")             If encryptedMessage Is Nothing OrElse encryptedMessage.Length = 0 Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage")              Using cipherStream = New MemoryStream(encryptedMessage)                  Using cipherReader = New BinaryReader(cipherStream)                     Dim nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength)                     Dim nonce = cipherReader.ReadBytes(CInt(NonceBitSize / 8))                     Dim cipher = New GcmBlockCipher(New AesEngine())                     Dim parameters = New AeadParameters(New KeyParameter(key), MacBitSize, nonce, nonSecretPayload)                     cipher.Init(False, parameters)                     Dim cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length)                     Dim plainText = New Byte(cipher.GetOutputSize(cipherText.Length) - 1) {}                      Try                         Dim len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0)                         cipher.DoFinal(plainText, len)                     Catch unusedInvalidCipherTextException1 As InvalidCipherTextException                         Return Nothing                     End Try                      Return plainText                 End Using             End Using         End Function          Shared Function SimpleEncryptWithPassword(secretMessage As Byte(), password As String, ByVal Optional nonSecretPayload As Byte() = Nothing) As Byte()             nonSecretPayload = If(nonSecretPayload, New Byte() {})             If String.IsNullOrWhiteSpace(password) OrElse password.Length < MinPasswordLength Then Throw New ArgumentException($  "Must have a password of at least {MinPasswordLength} characters!", "password")             If secretMessage Is Nothing OrElse secretMessage.Length = 0 Then Throw New ArgumentException("Secret Message Required!", "secretMessage")             Dim generator = New Pkcs5S2ParametersGenerator()             Dim salt = New Byte(CInt(SaltBitSize / 8 - 1)) {}             Random.NextBytes(salt)             generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations)             Dim key = CType(generator.GenerateDerivedMacParameters(KeyBitSize), KeyParameter)             Dim payload = New Byte(salt.Length + nonSecretPayload.Length - 1) {}             Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length)             Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length)             Return SimpleEncrypt(secretMessage, key.GetKey(), payload)         End Function          Shared Function SimpleDecryptWithPassword(encryptedMessage As Byte(), password As String, ByVal Optional nonSecretPayloadLength As Integer = 0) As Byte()             If String.IsNullOrWhiteSpace(password) OrElse password.Length < MinPasswordLength Then Throw New ArgumentException($  "Must have a password of at least {MinPasswordLength} characters!", "password")             If encryptedMessage Is Nothing OrElse encryptedMessage.Length = 0 Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage")             Dim generator = New Pkcs5S2ParametersGenerator()             Dim salt = New Byte(CInt(SaltBitSize / 8 - 1)) {}             Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length)             generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations)              Dim key = CType(generator.GenerateDerivedMacParameters(KeyBitSize), KeyParameter)             Return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength)         End Function     End Class End Namespace 

Scaling a shopping website with limited stock and high traffic

I’m trying to decide on an architecture to scale a scenario where millions of customers might purchase a sale product at the same time (e.g. at the time when the sale opens) and that product has a limited amount in stock.

I need to make sure that I don’t charge users when the product is already out of stock, that I won’t miss purchases and that the clients would receive a feedback quickly whether the purchases succeeded or not.

I wasn’t sure whether to include a queue in that architecture or not, so far I thought about scaling out many WebJobs (lets say the service hosted on Azure for example) which the main host will send the payment request to via some load balancing mechanism. I still need to sync all those WebJobs to determine when all products in stock are sold and each architecture I try to think of (DB, keeping the stock amount on a cache) becomes a bottleneck.

I’m also not sure how to create an architecture that from one hand scales out as necessary so users will have a quick response but from other hand if and when the traffic becomes low I won’t pay for servers that are doing nothing.

I was also trying to search for literature on scaling web apps with high traffic but could only find old books (10 years old) which only offer some best practices and not a full architecture examples to such problems.

Please advice me on a possible architecture to handle high scales on the web, and if possible also offer some books I can read to gain more practical background on scaling.

Getting limited user input: strings and numbers

I posted part of this module earlier (here). I implemented that feedback and now am looking for another round of gut checking. Questions/Concerns I have:

  • Does the way I’ve structured my functions make sense? Can they be broken down more/differently?
  • Is there a better way of doing the error handling? I feel like I’m repeating a lot of code, especially in GetNumber, GetNumberInRange, and _AcceptAndValidateNumber
  • Anything else that will help me improve my coding skills

Also, I’m not sure if I qualify as a beginner anymore, but I tagged it as such because I feel I still am.

Thanks in advance!

""" This module contains tools for getting input from a user. At any point while getting input, the user may enter "quit", "exit", or   "leave" to raise a SystemExit exception and quit. """  import textwrap as tw from enum import Enum, auto  _EXIT_WORDS = {"quit", "exit", "leave"}   class OutputMode(Enum):     """     Used to determine the output of the GetNumber function     """     INT = auto()     FLOAT = auto()     NUM = auto()   def GetStringChoice(prompt, **kwoptions):     """     Print out the prompt and then return the input as long as it matches one     of the options (given as key/value pairs)      Example call:         >>> prompt = "Who is the strongest Avenger?"         >>> input_options = {                 "t":"Thor",                 "i":"Iron Man",                 "c":"Captain America",                 "h":"The Hulk"}         >>> response = GetStringChoice(prompt, **input_options)         Who is the strongest Avenger?          - 't' for 'Thor'          - 'i' for 'Iron Man'          - 'c' for 'Captain America'          - 'h' for 'The Hulk'         h         >>> response         'h'     Invalid results are rejected:         >>> response = GetStringChoice(prompt, **input_options)         Who is the strongest Avenger?         - 't' for 'Thor'         - 'i' for 'Iron Man'         - 'c' for 'Captain America'         - 'h' for 'The Hulk'         Ant-Man         That wasn't one of the options.         Who is the strongest Avenger?         ...     """     formatted_options = _get_formatted_options(**kwoptions)      print(tw.fill(prompt))     while True:         try:             print(formatted_options)              user_choice = input()             if user_choice in kwoptions:                 return user_choice             elif user_choice in _EXIT_WORDS:                 _SysExitMsg()              print("That wasn't one of the options.",)         except TypeError as t:             raise t         except SystemExit as s:             raise s         except Exception as e:             raise e   def _get_formatted_options(**kwoptions):     """Formats a dictionary of options and returns them as a string"""      OPTION_TEMPLATE = " - '{0:{1}}' for '{2}'"     # The 1 as the second arg below is filler because format won't allow 0     # -2 ensures that the subsequent indent lines up with the first char     STR_PADDING = len(OPTION_TEMPLATE.format("", 1, "")) - 2      # This is used to adjust the section before the "-" to be as wide as the     # longest key     space = max(map(len, kwoptions))     pad_length = space + STR_PADDING      prompt_lines = []      for key in kwoptions:         # This wraps the text at the max line length and pads the new         # lines so it looks nice.         full_option = tw.fill(             kwoptions[key],             subsequent_indent=" " * pad_length)          prompt_lines.append(OPTION_TEMPLATE.format(key, space, full_option))      return "\n".join(prompt_lines)   def GetYesNo(prompt):     """     Calls GetStringChoice and only allows yes or no as response. Return y/n.      Example:         >>> response = GetYesNo("Is Footloose still the greatest movie ever?")         Is Footloose still the greatest movie ever?         - 'y' for 'yes'         - 'n' for 'no'         It never was!         That wasn't one of the options.         Is Footloose still the greatest movie ever?         - 'y' for 'yes'         - 'n' for 'no'         n         >>> response         'n'      """     return GetStringChoice(prompt, y="yes", n="no")   def GetTrueFalse(prompt):     """     Calls GetStringChoice and only allows boolean response.     Return boolean True or False.      Example:         >>> GetTrueFalse("True or False: Star-Lord was responsible for"                          "the team losing on Titan:")         True or False: Star-Lord was responsible for the team losing on Titan:         - 't' for 'True'         - 'f' for 'False'         f         False         >>>     """     if GetStringChoice(prompt, t="True", f="False") == "t":         return True     return False   def GetNumber(prompt, min_opt=1, max_opt=10, data_type=OutputMode.NUM,               restrict_range=False):     """     Return the user's choice of number.      If restrict_range=False, don't restrict the range (deafult).     Otherwise, restrict answer to between min/max_opt.      Use data_type to determine what type of number to return, passing in an       OutputMode enum. Examples:     - ui.OutputMode.NUM: whatever type the user entered (this is the default)         >>> my_num = GetNumber("Pick a number:")         Pick a number:         5.0         >>> my_num         5.0         >>> my_num = GetNumber("Pick a number:")         Pick a number:         5         >>> my_num         5     - ui.OutputMode.INT: integers         >>> my_num = GetNumber("Pick an integer:", 1, 10, ui.OutputMode.INT,                                restrict_range=False)         Pick an integer:         (min = 1, max = 10)         5.0         >>> my_num         5     - ui.OutputMode.FLOAT: floats         >>> my_num = GetNumber("Pick an integer:", 1, 10, ui.OutputMode.FLOAT                                restrict_range=False)         Pick an integer:         (min = 1, max = 10)         5         >>> my_num         5.0     """     print(tw.fill(prompt))      if not restrict_range:         # User is not restricted to the min/max range         num_choice = _AcceptAndValidateNumber()     else:         num_choice = GetNumberInRange(min_opt, max_opt)      if data_type == OutputMode.NUM:         return num_choice     elif data_type == OutputMode.FLOAT:         return float(num_choice)     elif data_type == OutputMode.INT:         return int(num_choice)   def GetNumberInRange(min_opt, max_opt):     """     Let the user pick a number     Return it as whatever data type the user used     """      # This could live in a separate func but then it'd have to assign     # min/max_opt even when nothing changes     if max_opt < min_opt:         # Switch the order if the maximum is less than the minimum.         # This is done for aesthetics         min_opt, max_opt = max_opt, min_opt      if max_opt == min_opt:         # It makes no sense for these to be equal, so raise an error         raise ValueError("The min and max numbers should not be the same.\n")      print("(min = {0:,}, max = {1:,})".format(min_opt, max_opt))      while True:         try:             num_choice = _AcceptAndValidateNumber()              # Check to see if the num_choice is valid in our range             if eval("{0}<={1}<={2}".format(min_opt, num_choice, max_opt)):                 return num_choice             print("Please pick a number between {0} and {1}.".format(                 min_opt,                 max_opt))                 # The comma here places the user's response on the same line         except SystemExit as s:             raise s         except Exception as e:             raise e   def _AcceptAndValidateNumber():     """     Accept a user's choice of number, and then return it as a float or int.      Type is determined by whether the user includes a decimal point.     """     while True:         try:             num_choice = input()             if num_choice in _EXIT_WORDS:                 _SysExitMsg()              # Return the corresponding number type             if num_choice.find(".") == -1:                 return int(float(num_choice))             return float(num_choice)         except ValueError:             # Don't raise; just force the user back into the loop             print("Please pick a number.")         except SystemExit as s:             raise s         except Exception as e:             raise e   def _SysExitMsg(msg="Thanks!"):     """     A consistent process for SystemExit when a user enters one of the     _EXIT_WORDS     """     print(msg)     raise SystemExit  # Raise the SystemExit exception again to exit 

I don’t currently have unit tests for this module (I’m struggling with testing incorrect answers), so I use these functions as a way of running through the different variations of input this module can receive:

def main():     """     A demonstration function.     """     _demonstrateGetNumber()     _demonstrateGetStringChoice()   def _demonstrateGetNumber():     print("""     Demonstration of GetNumber()     """)      print("Returns {0}\n".format(GetNumber(         "Step right up and pick a number, any number!")))      print("Returns {0}\n".format(GetNumber(         "Only integers this time (decimals will be rounded). "         "Pick any integer!",         data_type=OutputMode.INT)))     print("Returns {0}\n".format(GetNumber(         prompt="Now only an integer in the range below!",         data_type=OutputMode.INT,         restrict_range=True)))     print("Returns {0}\n".format(GetNumber(         "Now pick a float! (root beer not allowed)",         data_type=OutputMode.FLOAT)))     print("Returns {0}\n".format(GetNumber(         prompt="And finally, a float in the given range:",         min_opt=1,         max_opt=50,         data_type=OutputMode.FLOAT,         restrict_range=True)))     return None   def _demonstrateGetStringChoice():     print("""     Demonstration of GetStringChoice()     """)      print("Returns {0}\n".format(GetStringChoice(         "What does your mother smell of?", e="elderberries", h="hamster")))      print("Returns {0}\n".format(GetYesNo(         "That was just a little Python humor. Did you enjoy it?")))      print("Returns {0}\n".format(GetTrueFalse(         "Is it true that an African swallow could carry a coconut?")))      return None 

[get] Acupressure For Best Love Life: Better Sex, Potency & More! – $79 -free limited time

Acupressure For Best Love Life: Better Sex, Potency & More!
Learn to enjoy sex to the full, have strong potency and relax on your own with the best professional acupressure videos.

Code:
https://www.udemy.com/acupressure-for-best-love-life-better-sex-potency-health-acupuncture/?couponCode=24_HOUR_FREE

Welcome to The Acupressure For Better Love Life – The Place on Udemy to Learn Sex-Related Acupressure Points!

√ Enjoy The Best Sex using Traditional Chinese Massage Points

√…

[get] Acupressure For Best Love Life: Better Sex, Potency & More! – $ 79 -free limited time

Encrypts using AES with random initialization vector meant for data with limited visibility and then long rest

I’ve done some research, reviewed countless SO questions that appeared similar, leading me to endless rabbit holes.

My solution is working, but I don’t like it. I want to create a random IV for AES and store it with my cipher. You’ll see various approaches based on the comments in my code. This final version is mostly from another source I found with some changes. What I was hoping to do is instead of generating two separate strings and concatenating them together, I could write into the same byte array and break it apart later. Goal is AES256 with random IV.

This led to errors like:

  • Invalid characters in base64 string
  • length of data to encrypt is invalid
  • padding is invalid and cannot be removed

So here’s my code. And of course, if there’s a hole or ten, advice welcome. Feel free to share examples in c#. This project just happens to be in VB.net

Public Function EncryptText(input As String) As String          Dim password As String = "THISISONLYTEMPORARY"          Dim bytesToBeEncrypted As Byte() = Encoding.UTF8.GetBytes(input)         Dim passwordBytes As Byte() = Encoding.UTF8.GetBytes(password)         passwordBytes = SHA256.Create().ComputeHash(passwordBytes)         Dim result As String = AES_Encrypt(bytesToBeEncrypted, passwordBytes)          Return result     End Function      Public Function DecryptText(ByVal input As String) As String          Dim password As String = "THISISONLYTEMPORARY"         'Dim savedSalt As Byte() = Convert.FromBase64String(input.Split("%"c)(0))         'Dim savedValue As String = input.Split("%"c)(1)         Dim savedSalt As Byte() = Convert.FromBase64String(input.Substring(0, 44))         Dim savedValue As String = input.Substring(44, input.Length - 44)          Dim bytesToBeDecrypted As Byte() = Convert.FromBase64String(savedValue)         Dim passwordBytes As Byte() = Encoding.UTF8.GetBytes(password)         passwordBytes = SHA256.Create().ComputeHash(passwordBytes)         Dim result As String = AES_Decrypt(bytesToBeDecrypted, passwordBytes, savedSalt)         Return result     End Function       Public Function AES_Encrypt(ByVal bytesToBeEncrypted As Byte(), ByVal passwordBytes As Byte()) As String         Dim encryptedBytes As Byte() = Nothing          'Dim saltBytes As Byte() = New Byte() {1, 2, 3, 4, 5, 6, 7, 8}          Dim saltBytes = New Byte(31) {}         Using rng As RandomNumberGenerator = New RNGCryptoServiceProvider()             rng.GetBytes(saltBytes)         End Using          Dim saltToSave As String = Convert.ToBase64String(saltBytes)          Using ms As MemoryStream = New MemoryStream()              Using AES = New AesManaged()                 AES.KeySize = 256                 AES.BlockSize = 128                 Dim key = New Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000)                 AES.Key = key.GetBytes(CInt(AES.KeySize / 8))                 AES.IV = key.GetBytes(CInt(AES.BlockSize / 8))                 AES.Mode = CipherMode.CBC                 AES.Padding = PaddingMode.PKCS7                  Using cs = New CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)                     'cs.Write(saltBytes, 0, saltBytes.Length) ' new                     cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length)                     cs.Close()                 End Using                  encryptedBytes = ms.ToArray()             End Using         End Using          Return saltToSave & Convert.ToBase64String(encryptedBytes)     End Function      Public Function AES_Decrypt(ByVal bytesToBeDecrypted As Byte(), ByVal passwordBytes As Byte(), savedSalt As Byte()) As String         Dim decryptedBytes As Byte() = Nothing         'Dim saltBytes As Byte() = New Byte() {1, 2, 3, 4, 5, 6, 7, 8}           Using ms As MemoryStream = New MemoryStream()              Using AES = New AesManaged()                 AES.KeySize = 256                 AES.BlockSize = 128                 Dim key = New Rfc2898DeriveBytes(passwordBytes, savedSalt, 1000)                 AES.Key = key.GetBytes(CInt(AES.KeySize / 8))                 AES.IV = key.GetBytes(CInt(AES.BlockSize / 8))                 AES.Mode = CipherMode.CBC                 AES.Padding = PaddingMode.PKCS7                  Using cs = New CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write)                     cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length)                     cs.Close()                 End Using                  decryptedBytes = ms.ToArray()             End Using         End Using          'Return Encoding.UTF8.GetString(decryptedBytes.Skip(savedSalt.Length).ToArray())         Return Encoding.UTF8.GetString(decryptedBytes.ToArray())     End Function 

I was at one point joining my IV and cipher text with a % character and splitting those, but didn’t like the visible clear separation which made the IV obvious.

Again this is working. My question is more about hardening it within the constraints that you see (A single private password and random IV) and ditching this string concatenation.

I posted this on stackoverflow but it was suggested to move to here because my solution is working. It was also suggested to not be concerned about splitting my encrypted string with “%” as you see commented out in my code and was pointed to this link: https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle

Need to set up a phone with limited permissions to help with a learning disorder

I need to set up a phone that will allow the user access to installed apps but will not allow them to install new apps. In addition I need to allow access to only a whitelist of websites. These constraints need to be unbreakable short of a factory wipe. My thought regarding privacy was to have a superuser account that the user and administrator each have half of the password, so the administrator can’t get on the phone without the permission of the user.

I’m kind of desperate here. I asked this question twice on r/androidroot and both times people told me to just install apps that “reward good behavior” etc. We’re way past that point. The user really needs email, text, maps, and a few work related apps (plus definitely some apps like Habitica to reward good habits!).

I haven’t rooted a phone before but am fairly technically proficient. If Tasker is any part of the solution I’m pretty handy with that, otherwise I will do or learn anything necessary to make this happen. I have a google pixel to work with but if absolutely necessary will get a different phone.

Thank you very much for any help you’re able to provide! p.s. the disorder is a pretty strong Executive Function disorder – despite 18 years of therapy with 6 different people the user is basically unable to build good habits or demonstrate much willpower. It’s been pretty devastating for them.

Cache with limited size; If full remove the oldest

Here is a class that stores a single value into the limited cache. If cache is full, it will remove the oldest element to make a space for a new value. I’m using 2 structures to accomplish this because I need a fast lookup. I’m not very confident this is the best approach. Cache will contain a small amount of data (lets say 1000 elements).

#include <unordered_set> #include <queue>  template <class T> class Cache{  private:     int _maxSize;     std::unordered_set<T> _set;     std::queue<T> _queue;  public:     explicit Cache(int maxSize) : _maxSize(maxSize){}      bool add(T value){         if(_set.find(value) == _set.end()){ // // if not exists in set             if(_set.size() == _maxSize){ // if set is 'full'                 _set.erase(_queue.front()); // delete the oldest value from the set                 _queue.pop(); // delete oldest value from queue             }             _queue.push(value); // push new value into queue             _set.insert(value);  // insert new value into set             return true;         }         return false;     }      int size(){         return static_cast<int>(_set.size());     } }; 

Publish Health Niche Guest Post on “Curezone.com (Limited Offer) Only for 5 client for $25

What you get with this service? I’ll write & submit a guest post on the Health Niche website – Curezone.com This will be a blog on the “Curezone” website with a Domain Authority where your link will be live and Google Indexed. What will you get? – Permanent Post – Do-Follow Backlink This Hourlie is for limited period. It’ll increase your SERP value in Google Search. ➡️ Please note that this is NOT a paid media placement. The fee is for me representing you and doing outreach for you. But if my efforts don’t result in publishing an article for you, you’ll get a full refund of the deposit. I refuse to let your budget be affected by efforts that don’t yield results. ➡️ The metrics of the Curezone website are as follows: Domain Authority (DA): 60 Page Authority (PA): 66 Trust Flow (TF): 62 Citation Flow (CT): 52 ★★ Please note ★★ 1. The pricing includes complete content creation, pitching and publication. And also you can provide your own article for submission if you want. 2. The turnaround time is 3 days. 3. I cannot work with adult niches. ★★ Key Features ★★ ➡️ UNIQUE 500 Word Hand Written article based on your subject and keywords. ➡️ Researched, SEO-friendly and reader-friendly content ➡️ Each post will include relevant pictures and headings. ➡️ You will receive an exact report with the links where your blog posts are posted ➡️ articles are posted on really high quality websites, with only unique content and few outgoing links. ➡️ The Guest Post Back-links will Surely improve your Presence in Search Engines. Feel free to contact us and we’ll be glad to help.

by: seotrust
Created: —
Category: Guest Posts
Viewed: 227