text:
Q: Javascript How to canvas drawing work on Mobile I want to make canvas drawing but this code not working on Mobile browser
const canvas = document.getElementById("draw");
    canvas.width = window.innerWidth - 60;
    canvas.height = 400;

    let context = canvas.getContext("2d");
    context.fillStyle = "white";
    context.fillRect(0, 0, canvas.width, canvas.height);

    let draw_color = "black";
    let draw_width = "2";
    let is_drawing = false;

    canvas.addEventListener("touchstart", start, false);
    canvas.addEventListener("touchmove", draw, false);
    canvas.addEventListener("mousedown", start, false);
    canvas.addEventListener("mousemove", draw, false);

    canvas.addEventListener("touchend", stop, false);
    canvas.addEventListener("mouseup", stop, false);
    canvas.addEventListener("mouseout", stop, false);

    function start(event) {
        is_drawing = true;
        context.beginPath();
        context.moveTo(event.clientX - canvas.offsetLeft,
                       event.clientY - canvas.offsetTop);
        event.preventDefault();
    }

    function draw(event) {
        if (is_drawing) {
            context.lineTo(event.clientX - canvas.offsetLeft,
                           event.clientY - canvas.offsetTop);
            context.strokeStyle = draw_color;
            context.lineWidth = draw_width;
            context.lineCap = "round";
            context.lineJoin = "round";
            context.stroke();
        }
        event.preventDefault();
    }

    function stop(event) {
        if (is_drawing) {
            context.stroke();
            context.closePath();
            is_drawing = false;
        }
        event.preventDefault();
    }

A: try this
function draw(event) {
   e.preventDefault();
    e.stopPropagation();
    if (is_drawing) {
        context.lineTo(event.clientX - canvas.offsetLeft,
                       event.clientY - canvas.offsetTop);
        context.strokeStyle = draw_color;
        context.lineWidth = draw_width;
        context.lineCap = "round";
        context.lineJoin = "round";
        context.stroke();
    }
}


text:
Q: Loading an interstital Ad on a timer with a loading page with navigation app? I'm looking to show a screen (non-interactive) to show for a few seconds, before presenting an interstitial ad.
At the moment, my interstitial is called using a method
[self showStartupAd];

Which shows this; which of course shows the ad.
-(void)showStartupAd{
    UIViewController *rootController = self.window.rootViewController;
    [IronSource showInterstitialWithViewController:rootController placement:0];
}

However, I would like to show a basic timer, say, to show for 5 seconds, an activityview or indicator of some sort, that launches first, which allows the user to see a short text (such as 'Sponsored ad loading' and then have a method for when the timer ends/view dismisses, to then show the ad (I can then handle the rest in the ad callbacks).
I can of course get a progress view showing like this;
UIViewController *rootController = self.window.rootViewController;

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.frame = CGRectMake(0.0, 0.0, 140.0, 140.0);
indicator.center = rootController.view.center;
[rootController.view addSubview:indicator];
[indicator bringSubviewToFront:rootController.view];
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;

[indicator startAnimating];

But this doesn't show any kind of screen I can customise / use callbacks from.

A: Assuming that the initial view controller is not a UINavigationController:

*

*Put the content you wish to show on the initial view controller

*On that same view controller, override viewDidAppear and add a dispatch-after block with whatever delay you would like (see https://www.codegrepper.com/code-examples/objectivec/dispatch+after+objective+c)

*Inside the dispatch block, put showStartupAd

redpajama_set_name: RedPajamaStackExchange


text:
Q: An error while compare pointer with "NULL" I got an error while  "if (this == nullptr)" , the error :
 warning: nonnull argument 'this' compared to NULL [-Wnonnull-compare]

22 |             if (this != nullptr)
The command : g++ -std=c++11 -DNDEBUG -Wall .\avl.cpp
Why can't I compare pointer with nullptr ? (null doesn't work either).
How am I supposed to check if the pointer is null?
The code :
#include <iostream>
#include <stdlib.h>

namespace AVL{
    template <class T>
    class Node{

        public:
        T data;
        Node<T> *left,*right;
        int height;
        ~Node(){
            delete left;
            delete right;
        }
        Node(T& inData):data(inData),left(NULL),right(NULL),height(1){};

        Node<T> * insert_node (T & inData)
        {
            if (this == nullptr)
                return new Node<T> (inData);

            if (inData < data)
                left = left -> insert_node (inData);
            else
                right = right -> insert_node (inData);
            return this;
        }
        private:

        void compute_height(){
            height=0;
            if(left != NULL && left->height > height){height = left->height;}
            if(right != NULL && right->height > height){height = right->height;}
        }

};
}

int main ()
{
    int num1=55,num2=76;
    AVL::Node<int> *new_node1 = new AVL::Node<int>(num1);
    AVL::Node<int> *new_node2 = new AVL::Node<int>(num2);
    new_node2=new_node1->insert_node(num2);
    system("pause");

}

A: First, it is a warning, not an error:
warning: nonnull argument 'this' compared to NULL [-Wnonnull-compare]
   22 |             if (this == 0)

The compiler tries to tell you that it makes no sense to compare this to NULL (or 0 or nullptr), because this == 0 or this == nullptr or this == NULL is never true.
this is never 0, NULL or nullptr. The condition can and should be removed.

Why can't I compare pointer with nullptr ?

You can compare this with nullptr or 0. It just doesn't make sense because the result is always false.

How am I supposed to check if the pointer is null?

You are not supposed to check if this is null, because that never happens. It's not quite clear what purpose that if is supposed to have in your code. If you expected it to catch errors like this:
Node* n = nullptr;
new_node = n->insert_node(num2);  // UB!!

Then you were wrong. Dereferencing a null pointer is undefined behavior. You cannot call a member function on a nullpointer, hence inside a member function this is never nullptr.

A:
I got an error ...

warning:

That's not an error. That's a warning.

Why can't I compare pointer with nullptr ?

You can compare the pointer with null. It's just pointless in this case because this is never null. It's like comparing whether unsigned integer is >= 0 or to test a_bool == true || a_bool == false. There is no case where the test would be false.
That is why the compiler is being helpful and warns that you wrote something that doesn't make sense. Think about the reason why you thought it would be useful to write that check, and then compare that reason with the fact that this can never be null. There's probably a more serious bug than redundant test...
And here is the serious bug:

left = left -> insert_node (inData);

You never test whether left is null before indirecting through it. The consequence is that the behaviour of the program is be undefined. Don't do this. You may indirect only through valid pointers.
You can also find this bug easily using an address sanitiser.

A: insert_node is a non-static member function. It may be called for an existent object. So this can not be a null pointer. As a result the if statement does not make a sense.
    Node<T> * insert_node (T & inData)
    {
        if (this == nullptr)
            return new Node<T> (inData);
            //...

Moreover this code snippet
AVL::Node<int> *new_node2 = new AVL::Node<int>(num2);
new_node2=new_node1->insert_node(num2);

produces a memory leak.


text:
Q: remove the local timezone from a date in javascript? I was wondering if I can remove the timezone from the date using javascript? I get the datetime on a json format, now I want to set it back but it returns more info of what I actually want/need.
What I have now is:
var d = new Date();
d.setTime(1432851021000);
document.write(d);

and the output is something like this:
Thu May 28 2015 16:10:21 GMT-0600 (CST)

Id like to show only until the hour, and remove GMT-0600 (CST).
I know javascript takes that depending on the current user's timezone, which is a problem, because the information could be saved on different countries.
I am trying to avoid to create the format using something like:
d.date() + "/" + d.month()...etc

Is there a better solution for this?

A: Using moment
moment().utcOffset(0, true).format()

From Javascript Date
var date = new Date();
Tue Sep 06 2021 00:00:00 GMT+0200

var isoDate = date.toISOString()
'2021-09-05T22:00:00.000Z'

var clearUTCDate = moment(date).utcOffset(0, true).format()
'2021-09-06T00:00:00Z'

A: I believe d.toDateString() will output the format you're looking for.
var d = new Date();
d.setTime(1432851021000);
d.toDateString(); // outputs to "Thu May 28 2015"
d.toGMTString(); //outputs to "Thu, 28 May 2015 22:10:21 GMT"

Or even d.toLocaleString()
"5/28/2015, 6:10:21 PM"
There are lots of methods available to Date()

A: with momentjs
var d = new Date();
d.setTime(1432851021000);

var newdate = moment(d);

alert(newdate.format("MMM DD/MM/YYYY HH:mm:ss "));

http://jsfiddle.net/vynvepak/

A: Since the part you want will always has fixed length you can use:
d.toString().slice(0, 24)

jsfiddle

A: You can use 2 options:
1. use split function: d.split('GMT'). this gives you an array.
2. get the usual js data functions like getHour and getFullYear and so on to format the result as you prefer.

A: var x = d.toDateString().length;
var result = d.toDateString() + d.toString().substring(x,x+9);

A: var date = new Date(myUnixTimestamp*1000);
var prettyDate = date.toLocaleString();

A: I have created simple js function to remove timezone part from datetime string. It which will give output like

*

*2019-07-27T19:00:00.000-0700 => 2019-07-27T19:00:00.000

*2019-09-17T19:00:00.000+0100 => 2019-09-17T19:00:00.000

function removeTimeZonePart(dateString) {

             let finalDate = '';

             if (dateString.split('+').length > 1) {
                 let b = dateString.split('+');

                 finalDate = b[0];
             } else {
                 let b = dateString.split('-');

                  if (b.length > 1) {
                   b.pop();
                   finalDate = b.join('-');
                 }
             }

             return finalDate;

}

alert(removeTimeZonePart('2019-07-27T19:00:00.000-0700'));

A: Using Luxon, the sample code below takes the current date and time, making it time zone agnostic in an ISO Standard Format.

const { DateTime, ToISOTimeOptions } = window.luxon;
const currentDate = new Date();

// Unspecified timezone.
console.log(
  DateTime.fromJSDate(currentDate)
    .toISO(
          {includeOffset:false} // ToISOTimeOptions
    )
  );
<script src="https://cdn.jsdelivr.net/npm/luxon@2.0.2/build/global/luxon.min.js"></script>

A: There are 2 ways -
1. .toLocaleString()
Will give you date time in this format -
'24/11/2021, 20:19:36'
but there's a caveat, you cannot parse this date-
const myDate = new Date('24/11/2021, 20:19:36')
=> Invalid Date

If you want to be able to parse the date again, and also remove the timezone, use the 2nd method
2. .split("GMT")[0]
Input:
new Date()
Wed Nov 24 2021 20:23:54 GMT+0530 (India Standard Time)
Output:
"Wed Nov 24 2021 20:25:17 GMT+0530 (India Standard Time)".split('GMT')[0]
'Wed Nov 24 2021 20:25:17 '

A: Regex arrived to the party

// for ISO Datetime strings only

const rmvTZOffset = str => str.replace(/[+-]\d\d:\d\d$/, '')

console.log(rmvTZOffset('2023-02-22T10:18:17+00:00'))
console.log(rmvTZOffset('2024-02-22T10:18:17.7543-02:30'))

const zone = 'Europe/Lisbon'
fetch('https://worldtimeapi.org/api/timezone/' + zone)
  .then(r => r.json())
  .then(r => {
    console.log(rmvTZOffset(r.datetime))
  })

A: I feel there is a better yet simpler solution!

*

*Extract the Day, Month & Year from your "Date Variable".

*

*var day = d.getDate(); //to get the day

*var month = d.getMonth(); // to get the month

*var year = d.getYear(); // to get the year

*Now just assign a new variable like

*

*var newDate = day+"/"+(month+1)+"/"+year; //Note, we are doing (month+1) because in Javascript the month varibale runs from {0-11} (0: Jan , 1:Feb,2: Mar, 4: Apr.... 11:Dec)

And there you have it, your customized date without timezone is ready!


text:
Q: Firebase still retrieving authData after deletion After I manually deleted the account connected to the uid that my iphone simulator is on (from firebase dashboard), when I run the code below it's somehow still authenticating and retrieving a uid. How is this possible?
let ref = Firebase(url: "https://moviebuffapp.firebaseio.com/")

override func viewDidLoad() {
    super.viewDidLoad()

    if ref.authData != nil {

        let uid = ref.authData.uid
        print(uid)

A: Deleting an account does not automatically expire the current session(s) for that account. Their current sessions will remain valid until they expire. You can set the session expiration interval in your Firebase Dashboard.
If you want to force the user to be logged out, call ref.unauth().
But in general you'll likely want to build authorization rules to prevent such users with valid tokens from deleted accounts to make changes to the data.
If you keep the user profiles in your database, you can check whether that record still exists in your security rules: root.child('users').child(auth.uid).exists().
Also see:

*

*Firebase authentication not revoked when user deleted?

*Deletion of User in firebase does not trigger onAuth method


text:
Q: Twilio javascript client has no audio I tried using the Twilio Javascript Client Quickstart and am having some audio issues. I am trying to place a call to a cell phone from the browser. In general, everything seems to work without errors. The issue I am having seems to be an audio problem.
Edge - The call goes through, I can hear the audio from the microphone on the client but I cannot hear the audio from the phone on the client.
Chrome - I cannot even get the call to connect because I cannot click the Call button. It seems to get hung up on the microphone permission.
Firefox - The call goes though but no audio on either end.
IE - The Call button and textbox too enter in the phone number on the client don't even display.
Does anyone have any suggestions? Thanks!!
EDIT: Based on the comments I tried to use the sample files without changing them. There were some errors and I had to add the bootstrap and modernizr packages in nuget. Same result. No audio.


text:
Q: Cant enable bluetooth on 18.04 First time Linux user, just installed Ubuntu 18.04.4 LTS on an old Satellite L510 (model No. PSLF2A 01U00R)
In settings I can't turn the Bluetooth slider to 'on'.
"No Bluetooth found, plug in a dongle to use bluetooth".
A wireless mouse does work with a dongle but a wireless Logitech K380 keyboard is not recognised (doesnt come with dongle).
Specs for this laptop specify Bluetooth 2.1
Any help appreciated. Thanks
familypc@familypc-Satellite-L510:~$ lspci -knn | grep Net -A3; lsusb
Bus 002 Device 003: ID 0bda:8198 Realtek Semiconductor Corp. RTL8187B Wireless Adapter
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 04f2:b120 Chicony Electronics Co., Ltd
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub


text:
Q: How to Split a text into List by multiple characters Let's say i have:
string text = "Ivan - George ; Josh , Mike John";

And i want to split it by
" - ", " ; " , " ".

Normally when I want to split a text by 1 element I would use:
List<string> names = text.Split(" - ").ToList();

But now I encountered a problem where i need to split a text by multiple characters and I don't know how to do it...

A: List<string> names = text.Split(
    new []{" - ", " ; ", " "},
    StringSplitOptions.None).ToList();


text:
Q: Blank Xamarin watchOS app does not deploy to device - "Execution failed" When creating an empty Xamarin iOS project via Visual Studio for Mac 2022 "iOS -> App -> Xamarin -> Single View App" and then adding a watchOS project "watchOS -> App -> Xamarin -> WatchKit App" the build is working fine.
Nuget package restore issue could be solved by adding <ReferenceOutputAssembly>false</ReferenceOutputAssembly> to the Watch App Project Reference in the iOS app project file.
The build for all three projects (iOS App, WatchOS Extension, WatchOS App) succeeds without any errors. When trying to deploy the watchOS target to any device, either Simulator or physical Apple Watch, VS just shows "Execution failed" and doesn't give any more detail why it failed.
While researching for a solution we stumpled across a GitHub issue in the xamarin-macios repo that states that watchOS will not be supported with .NET 6. We haven't found an official statement regarding watchOS not being supported anymore. Does that mean it is not possible to deploy a Xamarin watchOS app and also watchOS not supported within MAUI?
Current setup:

*

*Operating System: Mac OS X 12.6.2

*Visual Studio Enterprise 2022 for Mac, Version 17.4.3 (build 21)

*Runtime: .NET 6.0.12 (64-bit), Architecture: X64

*NuGet Version: 6.3.1.1

*Xcode 14.2 (21534), Build 14C18

*Xamarin.iOS, Version: 16.1.1.27 (Visual Studio Enterprise)

Deploying a blank watchOS app in Visual Studio results in "Execution failed"


text:
Q: How to convert Hour to 12 HRS / 24 HRS Format with javascript i convert Hour to 12 HRS / 24 HRS Format this way in c# but not being able to do the same in javascript.
my c# code for formatting 12 HRS / 24 HRS Format as below
for (int i = 0; i <= 15; i++)
{
    strHrs.Add((i == 0 ? "00" : Convert.ToDateTime(TimeSpan.FromHours(i).ToString()).ToString("hh")),
        (i == 0 ? "00" : Convert.ToDateTime(TimeSpan.FromHours(i).ToString()).ToString("HH")));
}

i got a js code which looks fine
var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = H < 12 ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;

i have to show 12 hrs format in dropdown text but have to show 24 hrs format in dropdown value.
but how to apply in my case not very sure. so any help would be appreciated. thanks
EDIT
        function convertDateTo12Hrs(timeStr, is24) {
            if (is24) {
                var BigHrs = timeStr.toString().length == 1 ? "0" + timeStr : timeStr;
                return BigHrs; // return if is24 true
            }
            var h = "" + (+timeStr > 12 ? timeStr - 12 : timeStr);
            return h.length == 1 ? "0" + h : h;
        }

Calling
convert("2", true); // "02"
convert("18", false); // "06"

A: Base on your comment on my post, you could just create a function which would return both.
function convert(timeStr, is24) {
    if (is24) return timeStr; // return if is24 true
    var h = "" + (+timeStr  > 12 ? timeStr - 12 : timeStr);
    return h.length == 1 ? "0" + h : h;
}

Now you can call it like
convert("18", true); // "18"
convert("18", false); // "06"


text:
Q: Move Settings folder to settings.py Recently I received a started project with Django and Python, the project is constantly giving us errors, but some of them are probably because the last programmer made a directory of settings instead a settings.py. My question is if there is some way of move all this .py in the settings folder to a new python file called settings.py, to optimize it.
I algo post the error message,
Thanks!
    PS C:\Users\jmtorices\Documents\shpssl-main> py manage.py runserver
Invalid line: ÿþSECRET_KEY=my_secret_key_value
Invalid line:
Invalid line: DEBUG=True
Invalid line:
Invalid line:
Invalid line:
Invalid line: import environ
Invalid line:
Invalid line:
Invalid line:
Invalid line: env = environ.Env()
Invalid line:
Invalid line: environ.Env.read_env(os.path.join(BASE_DIR, 'somepath/.env')) # < --where ever your.env lies inside project directory
Invalid line:
Invalid line: SECRET_KEY = os.environ.get('somekeyInsidenvFile', env('somekeyInsidenvFile')) #
Invalid line: ÿþSECRET_KEY=my_secret_key_value
Invalid line:
Invalid line: DEBUG=True
Invalid line:
Invalid line:
Invalid line:
Invalid line: import environ
Invalid line:
Invalid line:
Invalid line:
Invalid line: env = environ.Env()
Invalid line:
Invalid line: environ.Env.read_env(os.path.join(BASE_DIR, 'somepath/.env')) # < --where ever your.env lies inside project directory
Invalid line:
Invalid line: SECRET_KEY = os.environ.get('somekeyInsidenvFile', env('somekeyInsidenvFile')) #
Invalid line: ÿþSECRET_KEY=my_secret_key_value
Invalid line:
Invalid line: DEBUG=True
Invalid line:
Invalid line:
Invalid line:
Invalid line: import environ
Invalid line:
Invalid line:
Invalid line:
Invalid line: env = environ.Env()
Invalid line:
Invalid line: environ.Env.read_env(os.path.join(BASE_DIR, 'somepath/.env')) # < --where ever your.env lies inside project directory
Invalid line:
Invalid line: SECRET_KEY = os.environ.get('somekeyInsidenvFile', env('somekeyInsidenvFile')) #
Traceback (most recent call last):
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\environ\environ.py", line 403, in get_value
    value = self.ENVIRON[var_name]
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\os.py", line 680, in __getitem__
    raise KeyError(key) from None
KeyError: 'SECRET_KEY'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\jmtorices\Documents\shpssl-main\manage.py", line 22, in <module>
    main()
  File "C:\Users\jmtorices\Documents\shpssl-main\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line
    utility.execute()
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 66, in execute
    super().execute(*args, **options)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 417, in execute
    output = self.handle(*args, **options)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 73, in handle
    if not settings.DEBUG and not settings.ALLOWED_HOSTS:
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf\__init__.py", line 84, in __getattr__
    self._setup(name)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf\__init__.py", line 71, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf\__init__.py", line 179, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\jmtorices\Documents\shpssl-main\shpssl\settings\production.py", line 6, in <module>
    from .base import *
  File "C:\Users\jmtorices\Documents\shpssl-main\shpssl\settings\base.py", line 39, in <module>
    SECRET_KEY = env('SECRET_KEY')
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\environ\environ.py", line 197, in __call__
    return self.get_value(
  File "C:\Users\jmtorices\AppData\Local\Programs\Python\Python310\lib\site-packages\environ\environ.py", line 407, in get_value
    raise ImproperlyConfigured(error_msg) from exc
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable


text: Q: iOS app can record audio, but in the same iOS app, at the in-app browser audio is not recording I have an iOS app which has audio record in it, which is recording the audio, after giving microphone permission. But in the same iOS app, in the in-app browser, audio is not recording. What is the issue? Why audio is not recording?


text:
Q: iitialize ImageCache from the context of an activity I try to understand this sample to match with mine:(DisplayingBitmaps)
http://developer.android.com/downloads/samples/DisplayingBitmaps.zip
This code uses the class ImageCache that manages the caching of bitmaps:
public class ImageCache {
private static final String TAG = "ImageCache";

// Default memory cache size in kilobytes
private static final int DEFAULT_MEM_CACHE_SIZE = 1024 * 5; // 5MB

// Default disk cache size in bytes
private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB

// Compression settings when writing images to disk cache
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
private static final int DEFAULT_COMPRESS_QUALITY = 70;
private static final int DISK_CACHE_INDEX = 0;

// Constants to easily toggle various caches
private static final boolean DEFAULT_MEM_CACHE_ENABLED = true;
private static final boolean DEFAULT_DISK_CACHE_ENABLED = true;
private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false;

private DiskLruCache mDiskLruCache;
private LruCache<String, BitmapDrawable> mMemoryCache;
public static ImageCacheParams mCacheParams;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;

private Set<SoftReference<Bitmap>> mReusableBitmaps;

/**
 * Create a new ImageCache object using the specified parameters. This should not be
 * called directly by other classes, instead use
 * {@link ImageCache#getInstance(FragmentManager, ImageCacheParams)} to fetch an ImageCache
 * instance.
 *
 * @param cacheParams The cache parameters to use to initialize the cache
 */
public ImageCache(ImageCacheParams cacheParams) {

    init(cacheParams);
}

/**
 * Return an {@link ImageCache} instance. A {@link RetainFragment} is used to retain the
 * ImageCache object across configuration changes such as a change in device orientation.
 *
 * @param fragmentManager The fragment manager to use when dealing with the retained fragment.
 * @param cacheParams The cache parameters to use if the ImageCache needs instantiation.
 * @return An existing retained ImageCache object or a new one if one did not exist
 */
public static ImageCache getInstance(
        FragmentManager fragmentManager, ImageCacheParams cacheParams) {

    // Search for, or create an instance of the non-UI RetainFragment
    final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager);

    // See if we already have an ImageCache stored in RetainFragment
    ImageCache imageCache = (ImageCache) mRetainFragment.getObject();

    // No existing ImageCache, create one and store it in RetainFragment
    if (imageCache == null) {
        imageCache = new ImageCache(cacheParams);
        mRetainFragment.setObject(imageCache);
    }

    return imageCache;
}

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 */
public void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps =
                    Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key,
                    BitmapDrawable oldValue, BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable

                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the bitmap
                        // to a SoftReference set for possible use with inBitmap later
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
    //END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

/**
 * Initializes the disk cache.  Note that this includes disk access so this should not be
 * executed on the main/UI thread. By default an ImageCache does not initialize the disk
 * cache when it is created, instead you should call initDiskCache() to initialize it on a
 * background thread.
 */
public void initDiskCache() {
    // Set up disk cache
    synchronized (mDiskCacheLock) {
        if (mDiskLruCache == null || mDiskLruCache.isClosed()) {
            File diskCacheDir = mCacheParams.diskCacheDir;
            if (mCacheParams.diskCacheEnabled && diskCacheDir != null) {
                if (!diskCacheDir.exists()) {
                    diskCacheDir.mkdirs();
                }
                if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) {
                    try {
                        mDiskLruCache = DiskLruCache.open(
                                diskCacheDir, 1, 1, mCacheParams.diskCacheSize);
                        if (BuildConfig.DEBUG) {
                            Log.d(TAG, "Disk cache initialized");
                        }
                    } catch (final IOException e) {
                        mCacheParams.diskCacheDir = null;
                        Log.e(TAG, "initDiskCache - " + e);
                    }
                }
            }
        }
        mDiskCacheStarting = false;
        mDiskCacheLock.notifyAll();
    }
}

public void addBitmapToCache(String data, BitmapDrawable value) {
    //BEGIN_INCLUDE(add_bitmap_to_cache)
    if (data == null || value == null) {
        return;
    }

    // Add to memory cache
    if (mMemoryCache != null) {
        if (RecyclingBitmapDrawable.class.isInstance(value)) {
            // The removed entry is a recycling drawable, so notify it
            // that it has been added into the memory cache
            ((RecyclingBitmapDrawable) value).setIsCached(true);
        }
        mMemoryCache.put(data, value);
    }

    synchronized (mDiskCacheLock) {
        // Add to disk cache
        if (mDiskLruCache != null) {
            final String key = hashKeyForDisk(data);
            OutputStream out = null;
            try {
                DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
                if (snapshot == null) {
                    final DiskLruCache.Editor editor = mDiskLruCache.edit(key);
                    if (editor != null) {
                        out = editor.newOutputStream(DISK_CACHE_INDEX);
                        value.getBitmap().compress(
                                mCacheParams.compressFormat, mCacheParams.compressQuality, out);
                        editor.commit();
                        out.close();
                    }
                } else {
                    snapshot.getInputStream(DISK_CACHE_INDEX).close();
                }
            } catch (final IOException e) {
                Log.e(TAG, "addBitmapToCache - " + e);
            } catch (Exception e) {
                Log.e(TAG, "addBitmapToCache - " + e);
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {}
            }
        }
    }
    //END_INCLUDE(add_bitmap_to_cache)
}

public BitmapDrawable getBitmapFromMemCache(String data) {
    //BEGIN_INCLUDE(get_bitmap_from_mem_cache)
    BitmapDrawable memValue = null;

    if (mMemoryCache != null) {
        memValue = mMemoryCache.get(data);
    }

    if (BuildConfig.DEBUG && memValue != null) {
        Log.d(TAG, "Memory cache hit");
    }

    return memValue;
    //END_INCLUDE(get_bitmap_from_mem_cache)
}

public Bitmap getBitmapFromDiskCache(String data) {
    //BEGIN_INCLUDE(get_bitmap_from_disk_cache)
    final String key = hashKeyForDisk(data);
    Bitmap bitmap = null;

    synchronized (mDiskCacheLock) {
        while (mDiskCacheStarting) {
            try {
                mDiskCacheLock.wait();
            } catch (InterruptedException e) {}
        }
        if (mDiskLruCache != null) {
            InputStream inputStream = null;
            try {
                final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
                if (snapshot != null) {
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "Disk cache hit");
                    }
                    inputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
                    if (inputStream != null) {
                        FileDescriptor fd = ((FileInputStream) inputStream).getFD();

                        // Decode bitmap, but we don't want to sample so give
                        // MAX_VALUE as the target dimensions
                        bitmap = ImageResizer.decodeSampledBitmapFromDescriptor(
                                fd, Integer.MAX_VALUE, Integer.MAX_VALUE, this);
                    }
                }
            } catch (final IOException e) {
                Log.e(TAG, "getBitmapFromDiskCache - " + e);
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {}
            }
        }
        return bitmap;
    }
    //END_INCLUDE(get_bitmap_from_disk_cache)
}

/**
 * @param options - BitmapFactory.Options with out* options populated
 * @return Bitmap that case be used for inBitmap
 */
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
    //BEGIN_INCLUDE(get_bitmap_from_reusable_set)
    Bitmap bitmap = null;

    if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
        synchronized (mReusableBitmaps) {
            final Iterator<SoftReference<Bitmap>> iterator = mReusableBitmaps.iterator();
            Bitmap item;

            while (iterator.hasNext()) {
                item = iterator.next().get();

                if (null != item && item.isMutable()) {
                    // Check to see it the item can be used for inBitmap
                    if (canUseForInBitmap(item, options)) {
                        bitmap = item;

                        // Remove from reusable set so it can't be used again
                        iterator.remove();
                        break;
                    }
                } else {
                    // Remove from the set if the reference has been cleared.
                    iterator.remove();
                }
            }
        }
    }

    return bitmap;
    //END_INCLUDE(get_bitmap_from_reusable_set)
}

/**
 * Clears both the memory and disk cache associated with this ImageCache object. Note that
 * this includes disk access so this should not be executed on the main/UI thread.
 */
public void clearCache() {
    if (mMemoryCache != null) {
        mMemoryCache.evictAll();
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Memory cache cleared");
        }
    }

    synchronized (mDiskCacheLock) {
        mDiskCacheStarting = true;
        if (mDiskLruCache != null && !mDiskLruCache.isClosed()) {
            try {
                mDiskLruCache.delete();
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Disk cache cleared");
                }
            } catch (IOException e) {
                Log.e(TAG, "clearCache - " + e);
            }
            mDiskLruCache = null;
            initDiskCache();
        }
    }
}

/**
 * Flushes the disk cache associated with this ImageCache object. Note that this includes
 * disk access so this should not be executed on the main/UI thread.
 */
public void flush() {
    synchronized (mDiskCacheLock) {
        if (mDiskLruCache != null) {
            try {
                mDiskLruCache.flush();
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Disk cache flushed");
                }
            } catch (IOException e) {
                Log.e(TAG, "flush - " + e);
            }
        }
    }
}

/**
 * Closes the disk cache associated with this ImageCache object. Note that this includes
 * disk access so this should not be executed on the main/UI thread.
 */
public void close() {
    synchronized (mDiskCacheLock) {
        if (mDiskLruCache != null) {
            try {
                if (!mDiskLruCache.isClosed()) {
                    mDiskLruCache.close();
                    mDiskLruCache = null;
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "Disk cache closed");
                    }
                }
            } catch (IOException e) {
                Log.e(TAG, "close - " + e);
            }
        }
    }
}

/**
 * A holder class that contains cache parameters.
 */
public static class ImageCacheParams {
    public int memCacheSize = DEFAULT_MEM_CACHE_SIZE;
    public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE;
    public File diskCacheDir;
    public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
    public int compressQuality = DEFAULT_COMPRESS_QUALITY;
    public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;
    public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED;
    public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE;

    /**
     * Create a set of image cache parameters that can be provided to
     * {@link ImageCache#getInstance(FragmentManager, ImageCacheParams)} or
     * {@link ImageWorker#addImageCache(FragmentManager, ImageCacheParams)}.
     * @param context A context to use.
     * @param diskCacheDirectoryName A unique subdirectory name that will be appended to the
     *                               application cache directory. Usually "cache" or "images"
     *                               is sufficient.
     */
    public ImageCacheParams(Context context, String diskCacheDirectoryName) {
        diskCacheDir = getDiskCacheDir(context, diskCacheDirectoryName);
    }

    /**
     * Sets the memory cache size based on a percentage of the max available VM memory.
     * Eg. setting percent to 0.2 would set the memory cache to one fifth of the available
     * memory. Throws {@link IllegalArgumentException} if percent is < 0.01 or > .8.
     * memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed
     * to construct a LruCache which takes an int in its constructor.
     *
     * This value should be chosen carefully based on a number of factors
     * Refer to the corresponding Android Training class for more discussion:
     * http://developer.android.com/training/displaying-bitmaps/
     *
     * @param percent Percent of available app memory to use to size memory cache
     */
    public void setMemCacheSizePercent(float percent) {
        if (percent < 0.01f || percent > 0.8f) {
            throw new IllegalArgumentException("setMemCacheSizePercent - percent must be "
                    + "between 0.01 and 0.8 (inclusive)");
        }
        memCacheSize = Math.round(percent * Runtime.getRuntime().maxMemory() / 1024);
    }
}

/**
 * @param candidate - Bitmap to check
 * @param targetOptions - Options that have the out* value populated
 * @return true if candidate can be used for inBitmap re-use with
 *      targetOptions
 */
@TargetApi(VERSION_CODES.KITKAT)
private static boolean canUseForInBitmap(
        Bitmap candidate, BitmapFactory.Options targetOptions) {
    //BEGIN_INCLUDE(can_use_for_inbitmap)
    if (!Utils.hasKitKat()) {
        // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
        return candidate.getWidth() == targetOptions.outWidth
                && candidate.getHeight() == targetOptions.outHeight
                && targetOptions.inSampleSize == 1;
    }

    // From Android 4.4 (KitKat) onward we can re-use if the byte size of the new bitmap
    // is smaller than the reusable bitmap candidate allocation byte count.
    int width = targetOptions.outWidth / targetOptions.inSampleSize;
    int height = targetOptions.outHeight / targetOptions.inSampleSize;
    int byteCount = width * height * getBytesPerPixel(candidate.getConfig());
    return byteCount <= candidate.getAllocationByteCount();
    //END_INCLUDE(can_use_for_inbitmap)
}

/**
 * Return the byte usage per pixel of a bitmap based on its configuration.
 * @param config The bitmap configuration.
 * @return The byte usage per pixel.
 */
private static int getBytesPerPixel(Config config) {
    if (config == Config.ARGB_8888) {
        return 4;
    } else if (config == Config.RGB_565) {
        return 2;
    } else if (config == Config.ARGB_4444) {
        return 2;
    } else if (config == Config.ALPHA_8) {
        return 1;
    }
    return 1;
}

/**
 * Get a usable cache directory (external if available, internal otherwise).
 *
 * @param context The context to use
 * @param uniqueName A unique directory name to append to the cache dir
 * @return The cache dir
 */
public static File getDiskCacheDir(Context context, String uniqueName) {
    // Check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
    final String cachePath =
            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                    !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
                            context.getCacheDir().getPath();

    return new File(cachePath + File.separator + uniqueName);
}

/**
 * A hashing method that changes a string (like a URL) into a hash suitable for using as a
 * disk filename.
 */
public static String hashKeyForDisk(String key) {
    String cacheKey;
    try {
        final MessageDigest mDigest = MessageDigest.getInstance("MD5");
        mDigest.update(key.getBytes());
        cacheKey = bytesToHexString(mDigest.digest());
    } catch (NoSuchAlgorithmException e) {
        cacheKey = String.valueOf(key.hashCode());
    }
    return cacheKey;
}

private static String bytesToHexString(byte[] bytes) {
    // http://stackoverflow.com/questions/332079
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(0xFF & bytes[i]);
        if (hex.length() == 1) {
            sb.append('0');
        }
        sb.append(hex);
    }
    return sb.toString();
}

/**
 * Get the size in bytes of a bitmap in a BitmapDrawable. Note that from Android 4.4 (KitKat)
 * onward this returns the allocated memory size of the bitmap which can be larger than the
 * actual bitmap data byte count (in the case it was re-used).
 *
 * @param value
 * @return size in bytes
 */
@TargetApi(VERSION_CODES.KITKAT)
public static int getBitmapSize(BitmapDrawable value) {
    Bitmap bitmap = value.getBitmap();

    // From KitKat onward use getAllocationByteCount() as allocated bytes can potentially be
    // larger than bitmap byte count.
    if (Utils.hasKitKat()) {
        return bitmap.getAllocationByteCount();
    }

    if (Utils.hasHoneycombMR1()) {
        return bitmap.getByteCount();
    }

    // Pre HC-MR1
    return bitmap.getRowBytes() * bitmap.getHeight();
}

/**
 * Check if external storage is built-in or removable.
 *
 * @return True if external storage is removable (like an SD card), false
 *         otherwise.
 */
@TargetApi(VERSION_CODES.GINGERBREAD)
public static boolean isExternalStorageRemovable() {
    if (Utils.hasGingerbread()) {
        return Environment.isExternalStorageRemovable();
    }
    return true;
}

/**
 * Get the external app cache directory.
 *
 * @param context The context to use
 * @return The external cache dir
 */
@TargetApi(VERSION_CODES.FROYO)
public static File getExternalCacheDir(Context context) {
    if (Utils.hasFroyo()) {
        return context.getExternalCacheDir();
    }

    // Before Froyo we need to construct the external cache dir ourselves
    final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
    return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}

/**
 * Check how much usable space is available at a given path.
 *
 * @param path The path to check
 * @return The space available in bytes
 */
@TargetApi(VERSION_CODES.GINGERBREAD)
public static long getUsableSpace(File path) {
    if (Utils.hasGingerbread()) {
        return path.getUsableSpace();
    }
    final StatFs stats = new StatFs(path.getPath());
    return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}

/**
 * Locate an existing instance of this Fragment or if not found, create and
 * add it using FragmentManager.
 *
 * @param fm The FragmentManager manager to use.
 * @return The existing instance of the Fragment or the new instance if just
 *         created.
 */
private static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
    //BEGIN_INCLUDE(find_create_retain_fragment)
    // Check to see if we have retained the worker fragment.
    RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(TAG);

    // If not retained (or first time running), we need to create and add it.
    if (mRetainFragment == null) {
        mRetainFragment = new RetainFragment();
        fm.beginTransaction().add(mRetainFragment, TAG).commitAllowingStateLoss();
    }

    return mRetainFragment;
    //END_INCLUDE(find_create_retain_fragment)
}

/**
 * A simple non-UI Fragment that stores a single Object and is retained over configuration
 * changes. It will be used to retain the ImageCache object.
 */
public static class RetainFragment extends Fragment {
    private Object mObject;

    /**
     * Empty constructor as per the Fragment documentation
     */
    public RetainFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Make sure this Fragment is retained over a configuration change
        setRetainInstance(true);
    }

    /**
     * Store a single object in this Fragment.
     *
     * @param object The object to store
     */
    public void setObject(Object object) {
        mObject = object;
    }

    /**
     * Get the stored object.
     *
     * @return The stored object
     */
    public Object getObject() {
        return mObject;
    }
}

}
In the sample, the cache (LRUCache) is initialized with the following code from a fragment (ImageGridFragment):
ImageCache.ImageCacheParams cacheParams =
            new ImageCache.ImageCacheParams(getActivity(), IMAGE_CACHE_DIR);

    cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

    // The ImageFetcher takes care of loading images into our ImageView children asynchronously
    mImageFetcher = new ImageFetcher(getActivity(), mImageThumbSize);
    mImageFetcher.setLoadingImage(R.drawable.empty_photo);
    mImageFetcher.addImageCache(getActivity().getSupportFragmentManager(), cacheParams);// <-- here we inititialise cache by method ImageWorker with the fragment context in parameter ?

The methods of ImageWorker that initialize the cache in ImageCache with a fragment context:
/**
 * Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap
 * caching.
 * @param fragmentManager
 * @param cacheParams The cache parameters to use for the image cache.
 */
public void addImageCache(FragmentManager fragmentManager,
        ImageCache.ImageCacheParams cacheParams) {
    mImageCacheParams = cacheParams;
    mImageCache = ImageCache.getInstance(fragmentManager, mImageCacheParams);
    new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE);
}

/**
 * Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap
 * caching.
 * @param activity
 * @param diskCacheDirectoryName See
 * {@link ImageCache.ImageCacheParams#ImageCacheParams(android.content.Context, String)}.
 */
public void addImageCache(FragmentActivity activity, String diskCacheDirectoryName) {
    mImageCacheParams = new ImageCache.ImageCacheParams(activity, diskCacheDirectoryName);
    mImageCache = ImageCache.getInstance(activity.getSupportFragmentManager(), mImageCacheParams);
    new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE);
}

How to "instantiate" and initialize the cahe from an activity context with this class?
Thanks


text:
Q: Add OverlayView on ImageView in Android at particular X-Y Co-ordinate I have back side TouchImageview, which having zoom in/out functionality, I am setting up bitmap on ImageView, the size of Bitmap is w-h (2100 x 2900), I have particular X-Y co-ordinate, now I want to add Overlay view at same co-ordinate as per imageview's X-Y co-ordinate, the background imageview should be touchable.
Can you please let me know solution for the same.
Thank you.

A: I'm an iOS developer, but can be answer to your question, as I'm sure that these things are also possible in Android ! ;)
You can follow these steps:

*

*Don't make any change in your current flow.

*Add overlay view the way you want.

*Take screenshot of the back image view which are showing location, may be of particular size (or the exact size of circle on overlay).

*Show that captured screenshot (image) at circle view position (you can have an another image view for that).

*Zoom that image view (From Step.4)

*You are done!

Goodluck.


text:
Q: How to make an application in lotus notes with high availability? Updated:
I'm dealing with a scenario here in the company about high availability. I'm not that knowledgeable in server and stuffs but, our adviser said that we also need to see if a lotus notes application is capable or prepared for high availability. All I know about "high availability" is that it is a server setup to prevent interruption of tasks performed by users who uses the servers, so when Server A is down Server B will handle the load. So it's really unclear to me why we need to check if a lotus notes app is ready for "high availability" since setting up servers are the main concerns there. Thanks in advance.

A: keywords :

*

*Domino cluster

*local replica

With two or more Domino servers in a cluster, load balancing is automatic. If you nuke one server, the users will be redirected to another one without even noticing it.
Those clustered servers can of course be at different locations, and can also be hosted on different OS. If you have the monnies for a full monty, host one on Linux, one on zOS, one on AIX in three different locations and you've got yourself an uninterruptible Domino.
Local replica : a copy of the database resides on the user's workstation or laptop and is periodically and automatically updated when a connection to the server is available. The local replica can (and should!) be encrypted and carries along all the security mechanisms of Domino.
The local replica  contains only those documents the users would be allowed to see if connected to the server and can be futher trimmed down if need be.
This way, you can nuke each and every of your Domino servers, and users are still able to work. After a while, of course, you'll need a new Domino server so that the users can synchronise again whatever change they made.
Local replicas also mean that users can work offline and remotely, even if they have no connection to the local network.
Both options work out of the box. Clusters require a bit of workk to be set up by a competent admin. Local replica may require a little users education and some minimum involvment from the field techs.
Now, it is very rare for a well architectured and well maintained Domino server to go down.


text:
Q: on click input type date but var $(#date).value is empty <input type="date" class="form-control" id="date" name="date" required>

whin I click on type="date"  alert is showing.
How I get the date with I click on the date input.
<script>
$("#date").click(function () {
  var date = $('#date').val();
    if(date == ''){
       alert('Error; Date is empty');
        return;
    }
    $('#name').html('');
    $('#name').html('<option>Select Name</option>');
    $.ajax({
      type:'post',
      url: 'recording.php',
      data : { date : date},
      success : function(data){
         $('#name').html(data);
      }

    });
});
</script>

A: With your code, at the begining before you enter/choose date, you have to click on input field which will trigger alert that date is empty.
You should change your event to change instead of click, so when the change happens then check for date (change will happen on input lose focus or enter key inside of input):
Also after we get an event change, inside of it, we can use $(this) so we get the element that is currently changed in this case it is #date.
<script>
$("#date").on('change', function() {
  var date = $(this).val();
    if(date == ''){
       alert('Error; Date is empty');
        return;
    }
    $('#name').html('');
    $('#name').html('<option>Select Name</option>');
    $.ajax({
      type:'post',
      url: 'recording.php',
      data : { date : date},
      success : function(data){
         $('#name').html(data);
      }

    });
});
</script>


text:
Q: 'wall' object is not callable Уже часа 3 сижу и не понимаю что делать с этой ошибкой.
Ошибка:

Traceback (most recent call last):
  File "C:\Users\Matvey\Desktop\TUTA\besiege_client.py", line 137, in <module>
    walls = create(1, wx*50, wy*50)
  File "C:\Users\Matvey\Desktop\TUTA\besiege_client.py", line 90, in create
    walls.append(wall((x, y)))
TypeError: 'wall' object is not callable

Вот сам код:

import pygame
import socket
from threading import Thread

hst = input("IP БЫСТРА >:(")
HOST = hst
PORT = 1531
sock = socket.socket()
pygame.init()
class player():
    def __init__(self, pos, pl):
        self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
        self.pl = pl
    def keys(self):
        if self.pl == 1:
            key = pygame.key.get_pressed()
            if key[pygame.K_a]:
                self.move(-speed, 0)
            if key[pygame.K_d]:
                self.move(speed, 0)
            if key[pygame.K_w]:
                self.move(0, -speed)
            if key[pygame.K_s]:
                self.move(0, speed)
        if self.pl == 2:
            self.rect.x = player2_x
            self.rect.y = player2_y
    def move(self, dx, dy):
        if dx != 0:
            self.move_single_axis(dx, 0)
        if dy != 0:
            self.move_single_axis(0, dy)
    def move_single_axis(self, dx, dy):
        self.rect.x += dx
        self.rect.y += dy
        for wall in walls:
            if self.rect.colliderect(wall.rect):
                if dx > 0:
                    self.rect.right = wall.rect.left
                if dx < 0:
                    self.rect.left = wall.rect.right
                if dy > 0:
                    self.rect.bottom = wall.rect.top
                if dy < 0:
                    self.rect.top = wall.rect.bottom
    def draw(self, win):
        #win.blit(wall_texture, (self.rect.x, self.rect.y))
        pygame.draw.rect(win, (255,255,255), self.rect)
class wall(object):
    def __init__(self, pos):
        self.rect = pygame.Rect(pos[0], pos[1], 50, 50)
    def draw(self, win):
        #win.blit(wall_texture, (self.rect.x, self.rect.y))
        pygame.draw.rect(win, (159,159,159), self.rect)

#wall_texture = pygame.image.load('Wall.png')
clock = pygame.time.Clock()
run = True
speed = 3
#pygame.mixer.music.load('kus.mp3')
oo = pygame.image.load("oo.png")
level = [
"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"O                                     O",
"O                                     O",
"O                                     O",
"O                                     O",
"O                                     O",
"O                                     O",
"O         OO       O                  O",
"O                                     O",
"O         O                           O",
"O               O 2    1              O",
"O                                     O",
"O                                     O",
"O                                     O",
"O                                     O",
"O                                     O",
"O                  OO   OOO           O",
"O                  OO      O          O",
"O                        OO           O",
"O                  OO      O          O",
"O                  OO   OOO           O",
"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"]
def create(what, x, y):
    walls = []
    players = []
    if what == 1:
        walls.append(wall((x, y)))
        return walls
    if what == 0:
        xw = 0
        yw = 0
        for line in level:
            for col in line:
                if col == "1":
                    players.append(player((xw, yw), 1))
                elif col == "2":
                    players.append(player((xw, yw), 2))
                xw += 50
            yw += 50
            xw = 0
        return players
walls = create(1, 0, 0)
players = create(0, 0, 0)
speed = 3
delay_kus = 0
x_kus = 1770
sock.connect((HOST, PORT))
win = pygame.display.set_mode((1920, 1080))
pygame.display.set_caption("SigSaw")
while run:
    delay_kus += 1
    if delay_kus >= 1000:
        win.blit(oo, (x_kus, 1080/2))
        if delay_kus > 1500 and delay_kus < 1900:
            x_kus -= 1
        if delay_kus > 2200:
            x_kus -= 1
    for player in players:
        if player.pl == 1:
            p2x = player.rect.x
            p2y = player.rect.y
    senda = "{}-{}".format(p2x, p2y).encode()
    sock.send(senda)
    pl2 = sock.recv(1024).decode()
    pl2 = pl2.split("-")
    player2_x = int(pl2[0])
    player2_y = int(pl2[1])
    mx, my = pygame.mouse.get_pos()
    mclk = pygame.mouse.get_pressed()
    if mclk[0]:
        wx, wy = mx//50, my//50
        walls = create(1, wx*50, wy*50)
    for player in players:
        player.keys()
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
        if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
            pygame.quit()
    for wall in walls:
        wall.draw(win)
    for player in players:
        player.draw(win)
    clock.tick(60)
    pygame.display.flip()
    win.fill((10, 150, 10))

Был бы очень благодарен, если кто-нибудь поможет.


text:
Q: connect Internet via Terminal linux I want to write a script-Ubuntu_OS- would connect to a wireless Internet so I need to know how to connect Internet via terminal in Linux.
I tried many suggestions on the Internet but nothing at all

A: By your question i assume you want a script to connect to a wi-fi network using a linux script and access internet.
Scan all networks available
iwlist wlan0 scan
      Cell 14 - Address: 80:A1:D7:7A:5E:68   <<AP
                Channel:6
                Frequency:2.437 GHz (Channel 6)
                Quality=26/70  Signal level=-84 dBm
                Encryption key:on
                ESSID:"ra"
                Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s
                Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s
                          36 Mb/s; 48 Mb/s; 54 Mb/s
                Mode:Master
                Extra:tsf=000000003621716c
                Extra: Last beacon: 1260ms ago
                IE: Unknown: 000472686561
                IE: Unknown: 010482848B96
                IE: Unknown: 030106
                IE: WPA Version 1
                    Group Cipher : TKIP
                    Pairwise Ciphers (1) : TKIP
                    Authentication Suites (1) : PSK
                IE: Unknown: 050400010000
                IE: Unknown: 2A0104
                IE: Unknown: 32080C1218243048606C

From the list select essid of wi-fi netwwork you want to connect
iwconfig wlan0 essid ID key KEY

if ESSID is "" use access-point
iwconfig wlan0 ap AP key KEY

script
#!/bin/bash
ifconfig wlan0
iwconfig wlan0 ap AP key KEY
dhclient wlan0

A: You could try using WICD network manager, it has a CLI network manager you can install.
You could also try using the Ceni script from smxi, which has worked great for me in a few cases where WICD and Gnome-network-manager were not working.
These won't really be a script to start a network connection, but both are accessible from command line and both will let you scan for networks, connect, put in keys, etc. in a nice manner.


text:
Q: How to perform Pandas outer merge while completely excluding duplicated entry? Let's say I want to outer merge 2 sets of items (data frames) with different sizes that do not have unique enough keys.
Set 1:

*

*Index: 1, 2, 3, 4, 5

*Key: A, A, B, C, A

*Items: Orange, Banana, Pancake, Cookie, Oreo

Set 2:

*

*Index: 1, 2, 3, 4

*Key: B, C, A, Z

*Items: Out-of-stock, In-stock, Back-order, Out-of-stock

Desired result (outer merge, index order is irrelevant):

*

*Row 1: Out-of-stock, B, Pancake

*Row 2: In-stock, C, Cookie

*Row 3: Back-order, A, Orange

Unmatched (right_only):

*

*Key: A, A

*Items: Banana, Oreo

Unmatched (left_only):

*

*Key: Z

*Items: Out-of-stock

Note: The unmatched rows will be used for further merges. This is an elimination process. Later merge relaxes conditions, but at the cost of reducing accuracy.

The problem:
If I use outer merge, Pandas will find every possible combination and create duplicates (all key-A items become back-order, but I only need one, whatever that is).
If I drop a duplicate, the drop is performed after the merge, so I lost the duplicated records and they cannot be used in later merges. Technically, I can dissect the dropped records and re-add them to the data frame from an outer merge, but the performance and code logic become horrible at scale (10k+ rows, 20+ columns).
I can only use keys, not indexes as records do not follow any particular order.
For this question, the brute-force solution is essentially having 2 sets of items. Then, use a nested loop to iterate both sets, find one match, then remove the match from 2 sets to avoid duplication in the next iteration. This solution has O(N^2) runtime and is a no-go (takes 20+ hours to run).
With that said, how should I approach this issue? Any suggestion is appreciated.

A: Create a temporary  column with groupby.cumcount in both dataframe to use as a merge column additional to key. Use indicator=True to create a column to select the three parts (both, only right, only left) later.
res = (
    df1.assign(cc=lambda x: x.groupby('key').cumcount())
       .merge(df2.assign(cc=lambda x: x.groupby('key').cumcount()),
              on=['key','cc'], how='outer', indicator=True)
)
print(res)
#   key  Items_x  cc       Items_y      _merge
# 0   A   Orange   0    Back-order        both
# 1   A   Banana   1           NaN   left_only
# 2   B  Pancake   0  Out-of-stock        both
# 3   C   Cookie   0      In-stock        both
# 4   A     Oreo   2           NaN   left_only
# 5   Z      NaN   0  Out-of-stock  right_only

Then you can select using the _merge column depending on your case, for example
print(res.loc[res['_merge'].eq('both')].drop(['cc','_merge'], axis=1))
#   key  Items_x       Items_y
# 0   A   Orange    Back-order
# 2   B  Pancake  Out-of-stock
# 3   C   Cookie      In-stock


text:
Q: How to know which line the app crashed? I'm debugging an app in a real device and Eclipse. Certain feature makes it crash. There is no error on LogCat. I've managed to find which line it crashed in a similar situation by writting Log.v in many lines until I found which Log.v didn't show up. Isn't there a better solution?

A: You could use the Debugging feature in Eclipse - it allows you to break the program flow on the occurrence of an exception (Run As -> Debug).
This will allow you to inspect the current local variables / call stack to further diagnose why the exception occurs.
p.s. One other method I use when hunting down an odd crash is to dump the full LogCat via the 'adb' CLI tool, and inspect it in a text editor. Sometimes the LogCat display in Eclipse can go a bit.. weird..especially if you've been connecting / disconnecting your device while developing (without closing Eclipse)

A: Check Logcat filters (in Eclipse). Happens to me.

A: I was using the 'debug' option on Eclipse, which made it not show the error. Detaching the debug after the crash, or just running the application from the begin (without the debug options) shows the error. To find the line, filter your LogCat by application, make the app crash and, on the red text that will appear, look for your package name. And the of the error (expection) itself is on the beginning of that text.


text:
Q: Beginner Node.JS net.createServer example I am an old PERL coder trying to learn node.JS programming.  I have question about the code I am writing to create a socket connection between a server and a client app.
The code below works.  But I do not know how to accept data sent from the client to the server.
Basically what I want to do is very simple.  Client connects to a Server listening on a socket, sends some information, which the Server reads and then sends information back to the Client.  The only part I am not understanding is how to get the Server side to read/accept/display the data string sent from the Client.
Can someone please point me in the right direction?
Thank you for your help in advance.
(My apologies for being ignorant.)
Here is the server side code:
var net = require('net');
var server = net.createServer(function(socket) {
    // confirm socket connection from client
    console.log((new Date())+'A client connected to server...');
    socket.on('data', function(data) {
        var json = JSON.parse(data.toString());
        console.log(json)
    });
    // send info to client
    socket.write('Echo from server: NODE.JS Server \r\n');
    socket.pipe(socket);
    socket.end();
    console.log('The client has disconnected...\n');
}).listen(10337, '192.168.100.1');

Here is the client code:
var net = require('net');

var client = new net.Socket();
client.connect(10337, '192.168.100.1', function() {
console.log('Connected');  // acknowledge socket connection
client.write('Hello, server! Love, Client.'); // send info to Server
});

client.on('data', function(data) {
console.log('Received: ' + data); // display info received from server
client.destroy(); // kill client after server's response
});

client.on('close', function() {
console.log('Connection closed');
});

I get an error on the server when I do this where it says the string sent from the client is an invalid token.  here is the error message.
undefined:1

Hello, server! Love, Client.
^
SyntaxError: Unexpected token H
at Object.parse (native)
at Socket.<anonymous> (/root/nodejs/server-example.js:7:19)
at Socket.emit (events.js:117:20)
at Socket.<anonymous> (_stream_readable.js:765:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:427:10)
at emitReadable (_stream_readable.js:423:5)
at readableAddChunk (_stream_readable.js:166:9)
at Socket.Readable.push (_stream_readable.js:128:10)
at TCP.onread (net.js:529:21)

A: I was being stupid.  I found the answer I was looking for.  And it was very simple.
Here is what I should have written in place of the JSON statements
    socket.on('data', function(data) {
            var string = (data.toString());
            console.log(string)
    });

A: or handle both JSON and Strings that get written to the socket:
socket.on('data', function(data) {
    try {
       var obj = JSON.parse(data.toString())
       console.log(JSON.stringify(obj, null, 4))
    }
    catch(e) {
       var string = data.toString()
       console.log(string)
    }
})


text:
Q: Update single record in mongodb using express and node.js I want to update a single record by _id in a collection in mongoDB.
UPDATE:  I changed the res to req (thanks!) and implemented the db.ObjectId() around the objectId I am passing in and now I get a 500 internal server error.
    "_id" : ObjectId("54d5296711436278137af74b"),
    "username" : "alex",
    "email" : "alex@gmail",
    "fullname" : "alex man",
    "age" : "15",
    "location" : "minneap",
    "gender" : "mal"

This is my ajax call from the client.
    $.ajax({
                    type: 'PUT',
                    data: updatedUser,
                    url: '/users/updateuser/' + globalUserID,
                    dataType: 'JSON'
                }).done(function(response){

This is the routing code.
/*
* PUT to updateuser
*/
router.put('/updateuser/:id', function(req, res) {
var db = req.db;
var userToUpdate = req.params.id;
db.collection('userlist').update(
{ _id: userToUpdate},
   req.body,
    function(err, result){
    res.send(
        (err === null) ? {msg: ''} : {msg: err}
    );
   });
});

I get a 200 response back but my record is not updated. What is wrong with my syntax?

A: You need to make sure you're turning the string _id into an ObjectId.
Also, you were using res.body instead of req.body.
router.put('/updateuser/:id', function(req, res) {
    var db = req.db;
    var userToUpdate = req.params.id;
    db.collection('userlist').update({ _id: ObjectId(userToUpdate)}, req.body, function (err, result) {
        res.send(
            (err === null) ? {msg: ''} : {msg: err}
        );
    });
});

Different drivers use a different method to create an ObjectId:

*

*mongoDB native driver: new ObjectId(idString);

*mongoJS: db.ObjectId(idString);

*mongoSkin: toObjectID(idString);

*mongoose: mongoose.Types.ObjectId(idString);

A: It should be req.body, not res.body
db.collection('userlist').update(
{ _id: userToUpdate},
   res.body -> should be req.body


text:
Q: imagecreatefromstring - catch fail - PHP I'm trying to detect if an image is an image when given a URL. To save an image from a url I used the following:
// create the image and save it
$imagefile = $URL;
$resource = imagecreatefromstring(file_get_contents($imagefile));
// X amount of quality is the last number
imagejpeg($resource, "images/covers/$imagepath.jpeg", 50);
imagedestroy($resource);

The $URL is simply an image link provided by the user.
I have tried the following:
$imagefile = $addBuildCover;
$resource = imagecreatefromstring(file_get_contents($imagefile));

if ($resource !== false) {
  $return['imageGood'] = true;
} else {
  $return['imageBad'] = true;
}

I have tried that code and i returns the correct JSON return of 'imageBad' but it's giving me an error before which is:
Warning: file_get_contents(ewffw.png): failed to open stream: No such file or directory in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116

Warning: imagecreatefromstring(): Empty string or invalid image in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116

How do I try I catch the URL fail but not actually have an error return like above?

A: imagecreatefromstring will unfortunately warn if you pass it invalid data, so using it unnecessarily problematic.
You will have to shut it up with the error suppression operator @:
$resource = @imagecreatefromstring(file_get_contents($imagefile));

Using this operator is something usually frowned upon, but this case is one which you really do have a legitimate use case.
This approach will also take care of the warning given from file_get_contents if the file cannot be loaded. That function is not as badly behaved (there are ways to check with reasonable certainty if it will fail or not, e.g. is_readable) so you could check with code instead of using @, but since you need to suppress errors anyway and it makes no difference to you if the file read failed or not, just slapping a @ in front is IMHO fully warranted here.

A: <?php
    $serverName = "server";

    $uid = "user";
    $pwd = "pass";
    $connectionInfo = array( "UID"=>$uid,
                             "PWD"=>$pwd,
                             "Database"=>"database");

    $conn = sqlsrv_connect( $serverName, $connectionInfo);
    if( $conn === false )
    {
         echo "Unable to connect.
";
         die( print_r( sqlsrv_errors(), true));
    }

    $fotoquery = "SELECT column_image FROM Table WHERE Column = 'xxxxxxxxxx'";

    $stmt = sqlsrv_query( $conn, $fotoquery);

    if( $stmt === false )
    {
       echo "Error in executing query.
";
       die( print_r( sqlsrv_errors(), true));
    }

    $dataImage = sqlsrv_fetch_array($stmt);
    $varimg = base64_encode($dataImage[0]);

    $data = base64_decode($varimg);

    $im = imagecreatefromstring($data);
    if ($im !== false) {
        header('Content-Type: image/png');
        imagepng($im);
        imagedestroy($im);
    }
    else {
        echo 'An error occurred.';
    }
?>


text:
Q: How to identify the most suitable Design Pattern for a scenario I want to implement a GUI based drawing program. It should be able to draw circles,triangles and squares. And it should be able to expand the number of shapes in the system in future.
The program will give certain 'abilities' to these shapes, such as the ability to 'move', 'expand' ,
'rotate' and of course 'draw' (to get the shape drawn in the GUI). Each of these methods needs a
'Graphics Context' passed in as as a parameter, in order to get them drawn.
I want use a design pattern for this program and since there will be methods differ from shape to shape I think strategy pattern will be useful.
I want to know the way which I have used this pattern is okay.
interface Shape{}

interface Behavioral{
public void move(Graphics g){}
public void expand(Graphics g){}
public void draw(Graphics g){}
}

(There is an aggregation between shape and behavioral)

interface Rotatable{
public void rotate(Graphics g)
}

interface RotatableToLeft extends Rotatable(){
public void rotate(Graphics g)
}

interface RotatableToRight extends Rotatable(){
public void rotate(Graphics g)
}

class circle implements Shape{
public void move(Shape g){--}
public void expand(Shape g){--}
public void draw(Shape g){--}

}

class Square implements Shape implements Rotatable{
public void move(Shape g){--}
public void expand(Shape g){--}
public void draw(Shape g){--}
public void rotatefree(RotatableToLeft g){--}
}

class Triangle implements Shape implements Rotatable{
public void move(Graphics g){--}
public void expand(Graphics g){--}
public void draw(Graphics g){--}
public void rotateLeft(RotatableToLeft g){--}
public void rotateRight(RotatableToRight g){--}

}

A: Shape should probably be a common abstract base class, not an interface, and at the very least, draw() should be a member of Shape.  And since every shape is probably to implement all other methods of Behavioral, you can get rid of Behavioral and move all of its methods to Shape.
RotatableToLeft and RotatableToRight do not make any sense.  Use only one interface, containing only one method, and pass the direction to rotate.
You will probably need a few 'tryAs' and 'is' and 'as' methods.  For example:
class Shape
{
    public Rotatable tryAsRotatable() { return null; }

    public final boolean isRotatable()
    {
        return tryAsRotatable() != null;
    }

    public final Rotatable asRotatable()
    {
        Rotatable result = tryAsRotatable();
        assert result != null;
        return result;
    }
}

class Circle extends Shape implements Rotatable
{
    @Override
    public Circle tryAsRotatable() { return this; }
}


text:
Q: Clarification of the meaning and functionality of private and public in java I have seen this question and I understand what theoretically the difference between public and private means. My understanding is as follows:

public means that it's "visible" / "accessible" everywhere. As in every class can see it.
  private is only "visible" / "accessible" in its declared class.

My first question is:
What does "visible" exactly mean? I'm not quite sure how to interpret the meaning of "this class can't "see" this method".
Second question is:
What is the functionality/use of these? In the second asnwer of the question, he explains that if we "encapsulate" our code, then we will make it "easier for ourselves to change the code later and not break anybody's else's code". What does this exactly mean?
Examples would help a lot

A: With respect to the first question: What does "visible" exactly mean?
visibility translates to accessibility when talking of classes, whenever a class is declared public, that class is accessible to all the other classes of the project, and all the classes can access them as they like either by inheriting the class or instantiating a new object of the class. Similar concepts also transcend to public class members. However, one important point is that public class members such as methods and variables will only be visible/accessible to other classes if the containing class is not marked as private.
On the other hand, when the class is marked as private, it is hidden from all the classes in the codebase, you can think that the rest of the code won't even know that, that class exists.
Members of a private class are only accessible within the class and are hidden from the outside world.
A private member will remain inaccessible for the outside world even if its class is marked as public.
Now, for the second question: What is the functionality/use of these?
Access modifiers are especially useful when you want to restrict as to what part of your class should be accessible from outside and what part should not be accessible.
For example, in general, it is a good idea to make class variables as private and then expose functions that will allow you to fetch those variables, the major benefit you get with this approach is that at any point of time in future, you can change how those variables are calculated and the changes would propagate to all the classes without having the need to change them, had the classes directly accessed the variable, it would have been very difficult to make the change without impacting other classes. This is just one example demonstrating how useful access modifiers can prove to be even for the simplest of things.
Hope this gives you a brief idea.


text:
Q: iPhone crash during layer animation after being in background I'm having trouble fixing a pesky crash. I can't figure out how to accurately reproduce it,
but it only occurs after the app comes out of the background. I get this crash every 2+ days.
In applicationDidBecomeActive:, I restart a timer that fires every 0.4 seconds. It calls:
- (void)rotate {

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    self.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(-[LocationModel    instance].heading.magneticHeading));
    [UIView commitAnimations];

}

Also in RotateView, is the drawRect, whose body is at line 41 as seen in the crash report.
- (void)drawRect:(CGRect)rect {

    [img drawInRect:rect]; // line 41
}

img is a small UIImage loaded with imageNamed: and stored in an ivar.
Any advice? I have little experience with crash reports.
Thanks!

Crash report:
Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x3001b482
Crashed Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libobjc.A.dylib                   0x333a6c98 objc_msgSend + 16
1   MyApp                           0x000259bc -[RotateView drawRect:] (RotateView.m:41)
2   UIKit                             0x34f4a9fe -[UIView(CALayerDelegate) drawLayer:inContext:] + 258
3   QuartzCore                        0x3058efa6 -[CALayer drawInContext:] + 86
4   QuartzCore                        0x3058ed24 _ZL16backing_callbackP9CGContextPv + 32
5   QuartzCore                        0x3058e776 CABackingStoreUpdate + 1226
6   QuartzCore                        0x3058e178 -[CALayer _display] + 724
7   QuartzCore                        0x3058de86 -[CALayer display] + 134
8   QuartzCore                        0x30582706 CALayerDisplayIfNeeded + 178
9   QuartzCore                        0x305821c6 CA::Context::commit_transaction(CA::Transaction*) + 214
10  QuartzCore                        0x30581fd0 CA::Transaction::commit() + 184
11  QuartzCore                        0x30580900 CA::Transaction::pop() + 120
12  QuartzCore                        0x3058087e +[CATransaction commit] + 22
13  UIKit                             0x35096bcc _UIWindowUpdateVisibleContextOrder + 136
14  UIKit                             0x35096c60 +[UIWindow _prepareWindowsForAppResume] + 4
15  UIKit                             0x3508f3de -[UIApplication _handleApplicationResumeEvent:] + 66
16  UIKit                             0x34f39e20 -[UIApplication handleEvent:withNewEvent:] + 2724
17  UIKit                             0x34f3920e -[UIApplication sendEvent:] + 38
18  UIKit                             0x34f38c4c _UIApplicationHandleEvent + 5084
19  GraphicsServices                  0x35873e70 PurpleEventCallback + 660
20  GraphicsServices                  0x35873efa PurpleEventSignalCallback + 10
21  CoreFoundation                    0x36126a72 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 6
22  CoreFoundation                    0x36128758 __CFRunLoopDoSources0 + 376
23  CoreFoundation                    0x361294e4 __CFRunLoopRun + 224
24  CoreFoundation                    0x360b9ebc CFRunLoopRunSpecific + 224
25  CoreFoundation                    0x360b9dc4 CFRunLoopRunInMode + 52
26  GraphicsServices                  0x35873418 GSEventRunModal + 108
27  GraphicsServices                  0x358734c4 GSEventRun + 56
28  UIKit                             0x34f63d62 -[UIApplication _run] + 398
29  UIKit                             0x34f61800 UIApplicationMain + 664
30  MyApp                           0x000026c4 main (main.m:14)
31  MyApp                           0x0000266c start + 32

A: EXC_BAD_ACCESS generally means you released an object then called that object later.  Try enabling NSZombies to find it.  There are numerous tutorials on how to do it.  Here's one  to start http://www.touch-code-magazine.com/how-to-debug-exc_bad_access/


text:
Q: How do I see who's attending a feast? Feasts will often have events which give you choices which will either increase or decrease the opinion of every guest. That's all fine and dandy, but it be great if I could know exactly who's at the feast when I'm presented with these decisions, since there's some folks whose opinion is already so high that I don't really care about taking a small opinion penalty.
How can I see who the guests are at a feast?

A: This is super unintuitive, but when you host a feast, a little tiny feast icon generates on the map when you're zoomed in close enough. I think it's always in your capital when you host it, but if you get invited to a vassal's feast, it'll be in their capital instead.
When you click it, you get a nifty little pop-up with a list of all the persons attending!

Hunts and pilgrimages also generate a tiny location-specific icon, but I don't think those expand out to show who's with you. (This may be a bug)


text:
Q: Why is my Lambda unable to access the internet? I have a Lambda function which can be triggered from an API gateway or ALB request. I also have an RDS Aurora PostgreSQL instance, both of which are running within a VPC.
I'm able to connect to the RDS instance from the Lambda just fine, however I can't access the internet, e.g. attempting to fire off a request to https://jsonplaceholder.typicode.com/todos/1 will cause a timeout.
I also can't connect to the remote database using a SQL client such as DBeaver.
Here's some detail below but let me know if you need anything else. I'm stumped.
Lambda Inbound Rules
Security group ID       Ports   Source
sg-0f2c4426c8fc85235    80      0.0.0.0/0
sg-0f2c4426c8fc85235    5432    0.0.0.0/0
sg-0f2c4426c8fc85235    All     sg-0f2c4426c8fc85235
sg-0f2c4426c8fc85235    22      0.0.0.0/0
sg-0f2c4426c8fc85235    443     0.0.0.0/0

Lambda Outbound Rules
Security group ID       Ports   Destination
sg-0f2c4426c8fc85235    All     0.0.0.0/0

RDS Connectivity

VPC

Public Subnet

Private Subnet

EDITS
Nat Gateway (associated with public subnet)

Route Tables

Route Table Routes

EDIT 2
Lambda Subnets

A: The Lambda function should only be connected to a private subnet.
This enables Internet-bound traffic to be routed to the NAT Gateway in the public subnet.
If the Lambda function connects to the public subnet, it will be unable to reach the Internet.

A: A mixture of two things I think. 1, as was pointed out, the Lambda should only be connected to private subnets.
I think I'd also mixed up the availability zones between the public and private subnets?
Anyway, the Lambda is now successfully connecting to RDS, hitting external APIs and I can also connect through DBeaver.
Thanks a lot.


text:
Q: out of order write a file python I have multiple segments saved in an input file. The format is;
  Use case 1:

  host        port    start_byte     end_byte
 127.0.0.1   12345   0              2048
 127.0.0.1   12346   0              1024
 127.0.0.1   12347   1024           2048

 Use case 2:

 host        port    start_byte     end_byte
 127.0.0.1   12345   0              2048
 127.0.0.1   12346   1024           2048
 127.0.0.1   12347   0              1024

Here, the first line is for the reference to understand what each line has.
The host is the localhost but ports are different.
Here we have 3 ports. Port #12345 has entire file (say abc.txt). Port #12347 has
the second segment whereas the port #12346 has the first segment.
Now, I want to read file from the end of file towards the start of file(from line 3 to 1).
The code to download each segment and write to a new file is given below.
 def downloadSegment(threadName, fileNameTemp, server_addr, server_port, segment_beginaddr, segment_endaddr, fileName, maxSegmentSize,ip_address,peer_server_port, relevant_path):

      downloadSegmentStr = "download," + fileName + ","+segment_beginaddr+"," + segment_endaddr
      socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      socket1.connect((server_addr, int(server_port)))
      socket1.send(downloadSegmentStr)

      lock.acquire()
      with open(fileNameTemp, 'ab') as file_to_write:
          file_to_write.seek(int(segment_beginaddr),0)
          while True:
          data = socket1.recv(maxSegmentSize)
          #print data
          if not data:
            break

          #print data
          file_to_write.write(data)
     file_to_write.close()
     lock.release();
     socket1.close()

When I write the segment in increasing order (Use case 1), then, it works perfectly. But, when I try using the out of order like explained in above Use case 2, it doesn't work.
Any help is appreciated. Thanks.

A: You missed these parts of the Python Documentation:

open(name[, mode[, buffering]])
… 'a' for appending (which on some Unix systems means that all
  writes append to the end of the file regardless of the current seek
  position).
file.seek(offset[, whence])
… Note that if the file is opened for appending (mode 'a' or 'a+'),
  any seek() operations will be undone at the next write. If the file is
  only opened for writing in append mode (mode 'a'), this method is
  essentially a no-op…

Thus, mode 'a' is unsuitable for the task. Sadly, stdio's fopen() offers no mode without a that creates a file if it doesn't exist and doesn't truncate it if it exists. So I'd use os.open() like in:
    with os.fdopen(os.open(fileNameTemp, os.O_CREAT|os.O_WRONLY), 'wb') as file_to_write:


text:
Q: What are the roles of celery-worker, celery-beat, message-broker? Most tutorials on the celery/redis/rabitmq/etc are about the setup not the concept.
I'll describe what I know below, please fix me if I'm wrong or let me know a good tutorial page on the issue.
-> event happen (user did something and web server knows)
-> message goes to the message broker (redis/rabitmq)
-> message broker gives message to celery-worker for him to work
-> if he fails, he reports back to the broker, and broker deals with it

-> (periodic task) celery-beat says it's time to work
-> celery-beat gives the work to celery-worker (or through message broker?)
-> same as above


text:
Q: Eccentricity of an ellipse.with b > a I have the following ellipse : $\frac{(x-3)^2}{\frac{9}{4}} + \frac{(y+4)^2}{\frac{25}{4}}=1$
In this case, b > a. It says that to find the eccentricity I must use $\frac{c}{a}$ but I think this is only valid when a>b. What'S the formula to find the eccentricity in my case ?

A: The formula for eccentricity is always (distance between foci)/(length of major axis).

A: In this case, $a=\frac 52$ and the major semi-axis is parallel to the $y$ axis, so the eccentricity is still $$e=\sqrt{1-\frac{b^2}{a^2}}=\sqrt{1-\frac {9}{25}}=\frac 45$$


text:
Q: Unable to set default value for Picker in Xamarin forms I am using to Picker in my project. I am successfully able to display the All items in the Picker without an issue but for update functionality, I am not able to display the Default Item for Picker,
I have used SelectedItem and SelectedIndex but nothing worked in my case.
Can someone explain how that SelectedItem and SelectedIndex works,
My code:
<Picker Title="Select Gender" Margin="0,0,0,-5" ItemsSource="{Binding GenderList}"  x:Name="pkrGender" ItemDisplayBinding="{Binding Name}" >

In view Model:
public class MainViewModel : BaseViewModel
{
 // Which is bind to ItemSource of the picker
 public ObservableCollection<Gender> GenderList { get; set; }

 public class Gender: BaseViewModel {
  private Genders _gender {
   get;
   set;
  }

  public Gender(Genders gender) {
   this._gender = gender;
  }

  public string Name {
   get {
    return _gender.name;
   }

   set {
    _gender.name = value;
    OnPropertyChanged("Name");
   }
  }

 }
 public void APICALL()
 {
   // Getting values from API
 }

}

And Genders Class:
public class Genders
{
   public string Name {get;set;}
   public string Code {get;set;}
}

And I am Adding the values in ViewModel like:
// From API Response Getting the list of Genders
var genderList = APICALL();
foreach (Genders gender in genderList)
{
    GendersList.Add(new Genders(gender));
}

But not able to bind the default value In my case he selected the Male while registration so the Male should be the Default value for the picker.

A: Fundamentally, I think you're missing the OnPropertyChanged method in the GenderList property. As a result, your Picker is bound to an empty list.
I found the following worked for me:
private List<Genders> listOfGenders = new List<Genders>();

public List<Genders> GenderList
{
    get => listOfGenders;
    set
    {
        listOfGenders = value;
        OnPropertyChanged(nameof(GenderList));
    }
}

private void AddToGenderList(params Gender[] genders)
{
    if (listOfGenders == null)
    {
        listOfGenders = new List<Genders>();
    }

    foreach(Gender gender in genders)
    {
        listOfGenders.Add(gender);
    }

    GendersList = listOfGenders;
}

How do the SelectedItem and SelectedIndex work?
SelectedItem returns the selected object from the list associated to the Picker. In your case, it will return the Gender object that you selected.
SelectedIndex returns the index of the item you selected in the list.
Assigning a default value
To assign a default value, first make sure that the list is not empty. For example, the code below (expanding from the code above) should work:
(In your C#)

private int currentSelectedIndex = 0;

public int CurrentSelectedIndex
{
    get => currentSelectedIndex;
    set
    {
        currentSelectedIndex = value;
        OnPropertyChanged(nameof(CurrentSelectedIndex));
    }
}

public MainViewModel()
{
    AddToGenderList(new Gender[]
    {
        new Gender
        {
            Name = "Male",
            Code = "M"
        },
        new Gender
        {
            Name = "Female",
            Code = "F"
        },
        new Gender
        {
            Name = "Other",
            Code = "O"
        }
        // Add more if necessary
    });

    // Set the default to "Male"
    CurrentSelectedIndex = 0;
}

(In your XAML)
<Picker
    Title="Select Gender"
    Margin="0,0,0,-5"
    ItemsSource="{Binding GenderList}"
    SelectedIndex="{Binding CurrentSelectedIndex}"
    x:Name="pkrGender"
    ItemDisplayBinding="{Binding Name}" />


text:
Q: Google Map w/ KML won't obey zoom setting; Instead zooms out to fit all markers Using Google Maps Javascript API V3, I have setup a map to pull data from a dynamically generated KML file. Here is the result:
http://theevolvement.org/MapRetailers.php
In my code (copied below), I specified the zoom to 12 in my map's options. When the page loads, it starts out at that assigned zoom, but within about one second the map zooms out (and shifts its assigned center) to fit all of the plotted points.
We want to load the map with a specified zoom, not include all the plotted data. So any advice anyone can give as to what I'm doing wrong would be greatly appreciated. Thank you all!
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />

A: WOO! I finally figured out the solution!
The KmlLayer function required another parameter, {preserveViewport: true}
  var ctaLayer = new google.maps.KmlLayer('<?=$kmlURL?>', {preserveViewport: true});


text:
Q: Looking for Kernel Header file for Macros of INTEL ethernet device related macros for base addresses of registers used in I/O where is the header file in Linux headers of addresses macros of PCI register's (address as in Memory IO Mapping of devices) for VendorID, DeviceID,CLASS and BASE addresses MACROs (for IO as ins(address) outb(..address)) for intel e1000e device in Debian Linux

A: Each network card is under drivers/net/ethernet/intel.  The E1000 cards, for example, list all the different  model ids in https://elixir.bootlin.com/linux/v4.10.17/source/drivers/net/ethernet/intel/e1000/e1000_hw.h#L409  The vendor ID for Intel is 8086.
PCI addresses are assigned, they are not fixed.


text:
Q: JavaScript form validation with a shake effect I have some JavaScript form validation I'm using before I send it across to my PHP. (I'm still learning). but my question for you today is how I would get my error message to shake without reloading the page. My below JS code seems to reload the page when I click submit. The error message style is set to disply:none; by default and only shows when needed.
I hope you understand what I am getting at. ha ha Thank you in advance.
Here's the js code.
function validateLoginForm() {
    var x = document.getElementById('email').value;
    if (x == null || x == "" || x == "Email") {
        document.getElementById('errorWrapper').style.display='block';
        document.getElementById('errorText').innerHTML='Please enter your Email address!';
        shakeIt();
        return false;
    }
}

and the jQuery.
$(document).ready(function() {
    function shakeIt(){
        $('#errorWrapper').effect("shake", { times:5, distance:8 }, 50);
    }
});

A: You need to do it on form.submit ie
$('#loginForm').submit(function(e){
var x= $('#email').val();
      if (x==null || x=="" || x=="Email")
      {
      $('#errorWrapper').show();
      $('#errorText').text('Please enter your Email address!');
      e.preventDefault();
      shakeIt();
      }
      return true;
});

Returning false will make the page not reload..