text:
Q: Windows DACL permissions I am trying to modify permissions using Windows permissions API.
I have a standalone use case code as below, I first revoke all the access and then grant read and write ones.
#include <fstream>
#include <iostream>
#include <aclapi.h>
#include <windows.h>
#include <string>
using namespace std;
#include <memory>

bool CanAccessFolder(LPCTSTR folderName, DWORD genericAccessRights,DWORD& grantedRights)
{
    bool bRet = false;
    DWORD length = 0;
    if (!::GetFileSecurity(folderName, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION
        | DACL_SECURITY_INFORMATION, NULL, NULL, &length) &&
        ERROR_INSUFFICIENT_BUFFER == ::GetLastError()) {
        PSECURITY_DESCRIPTOR security = static_cast< PSECURITY_DESCRIPTOR >(::malloc(length));
        if (security && ::GetFileSecurity(folderName, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION
            | DACL_SECURITY_INFORMATION, security, length, &length)) {
            HANDLE hToken = NULL;
            if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_IMPERSONATE | TOKEN_QUERY |
                TOKEN_DUPLICATE | STANDARD_RIGHTS_READ, &hToken)) {
                HANDLE hImpersonatedToken = NULL;
                if (::DuplicateToken(hToken, SecurityImpersonation, &hImpersonatedToken)) {
                    GENERIC_MAPPING mapping = { 0xFFFFFFFF };
                    PRIVILEGE_SET privileges = { 0 };
                    DWORD grantedAccess = 0, privilegesLength = sizeof(privileges);
                    BOOL result = FALSE;

                    mapping.GenericRead = FILE_GENERIC_READ;
                    mapping.GenericWrite = FILE_GENERIC_WRITE;
                    mapping.GenericExecute = FILE_GENERIC_EXECUTE;
                    mapping.GenericAll = FILE_ALL_ACCESS;

                    ::MapGenericMask(&genericAccessRights, &mapping);
                    if (::AccessCheck(security, hImpersonatedToken, genericAccessRights,
                        &mapping, &privileges, &privilegesLength, &grantedAccess, &result))
                    {
                        bRet = (result == TRUE);
                        grantedRights = grantedAccess;
                    }
                    ::CloseHandle(hImpersonatedToken);
                }
                ::CloseHandle(hToken);
            }
            ::free(security);
        }
    }

    return bRet;
}
 void printMasks(DWORD Mask)
 {
     // This evaluation of the ACCESS_MASK is an example.
     // Applications should evaluate the ACCESS_MASK as necessary.
    std::wcout << "Effective Allowed Access Mask :  "<< Mask << std::hex << std::endl;
     if (((Mask & GENERIC_ALL) == GENERIC_ALL)
         || ((Mask & FILE_ALL_ACCESS) == FILE_ALL_ACCESS))
     {
         wprintf_s(L"Full Control\n");
         //return;
     }
     if (((Mask & GENERIC_READ) == GENERIC_READ)
         || ((Mask & FILE_GENERIC_READ) == FILE_GENERIC_READ))
         wprintf_s(L"Read\n");
     if (((Mask & GENERIC_WRITE) == GENERIC_WRITE)
         || ((Mask & FILE_GENERIC_WRITE) == FILE_GENERIC_WRITE))
         wprintf_s(L"Write\n");
     if (((Mask & GENERIC_EXECUTE) == GENERIC_EXECUTE)
         || ((Mask & FILE_GENERIC_EXECUTE) == FILE_GENERIC_EXECUTE))
         wprintf_s(L"Execute\n");
 }

 DWORD AddAceToObjectsSecurityDescriptor(
     LPTSTR pszObjName,          // name of object
     SE_OBJECT_TYPE ObjectType,  // type of object
     DWORD dwAccessRights,       // access mask for new ACE
     ACCESS_MODE AccessMode,     // type of ACE
     DWORD dwInheritance         // inheritance flags for new ACE
 )
 {
     DWORD dwRes = 0;
     PACL pOldDACL = NULL, pNewDACL = NULL;
     PSECURITY_DESCRIPTOR pSD = NULL;
     EXPLICIT_ACCESS ea;

     if (NULL == pszObjName)
         return ERROR_INVALID_PARAMETER;

     // Get a pointer to the existing DACL.

     dwRes = GetNamedSecurityInfo(pszObjName, ObjectType,
         DACL_SECURITY_INFORMATION,
         NULL, NULL, &pOldDACL, NULL, &pSD);

     if (ERROR_SUCCESS != dwRes) {
         printf("GetNamedSecurityInfo Error %u\n", dwRes);
         goto Cleanup;
     }

     // Initialize an EXPLICIT_ACCESS structure for the new ACE.

     ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
     ea.grfAccessPermissions = dwAccessRights;
     ea.grfAccessMode = AccessMode;
     ea.grfInheritance = dwInheritance;
     ea.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
     ea.Trustee.ptstrName = L"CURRENT_USER";
     ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
     // Create a new ACL that merges the new ACE
     // into the existing DACL.

     dwRes = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
     if (ERROR_SUCCESS != dwRes) {
         printf("SetEntriesInAcl Error %u\n", dwRes);
         goto Cleanup;
     }

     // Attach the new ACL as the object's DACL.

     dwRes = SetNamedSecurityInfo(pszObjName, ObjectType,
         DACL_SECURITY_INFORMATION,
         NULL, NULL, pNewDACL, NULL);
     if (ERROR_SUCCESS != dwRes) {
         printf("SetNamedSecurityInfo Error %u\n", dwRes);
         goto Cleanup;
     }

 Cleanup:

     if (pSD != NULL)
         LocalFree((HLOCAL)pSD);
     if (pNewDACL != NULL)
         LocalFree((HLOCAL)pNewDACL);

     return dwRes;
 }

 int main()
 {
     DWORD access_mask = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | FILE_ALL_ACCESS;
     DWORD grant = 0;

     std::cout << "Before modification \n";

     bool b = CanAccessFolder(L"C:\\Deny\\file.txt", access_mask, grant);

     printMasks(grant);

     std::cout << "After removing access \n";

     DWORD dwres = AddAceToObjectsSecurityDescriptor(
         L"C:\\Deny\\file.txt",
         SE_FILE_OBJECT,
         FILE_ALL_ACCESS,
         DENY_ACCESS,
         NO_INHERITANCE);

     if (dwres == ERROR_SUCCESS)
     {
         grant = 0;
         bool b = CanAccessFolder(L"C:\\Deny\\file.txt", access_mask, grant);
         printMasks(grant);
     }
     else
     {
         std::cout << "Error   :   " << GetLastError() << '\n';
     }
     HANDLE hFile = CreateFileW(L"C:\\Deny\\file.txt",               // file name
         GENERIC_READ,          // open for reading
         0,                     // do not share
         NULL,                  // default security
         OPEN_EXISTING,         // existing file only
         FILE_ATTRIBUTE_NORMAL, // normal file
         NULL);                 // no template
     if (hFile == INVALID_HANDLE_VALUE)
     {
         std::cout << "CreateFileW1 Error  :  " << GetLastError() << '\n';
     }

 // ?????????????????????? GRANT ACCESS ?????????????????????????????????

     std::cout << "After granting access \n";
     DWORD dwres1 = AddAceToObjectsSecurityDescriptor(
         L"C:\\Deny\\file.txt",
         SE_FILE_OBJECT,
         FILE_GENERIC_READ | FILE_GENERIC_WRITE,
         GRANT_ACCESS,
         NO_INHERITANCE);

     if (dwres1 == ERROR_SUCCESS)
     {
         grant = 0;
         bool b = CanAccessFolder(L"C:\\Deny\\file.txt", access_mask, grant);
         printMasks(grant);
     }
     else
     {
         std::cout << "Error   :   " << GetLastError() << '\n';
     }
     HANDLE hFile1 = CreateFileW(L"C:\\Deny\\file.txt",               // file name
         GENERIC_READ,          // open for reading
         0,                     // do not share
         NULL,                  // default security
         OPEN_EXISTING,         // existing file only
         FILE_ATTRIBUTE_NORMAL, // normal file
         NULL);                 // no template
     if (hFile1 == INVALID_HANDLE_VALUE)
     {
         std::cout << "CreateFileW2 Error  :  " << GetLastError() << '\n';
     }

     return 0;
 }

I get the output for this code as below
Before modification
Effective Allowed Access Mask :  2032127
Full Control
Read
Write
Execute
After removing access
Effective Allowed Access Mask :  0
CreateFileW1 Error  :  5
After granting access
Effective Allowed Access Mask :  0

After granting permissions I can access the file "file.txt", I can open it/write to it (e.g. CreateFileW passes)
What I dont understand is the mystery behind the permission bits, which is displayed as 0 even though I have granted the permissions FILE_GENERIC_READ | FILE_GENERIC_WRITE to the CURRENT_USER trustee.
I also checked the DAC List using icacls and it gave me following output
C:\>icacls C:\Deny\file.txt
C:\Deny\file.txt DOMAIN\user:(DENY)(D,WDAC,WO,X,DC)
                 DOMAIN\user:(R,W)
                 NT AUTHORITY\Authenticated Users:(I)(F)
                 DOMAIN\user:(I)(F)
                 BUILTIN\Users:(I)(F)
                 BUILTIN\Administrators:(I)(F)
                 NT AUTHORITY\SYSTEM:(I)(F)

This tells me that my GRANT permissions ACE got pushed below the DENY one and this is a well documented behavior.
Is this why I am getting the flag value as 0 ?
Is there any way/API/function that can get me the correct flags i.e. which can tell that FILE_GENERIC_READ and FILE_GENERIC_WRITE are set ?


text:
Q: How to use original "break" in a loop when using pry-debugger How can I use break in a loop while using pry-debugger that has break function?
10.times do |i|
  break if i > 2
end

This code will fail with error ArgumentError: Cannot identify arguments as breakpoint.

A: Instead of using break, you could use break(). The parenthesis will help ruby distinguish between pry-debugger's break, and the ruby break() function. Your code would then look like this:
10.times do |i|
  break() if i > 2
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to return another return? I'm looking to use functions within my Python program to make it cleaner and more efficient, Within my function I either return true or false depending on a user's selection. Though in the case they enter an incorrect / invalid response, I'd like to return a return that way asking more questions don't be asked.
Edit:
To be a bit more descriptive; I'd like to re-create this:
def askquestion(question):
    response = input(question, "Enter T or F")
    if response == "T":
        return True
    elif response == "F":
        return False
    else:
        return None

def askmultiple():
    questionOne = askquestion("Do you fruits?")
    if questionOne == None:
        return # Exit the function, not asking more questions

    questionTwo = askquestion("Do you Apples?")
    if questionTwo == None:
        return # Exit the function, not asking more questions

I want to cut out checking afterwards if it is None and just return return.

A: When you don't create a return statement at the end of a function that is equal to a sole return and those two are equal to return None call.
So you may organize your code like:
if returned_value is None:
    # do something a
elif returned_value is False:
    # do something else
else:  # value is True
    # do something b

A: You can try using a while loop to make sure that the user inputs a correct input.
For example:
while not response.isdigit():
     response =  input("That was not a number try again")

In this case, while the user input, "response" is not a number the python console will keep asking for a response. For a basic template,
while not (what you want):
    (ask for input again)

I hope this helps you. :)

A: Use an exception flow.
def ask_question(prompt):
    """Asks a question, translating 'T' to True and 'F' to False"""
    response = input(prompt)

    table = {'T': True, 'F': False}
    return table[response.upper()]  # this allows `t` and `f` as valid answers, too.

def ask_multiple():
    questions = [
        "Do you fruits?",
        "Do you apples?",
        # and etc....
    ]

    try:
        for prompt in questions:
            result = ask_question(prompt)
    except KeyError as e:
        pass  # this is what happens when the user enters an incorrect response

Since table[response.upper()] will raise a KeyError if response.upper() is neither 'T' nor 'F', you can catch it down below and use that flow to move you out of the loop.

Another option is to write a validator that forces the user to answer correctly.
def ask_question(prompt):
    while True:
        response = input(prompt)
        if response.upper() in ['T', 'F']:
            break
    return True if response.upper() == 'T' else False


text:
Q: I want to implement an upload form in react My upload form needs to be able to select multiple files, show the upload progress, and show the files uploaded below the upload button, user will be able to delete the upload displayed also. I know there are libraries to execute this, point me in the direction of good ones that i can manipulate the css or provide useful links on how to build from scratch. Thank you

A: You can hide the file input and trigger the upload with the button or something.

const addFile = () => {
   document.getElementById('fileElement').click()
}
<input type="file" id="fileElement" style="display:none">
<button onclick="addFile"></button>


text:
Q: I am trying to get some details ( username, description, Posts Count, total likes & total comments ) from Instagram user* I am trying to get some details ( username, description, Posts Count, total likes & total comments ) from Instagram user

*

*First i get the code from api.instagram.com with scope user_profile and user_media
https://api.instagram.com/oauth/authorize?client_id={appId}&redirect_uri={redirectUri}&scope=user_profile,user_media&response_type=code

*After the user accepts the permission and allows the sharing of information it I got the code in my redirectUri.

*then using that code and developer auth details I get the access_token by
https://api.instagram.com/oauth/access_token endpoint with fields client_id, redirect_uri, grant_type = authorization_code, client_secret and the code.
in response, I got the user_id and the access_token.

*Then I try to get the username and user details by calling the below endpoint  Refrence
https://graph.instagram.com/me?fields=id,username&access_token={access_token}.
in response, I got the username and id.

*Now I am not sure how to get the details like ( username, description, Posts Count, total likes & total comments ).
What I have tried

*

*I try to get the details by calling the https://www.instagram.com/someone/?__a=1 it works fine sometimes but now it's not returning anything.

*Instagram Graph Api in this I am getting the error the access token is not valid. ( not sure which access token to user Instagrams or facebooks )

A: You're currently using the Instagram Basic Display APIs (official docs) which are highly limited and do not include any of the information you seek, apart from the username.
Instagram chose not to include this information in the Instagram Basic Display APIs, while they offer them in the Instagram Graph API (official docs) instead.
However, the Instagram Graph API only works with Business and Creators accounts, therefore you can not use it for most Instagram users.
Furthermore the 2 APIs do not communicate with each other, so you can not use the Basic Display Token on the Graph token, even if the user is business.
Bottom line:

*

*if you're planning to retrieve this information for normal users (non-business and non-creators), you won't be able to use any official API

*if you're planning to retrieve this information only for business or creator accounts, you need to switch your entire logic to the Instagram Graph API, including the login flow, which needs to happen via Facebook => Page connected to IG.

It's a pity, I know, but that's the current situation.
EDIT: scraping from https://www.instagram.com/someone/?__a=1 is very complicated, Instagram has a great anti-crawling policy and will block scraping very well.


text:
Q: Incompatible types error Java between short and int. Unsure of cause In the following code I have an error
"possible loss of precision
found   : int
required: short".
I understand what the error means but I'm just wondering why I'm getting it. Surely the function should return a type of short (I can't see how there could be any loss of precision, the code should return a 16 bit integer). Can anyone clear up for me why the following code seems to require the type int?
static short a() {
    short[] payload = {
            100, 200, 300,
            400, 500, 600,
            700, 800, 900, 1000
    };
    short offset = 2;
    return (payload[offset - 2] << 8 & 0xff00) + (payload[offset - 1] & 0xff);
}

Thanks!

A: Java arithmetic operations on short always return int, partly to help prevent overflow, and partly to reflect the underlying JVM bytecode, which doesn't distinguish between arithmetic operations on int, short, or byte.  But basically, (payload[offset - 2] << 8 & 0xff00) is an int, and it wants you to cast it back down to a short.


text:
Q: Does $\sum_{n=1}^{\infty} \frac{1}{n^2x-1}$ converge uniformly on $(-\infty, -a), a>0$? I'm currently using Rudins book and this problem is not one of the listed exercises, but I want to try to understand it.
My work:
Define $S_n(x)=\sum_{k=1}^n \frac{1}{k^2x-1}$. Then $\left\vert S_n-S_m\right\vert=\left\vert\sum_{k=n+1}^{m}\frac{1}{k^2x-1}\right\vert=\sum_{k=n+1}^{m}\left\vert\frac{1}{k^2x-1}\right\vert$. I want to find an upper bound for this difference but all I have is $|k^2x-1|=k^2x+(-1)|\leq |k^2x|+1$ which doesn't help.
Any tips?

A: If $x\in (-\infty,-a)$ with $a>0$, then $\frac{1}{n^{2}x-1}$ is always negative and:
$$|\frac{1}{n^{2}x-1}|= \frac{1}{n^{2}|x|+1}$$
So $S_{k} = -\sigma_{k}$ where $\sigma_{k} = \sum^{k}_{n=1}\frac{1}{n^{2}|x|+1}$.
$$ \sigma_{k} = \sum^{k}_{n=1}\frac{1}{n^{2}|x|+1} <  \sum^{k}_{n=1}\frac{1}{n^{2}|x|} = \frac{1}{|x|}\sum^{k}_{n=1}\frac{1}{n^{2}} $$
Assuming the solution of the Basel problem (you will have a small follow-up exercise to prove boundedness of the comparison series if you can't assume this), you know that {$\sigma_{k}$} is a monotone bounded sequence and thus converges, therefore {$S_{k}$} wth $S_{k} = -\sigma_{k}$ also converges, either by the same reasoning (monotone bounded sequence) or by nature of the relationship.
To finish the uniformity given convergence of {$\sigma_{k}$} to \sigma' consider that:
$$ \sigma' - \sigma_{k} = \sum^{\infty}_{n=k+1}\frac{1}{n^{2}|x|+1} <  \sum^{\infty}_{n=k+1}\frac{1}{n^{2}|x|} = \frac{1}{|x|}\sum^{\infty}_{n=k+1}\frac{1}{n^{2}} <  \frac{1}{a}\sum^{\infty}_{n=k+1}\frac{1}{n^{2}}$$
Therefore given $\epsilon > 0$ There is a $M$ such that $|S_{j}-S'| < \epsilon$ for all $j>M$ for every $x\in (-\infty,-a)$.


text:
Q: Custom validation rules generation with dynamic data in Laravel I have an application which contains products with

*

*dynamic dimensions. eg. 2D/3D products

*preset sizes eg. 2x2, 3x3

*custom size inputs AxB (user input)

These configurations are stored in the model and database.
I need to validate the size input.
This is an example of what I have written in my model. How do I go about converting this to a valid validation rule?
function validSizeString($size_string) {
        $size_array = explode('x', $size_string);
        $options = $this->getAttribute('options');
        $size_type = $this->getAttribute('size_type');
        if($size_type == self::SIZE_TYPE_2D && count($size_array) != 2){
            return false;
        } elseif($size_type == self::SIZE_TYPE_3D && count($size_array) != 3) {
            return false;
        } elseif ( !in_array($size_type, [self::SIZE_TYPE_2D, self::SIZE_TYPE_3D])) {
            return false;
        }
        if(isset($options->preset_sizes_on) && $options->preset_sizes_on){
            if(in_array($size_string, $options->preset_sizes) ){
                return true;
            }
        }
}

Custom size validation logic
if(isset($options->custom_size_on) && $options->custom_size_on){
        $within_limits = function($value, $type) use ($options) {
            if($value <= $options->{"max_.$type"} && $value >= $options->{"min_.$type"} ){
                return true;
            }
            return false;
        };
        if ( !$within_limits($size_array[0], 'width') ) {
            return false;
        }
        if ( !$within_limits($size_array[1], 'height') ) {
            return false;
        }
        if($size_type == self::SIZE_TYPE_3D) {
            if( !$within_limits($size_array[2], 'length') ) {
                return false;
            }
        }
        return true;
    }


text:
Q: Python regular expressions - either one character, or the other, or both given following string
f = "803611662_249364_200825.csv"
I want to extract all possible numbers, that could be handled as a date and surrounded by "_" andor ".",
in this case "249364" or "_200825."
My RE is:  _[0-9]{6}[_?|.]
So, first an underscore, then exactly 6 numbers (doesn't matter if date will be invalid), followed by either "_" or ".".
The [] is non greedy, so it'll only return the first match and not the second.
Expected output: ['_249364`_', '_200825.']

A: You can use a capture group with a positive lookahead to get only the numbers:
_(\d{6})(?=[._])

regex demo
Example
import re

s="803611662_249364_200825.csv"
pattern = "_(\d{6})(?=[._])"
print(re.findall(pattern, s))

Output
['249364', '200825']

To get the values including the leading _ and following . or _ you can also use the capture group inside the lookahead:
(?=(_\d{6}[._]))

Regex demo
Example
import re

s="803611662_249364_200825.csv"
pattern = "(?=(_\d{6}[._]))"
print(re.findall(pattern, s))

Output
['_249364_', '_200825.']


text:
Q: Heat equation in cylindrical coordinates with Neumann boundary condition Given a cylinder of internal radius $r_0$ and external radius $r_1$, the heat equation in cylindrical coordinates that represents the behaviour of the temperature inside the cylinder, can be written as:
$$\frac{dT(\alpha,r,t)}{dt}=D[\frac{d^2 T(\alpha,r,t)}{dr^2}+\frac{1}{r}\frac{dT(\alpha,r,t)}{dr}+\frac{1}{r^2}\frac{d^2T(\alpha,r,t)}{d\alpha^2}+\frac{d^2T(\alpha,r,t)}{dz^2}]\qquad1$$
If we suppose the temperature isn't depending by $\alpha$ and $z$, the previous equation can be simplified to:
$$\frac{dT(r,t)}{dt}=D[\frac{d^2 T(r,t)}{dr^2}+\frac{1}{r}\frac{dT(r,t)}{dr}]\qquad2$$
Assuming the following boundary and initial conditions:
$$T(r,0)=T_0$$ for $r_0\le r \le r_1$
$$\partial_r T(r,t)=T_1sin(\omega t)$$
calculated in $r_1$,
 how can be found the solution of the equation $(2)$?

A: Of course we use separation of variables:
Let $T(r,t)=F(r)G(t)$ ,
Then $F(r)G'(t)=D\left(F''(r)G(t)+\dfrac{1}{r}F'(r)G(t)\right)$
$F(r)G'(t)=DG(t)\left(F''(r)+\dfrac{1}{r}F'(r)\right)$
$\dfrac{G'(t)}{DG(t)}=\dfrac{F''(r)+\dfrac{1}{r}F'(r)}{F(r)}=-s^2$
$\begin{cases}\dfrac{G'(t)}{G(t)}=-Ds^2\\F''(r)+\dfrac{1}{r}F'(r)+s^2F(r)=0\end{cases}$
According to http://eqworld.ipmnet.ru/en/solutions/ode/ode0207.pdf,
$\begin{cases}G(t)=c_3(s)e^{-Dts^2}\\F(r)=\begin{cases}c_1(s)J_0(rs)+c_2(s)Y_0(rs)&\text{when}~s\neq0\\c_1\ln r+c_2&\text{when}~s=0\end{cases}\end{cases}$
$\therefore T(r,t)=C_1\ln r+C_2+\int_0^\infty C_3(s)e^{-Dts^2}J_0(rs)~ds+\int_0^\infty C_4(s)e^{-Dts^2}Y_0(rs)~ds$
$\partial_rT(r,t)=\dfrac{C_1}{r}-\int_0^\infty sC_3(s)e^{-Dts^2}J_1(rs)~ds-\int_0^\infty sC_4(s)e^{-Dts^2}Y_1(rs)~ds$
Substituting $T(r,0)=T_0$ and $\partial_rT(r_2,t)=T_1\sin\omega t$ respectively , you will get this system of equations $\begin{cases}C_1\ln r+C_2+\int_0^\infty C_3(s)J_0(rs)~ds+\int_0^\infty C_4(s)Y_0(rs)~ds=T_0\\\dfrac{C_1}{r_2}-\int_0^\infty sC_3(s)e^{-Dts^2}J_1(r_2s)~ds-\int_0^\infty sC_4(s)e^{-Dts^2}Y_1(r_2s)~ds=T_1\sin\omega t\end{cases}$ .
The only thing is that $C_3(s)$ and $C_4(s)$ are in fact really difficult to find.

A: Using Laplace Transform $\hat T(r,s) = \int_0^\infty e^{-st} T(r,t) dt$  on (2) we have
$$
\frac{d^2 \hat T}{d r^2} + \frac{1}{r} \frac{d \hat T}{d r} - \frac{s}{D} \hat T = - \frac{T_0}{D} \tag{1}
$$
with the condition
$$
\frac{d \hat T}{d r}(r_1,s) = \frac{T_1 \omega}{s^2 + \omega^2} \tag{2}
$$
As @in_wolfram_we_trust stated, you are missing a condition, and the problem is underdetermined. Surely there is something missing on the physics of the problem. That being said, taking the change of variables $r = b \rho$, eq. (1) transforms into
$$
\frac{d^2 \hat T}{d r^2} + \frac{1}{r} \frac{d \hat T}{d r} - \frac{b^2 s}{D} \hat T = - \frac{b^2 T_0}{D} \tag{3}
$$
Letting $b = \sqrt{\frac{D}{s}}$, eq. (3) becomes
$$
\frac{d^2 \hat T}{d r^2} + \frac{1}{r} \frac{d \hat T}{d r} - \hat T = - \frac{T_0}{s} \tag{4}
$$
which is the nonhomogeneous Modified Bessel Equation of order zero. Then eq. (1) has as solution
$$
\hat T(r,s) = c_1 I_0\left(\sqrt{\tfrac{s}{D}} r\right) + c_2 K_0\left(\sqrt{\tfrac{s}{D}} r\right) + \frac{T_0}{s} \tag{5}
$$
A typical physical restriction would be that the temperature should remain finite which, in the case of the full cylinder would mean $c_2 = 0$, but since the cylinder does not contain $r = 0$, nothing can be said of $c_2$ (or $c_1$ for that matter). Once again, I feel the need to emphasize that the problem is missing a condition and is underdetermined.
Condition (2) means
$$
\frac{T_1 \omega}{s^2 + \omega} = c_1 \sqrt{\tfrac{s}{D}} I_0'\left(\sqrt{\tfrac{s}{D}} r_1\right) + c_2 \sqrt{\tfrac{s}{D}} K_0'\left(\sqrt{\tfrac{s}{D}} r_1\right),
$$
and using known recurrence relations
$$
\frac{T_1 \omega}{s^2 + \omega} = c_1 \sqrt{\tfrac{s}{D}} I_1\left(\sqrt{\tfrac{s}{D}} r_1\right) - c_2 \sqrt{\tfrac{s}{D}} K_1\left(\sqrt{\tfrac{s}{D}} r_1\right) \tag{6}
$$
From eq. (6), the solution on Laplace space is
$$
\hat T(r,s) = c_1 I_0\left(\sqrt{\tfrac{s}{D}} r\right) +\left[c_1 I_1\left(\sqrt{\tfrac{s}{D}} r_1\right) - \sqrt{\tfrac{D}{s}}\tfrac{T_1 \omega}{s^2 + \omega^2} \right]\tfrac{K_0\left(\sqrt{\tfrac{s}{D}} r\right)}{K_1\left(\sqrt{\tfrac{s}{D}} r_1\right)} + \frac{T_0}{s} \tag{7}
$$
At this point, it's clear that no closed solution will be abailable (with this method, anyway), and given that there is a missing condition, I think this is as close to a solution as one might get. Fortunately, using Stehfest Algorithm you can have a pretty neat numerical inversion.
Doing some asymptotics one can build analytic expressions almost as good as the true solution, but given the lack of a second condition, it doesn't seem to worth the trouble (for now at least).


text:
Q: group of points which this eqution determines I suspect that $xy+x=0$ determines the equation of an infinite line in $R^3$ for which a general coordinate is $(0,-1,z)$ since in the end, it is the intersection of x=0 and y=-1 (the planes). is this right?

A: The equation is independent in $z$, so any $z$ coordinate will do.   Factoring, we have $x(y+1)=0$,  so we must have $x=0$ or $y=-1$.  If $x=0$, then both $y$ and $z$ are independent, so we have the plane $x=0$,  i.e. the y-z plane.  Similarly, if $y=-1$, we have $x,z$ are independant, so we have a plane in the x-z axis going through $y=-1$.  So the solution is the union of two planes


text:
Q: command-line-runner selenium EACCES: permission denied, mkdir I using docker-compose
in ubuntu container with Dockerfile I install
RUN npm install -g selenium-side-runner
Then i run try run from www-data user
selenium-side-runner --output-directory /tmp /application/src/www.opendi.co.uk.side --server http://chrome-hub.local:4444/wd/hub

get
EACCES: permission denied, mkdir 'side-suite-www.opendi.co.uk'
at Object.mkdirSync (fs.js:987:3)
at runProject (/usr/lib/node_modules/selenium-side-runner/dist/index.js:240:15)
at runAll (/usr/lib/node_modules/selenium-side-runner/dist/index.js:345:10)
at Object. (/usr/lib/node_modules/selenium-side-runner/dist/index.js:390:3)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
errno: -13,
syscall: 'mkdir',
code: 'EACCES',
path: 'side-suite-www.opendi.co.uk'

Where selenium-side-runner try create this directory ? in /tmp ? in this location it can do this

A: /application/src/www.opendi.co.uk.side

this is the path that doesn't exist inside docker. It is trying to create the www.opendi.co.uk.side directory
Remove that and try:
selenium-side-runner --output-directory /tmp --server http://chrome-hub.local:4444/wd/hub


text:
Q: Knitr / R error when saving to a relative directory I try to save a variable to a relative path. The R code runs without a problem in RStudio, but as soon as I compile the RMarkdown file i get a reproducible error (only if the destination path is relative).
This is my RMarkdown file:
---
title: "Untitled"
output: html_document
---

```{r test}
x<-"test"
save(x,file="./raw_data/test.r")
```

This is the resulting error:
processing file: Untitled.Rmd

Quitting from lines 7-9 (Untitled.Rmd)
Error in gzfile(file, "wb") : cannot open the connection
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> save -> gzfile
Execution halted

Is this a bug / does knitr not support relative directory paths?
Thanks


text:
Q: dblink for AWS RDS mysql or AWS Aurora (MySQL combatible) I am using AWS RDS MySQL and plan to move to Aurora (MySQL combatible).
I am looking for a method to use dblink between db instances as what Aurora (PostgreSQL combatible) can do.
Any one know how to do this or this is impossible with MySQL?
Thanks in advance.


text:
Q: Graphing an inverse parametrically My calculus book has the following question:
Graph the one - to - one function $ f(x) = x^2$ , where x is greater than or equal to zero, with its inverse.
Now my answer is that the inverse is the graph of: $ y = \sqrt { x }$ .
The book says that the answer is the graph of: $x = t^2$ , $y = t$ , where t is more than or equal to 0.
How did they get this answer?
Thanks!

A: It is easy. For all $(x_1,x_2)=(x_1,f(x_1))$ the inverse function should give $(x_2,x_1)$. Namely you will just the change of the place of $y$ and $x$ in the original equation. In other words take the square of the equation that you have already found.

A: Now consider $x=t^2 $ as You're Domain, And $y=\sqrt{x}=\sqrt {t ^ 2}=t $ As You're Range


text:
Q: ExtJs textarea multiline issue How can I assign text containing \r\n to an ExtJs textarea and get to see line breaks instead of the actual \r\n characters? When I manually press the Enter key and check Firebug, I can see \r\n getting inserted. But if I assign a string containing \r\n to the textarea, it renders as-is.
Any hints would be helpful.

A: I solved it myself. I was using the 'html' property to assign the \r\n-riddled text to the textarea. I changed that to 'value', and it works like a charm. Thanks anyway.

A: Try:
var text = text.replace('\r\n',"" + String.fromCharCode(13) + String.fromCharCode(10));

A: Try this:
Replace all occurrences of \r\n with \n globally.
g - represents replace all occurrences of \r\n with \n and it will move to the next line.
var formattedText=text.replace(/\\n/g,'\r\n');
Ext.ComponentQuery.query('#id')[0].setValue(formattedText);


text:
Q: Problems with responsive configurator I'm having a problem with making a responsive hubcap configurator. I don't know how to deal with it. I was trying to make it with CSS grid, but every time I was changing size of the site, my tires weren't fitting perfectly to their places. I was thinking about something like this:

But unfortunately it doesn't work.
Right now I'm trying to make it with position relative and absolute, but it still doesn't work.
Html:

Scss:
.content {
  background: url('../assets/tlo_3.png');
  background-position: center;
  background-size: center;
  background-repeat: no-repeat;
  height: 70vh;
  position: relative;
  &__car {
    background: url('../assets/auto/bmw/black.png');
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    left: 0;
    right: 0;
    bottom: 5%;
    text-align: center;
    height: 70%;
    width: 70%;
  }
  &__rig-left {
    position: absolute;
    left: 12.7%;
    bottom: 0;
    width: 15%;
  }
  &__rig-right {
    position: absolute;
    right: 16.5%;
    bottom: 0;
    width: 15%;
  }
}

and it looks like this, but it's no responsive:
In good resolution:

Issue with responsive:

I would be really appreciate if you could somehow help me, btw it's my first post :)

A: The trick to getting the hubcaps in the right place is to use their positions as percentages of the dimensions of the image - not directly of the device. Also, use the image of the car as an HTML img src so that its dimensions set the dimensions of its containing div. We can't use a background image and cover in this case as we need everything proportional to the image.
We can put the hubcaps in as backgrounds if desired as the dimensions of their divs will be what we use. In this snippet the hubcaps are just silver circles.
Each image will have its wheels in slightly different places within its image so each image will have to be measured and the measurements kept somewhere for each car. in this snippet they are kept in each car's class (car1, car2 etc) as CSS variables and CSS calcs are done to get them positioned.

body {
  width: 100vw;
  height: 100vh;
  background-image: linear-gradient(to bottom, white 0%, gray 100%);
}

.car {
  margin: 0;
  padding: 0;
  position: relative;
  width: 70%;
  height: auto;
  left: 50%;
  transform: translateX(-50%) translateY(-100%);
  top: 100%;
  background-color: pink; /* just to show that the image can be larger than the actual car */
}
.car img{
  width: 100%;
  height: auto;
}

.hubcap {
  position: absolute;
  width: calc((var(--d) / var(--w)) * 100%);
  height: calc((var(--d) / var(--h)) * 100%);
  background-color: silver; /* just as a test, change to whatever image is wanted */
  border-radius: 50%; /* ditto */
  border-style: solid;
}

.hubcapfront {
  bottom: calc((var(--bf) / var(--h)) * 100%);
  left: calc((var(--lf) / var(--w)) * 100%);
  transform: translateX(-50%) translateY(50%);
}

.hubcapback {
  bottom: calc((var(--bb) / var(--h)) * 100%);
  right: calc((var(--rb) / var(--w)) * 100%);
  transform: translateX(50%) translateY(50%);
}

.car1 {
 --d: 3.5;  /* diameter of wheels. Doesn't matter what units - just use the same units for all these measurements*/
 --lf: 5.5; /* distance from left edge of the image to center of front wheel  */
 --rb: 5;   /* distance from right edge of the image to center of back wheel */
 --bf: 2.7; /* distance from bottom of image to center of front wheel */
 --bb: 2.7; /* distance from bottom of image to center of back wheel */
 --w: 24;   /* width of the image */
 --h: 9;    /* height of the image */
}


text:
Q: OAuth for multuple internal apps and main site I have one main Asp.net MVC application, I also have a help site and quite a few internal apps (that I need to build - reporting, stats, support tickets).
Question: Can OAuth be used in this way? i.e. a user can be authenticated to use all apps (if they have access to that app)?
Ideally all or most of the other apps will be implemented in Ruby or Node.js - so I am hoping I can achieve this with OAuth.

A: As long as all of your apps run under the same top level domain, it should not be strictly neccessary to use OAuth or similar to obtain a shared session. Instead you could rely on a plain session cookie. You could run some kind of middleware in between your app and the user.
Only if the main app is providing a REST API that you may want to use on various client apps, where some of them run in external environments / domains, making use of OAuth may be relevant.


text:
Q: bootstrap-3 - img-responsive not working I have built a small site for fun, getting familiar with bootstrap.
The issue I have is that the logo image is not responsive, no matter what I try.
The code seems quite straightforward I am sure I am just missing a minor detail:

          TEL: 450 955-3422

          182 CHEMIN D'ADAMSVILLE

          J2L 2Y6, BROMONT

          laboucheriedugrosbuck@gmail.com

PROMO

              FAITES VOTRE PLAN DE VIANDE:

              ACHETEZ POUR PLUS DE 100$ DE PRODUITS
              À L'UNITÉ ET RECEVEZ 10% EN SAUCISSES.

( Here is a fiddle reproducing the issue ) - https://jsfiddle.net/JoshC/2XgDW/2/

A: First remove the max-width: 184px attribute from the image tag

Although it would be better to avoid the use of inline styling:

#myLogo {
    padding-right: 1.5em;
    padding-top: 0px;
}

If there is a possibility that one of the ancestor elements' styling may be interfering, you can reset it like so:
#myLogo {
    all: initial!important;
    width: 100%!important;
    height: auto!important;
}

If you're still facing the issue, the next step would be to use JavaScript
Object.assign(document.getElementById('myLogo').style, {
    all: 'initial',
    width: '100%',
    height: 'auto'
});

This code should be included after the element in the document otherwise it will not be able to find the specified element as it won't exist yet.

Now that you've added the example to your question, you can make the image assume its natural size by replacing the following CSS:
img {
    display:table-cell;
    width:100%;
    height:auto;
}

With this CSS:
img {
    display:inline-block;
}

(Demo)

I believe that your use of display: table is interfering with your design. Below are two methods of achieving the same layout without hacks.
CSS3 Method
All relevant modern browsers support this method so if you dont care about backwards compatibility with old browsers, you can use this method.
(Demo)

Lorem Ipsum is simply dummy text Lorem Ipsum is simply dummy text Lorem Ipsum is simply dummy text

*,*:before,*:after {
    box-sizing: border-box;
}
.inline-wrap {
    white-space: nowrap;
    font-size: 0;
    height: 150px;
}
.inline-wrap img {
    width: 150px;
}
.inline-wrap .text-wrap {
    white-space: initial;
    font-size: initial;
    display: inline-block;
    height: 100%;
    width: 65%; /* Fallback */
    width: calc(100% - 150px);
}

Table Method
For backwards compatibility you can use this method.
(Demo)

        Lorem Ipsum is simply dummy text Lorem Ipsum is simply dummy text Lorem Ipsum is simply dummy text

*, *:before, *:after {
    box-sizing: border-box;
}
table, tr, td {
    border: 0;
    padding: 0;
    margin: 0;
    border-collapse: collapse;
}
table {
    width:100%;
}
table .img-wrap {
    font-size: 0;
}
table .text-wrap {
    width: 100%;
    height: 100%;
}

A: Try changing max-width to width: 100% that should tell it to take up 100% of the containers width, but as the containers width changes, so will the images size, while always maintaining 100% width coverage.
This SHOULD work, if it doesn't let me know and I'll hack it out a bit.  I'm just on my phone so I don't really want to sandbox it anywhere with a touchscreen keyboard.  If this doesn't work, I'll hack it out on my PC tomorrow afternoon :D!
Ps.  Is there a reason you declare class .header-logo in one div and then again in the next div give it the same class.  I understand if it was a different div block, but this is essentially a header logo inside a header logo


text:
Q: Iterating via nested loops The packages.yml file defined as:
---
- packages:
    - name: Some description 1,
      packageList:
        - package1,
        - package2,
        - package3

    - name: Some description 2,
      package: package4

The first item contains a field packageList, the 2nd item does not have it, but only package field.
Playbook:
---
- hosts: all
  become: yes
  vars_files:
    - packages.yml

How to iterate via all packageList items of the packages list only if this packageList is defined for an item.
Here is how I can iterate through items which contain package field:
- name: iteration
  debug:
    msg: "name: {{ item.package }}"
  when: item.package is defined
  with_items: "{{ packages }}"

A: As noted in my comment, if you simply want to install multiple yum/apt packages, it is usually more efficient to simply pass the list to the apt/yum/package module. As the docs state:
"When used with a loop: each package will be processed individually, it is much more efficient to pass the list directly to the name option."
However, if you really need a loop, here is a possible solution:
playbook.yml:
---
- hosts: all
  gather_facts: false
  vars_files:
    - packages.yml

  tasks:
  - name: iteration over single items
    debug:
      msg: "name: {{ item.package }}"
    when: item.package is defined
    with_items: "{{ packages }}"

  - name: iteration over lists
    debug:
      msg: "name: {{ item.packageList }}"
    when: item.packageList is defined
    with_items: "{{ packages }}"

  - name: Do something with individual packages in the list
    include_tasks: process_list.yml
    vars:
      mylist: "{{outer.packageList}}"
    when: outer.packageList is defined
    loop: "{{ packages }}"
    loop_control:
      loop_var: outer

process_list.yml:
- name: See what we have received
  debug:
    var: item
  loop: "{{mylist}}"

result:
PLAY [all] *******************************************************************************************************************************

TASK [iteration over single items] *******************************************************************************************************
skipping: [localhost] => (item={u'packageList': [u'package1,', u'package2,', u'package3'], u'name': u'Some description 1,'})
ok: [localhost] => (item={u'name': u'Some description 2,', u'package': u'package4'}) => {
    "msg": "name: package4"
}

TASK [iteration over lists] **************************************************************************************************************
ok: [localhost] => (item={u'packageList': [u'package1,', u'package2,', u'package3'], u'name': u'Some description 1,'}) => {
    "msg": "name: [u'package1,', u'package2,', u'package3']"
}
skipping: [localhost] => (item={u'name': u'Some description 2,', u'package': u'package4'})

TASK [Do something with individual packages in the list] *********************************************************************************
skipping: [localhost] => (item={u'name': u'Some description 2,', u'package': u'package4'})
included: /root/tmp/process_list.yml for localhost

TASK [See what we have received] *********************************************************************************************************
ok: [localhost] => (item=package1,) => {
    "ansible_loop_var": "item",
    "item": "package1,"
}
ok: [localhost] => (item=package2,) => {
    "ansible_loop_var": "item",
    "item": "package2,"
}
ok: [localhost] => (item=package3) => {
    "ansible_loop_var": "item",
    "item": "package3"
}

PLAY RECAP *******************************************************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The loop_control/loop_var part is used because otherwise both the outer and inner loop will use {{item}} as the loop variable - and this will cause... interesting results :)

A: You can define a default value with an empty list for the cases, where the packageList is undefined.
{{ item.packageList | default ([]) }}

If the packageList is undefined, the job iterates over an empty list, which means, it does not do anything.

A: You can use default, as @ceving mentioned:
---
- hosts: localhost
  connection: local

  vars_files:
  - packages.yml

  tasks:
  - name: iteration
    debug:
      msg: "name: {{ item.packageList | default([item.package]) }}"
    with_items: "{{ packages }}"

If packageList exists, it will use that, else package put into a single-element array to match the form of packageList:
PLAY [localhost] **********************************************************************************************

TASK [Gathering Facts] ****************************************************************************************
ok: [localhost]

TASK [iteration] **********************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": "name: [u'package1,', u'package2,', u'package3']"
}
ok: [localhost] => (item=None) => {
    "msg": "name: [u'package4']"
}

PLAY RECAP ****************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0


text:
Q: When does it make sense to transmigrate/reincarnate story characters? I'm still fairly early on in Disgaea. I've just started Map 4, and Laharl is only level 18 or so.
I see that I have the option to Transmigrate him. As I understand it, transmigration makes a lot of sense for my newly-created characters, as I effectively upgrade what class they are (like Cleric to Priest or Bishop). However, for characters like Laharl and Etna, they can't upgrade their class or change class, so the only benefit seems to be that they may get some more ability points, depending on how much mana I spend.
I'm left with some questions about when it's worth it do this. Are the ability bonuses cumulative, such that if I transmigrate him 10 times, I'll get 10 times worth of stat bonsues? Or will my 2nd transmigration wipe out the ability bonuses of the first?

*

*If they do stack, does it ever make sense to transmigrate as a Genius, since it costs a heck of a lot more mana (8000) to get 10 points, whereas I could transmigrate 10 times for +1 ability points (only costs 10 mana each time!)?

*If it doesn't stack, will I ever need to transmigrate again once I've transmigrated at the Genius level?

*What's the "Inheritance Bonus" percentage, and how does this affect things?

A: Story Characters are great to migrate the first 5 times because you get a 5% aptitude bonus for all stats the first 5 times; aptitude % means you gain that much of your equipment's stats as a %. So after 5 transmigrations you get 25% more out of all equipment for that character!
However, transmigrating shouldn't be done lightly unless you can very easily level your characters. You'll have to level your characters over again and gain enough mana for them to transmigrate again.
The main reason for transmigrating to Genius is because of the Inheritance Rate. Inheritance rate is how much of your Skill and Weapon experience you lose when you transmigrate. If you have 1000 Ax Skill and transmigrate with 50% inheritance rate, you now have 500 Ax Skill. Since there is no easy way to grind Weapon Level or Skill Level, losing skill level really hurts. Doing it early on can be good if you're sure you can get the mana/levels back in reasonable time.
If you can't easily get enough mana to migrate your character as a Genius, don't transmigrate yet. Disgaea is not about grinding, it's about grinding intelligently. You're too early in the game to worry about this from what I can tell.
Ability points don't stack in the way you describe; you always get 10 for genius, and you get a set amount of points extra for that character based on their total level.


text:
Q: Finding a monochromatic cycle in clique 1) what is the minimum $n$ such that in every $2$ - coloring of $K_n$ there exist a monochromatic copy of $C_m$ ?
2) moreover, what is the minimum $n$ such that in every $r$ - coloring of $K_n$ there exist a monochromatic cycle?
I found that the answer to 1 is known, but I don't find it.
http://www.mate.unlp.edu.ar/~liliana/lawclique_2016/21.pdf - (page 24)

A: Let me elaborate on a comment of bof.  For positive integers $r$ and $s$, let $c(r,s)$ denote the smallest positive integer $n$ such that if we color the edges of a clique on $n$ vertices with red and blue, either the red subgraph contains a cycle of length $r$ or the blue subgraph contains a cycle of length $s$.  The main theorem of Faudree and Schelp [All Ramsey numbers for cycles in graphs, Discrete Math. 8 (1974), 313-329] is the following.
(i) If $3\le s\le r$ and $s$ is odd and $(r,s)\ne (3,3)$, then $c(r,s)=2r-1$.
(ii) If $4\le s\le r$ and $s$ and $r$ are even and $(r,s)\ne (4,4)$, then $c(r,s)=r+\frac12s+1$.
(iii) If $4\le s < r$ and $s$ is even and $r$ is odd, then $c(r,s)=\max(r+\frac12s-1,2s-1)$.
So the answer to (1), to guarantee a monochromatic copy of $C_m$, comes by setting $r=s=m$.  To complete the answer, we mention that $c(3,3)=c(4,4)=6$.


text:
Q: Prove the nonexistence of a function on[0,1]
Possible Duplicate:
Set of continuity points of a real function

I want to prove that there does not exist a function on [0,1] which is continuous on rational number,and it is not continuous on irrational number. Someone suggest that if this function exists,it is Riemann integrable. Then use Riemann Lebesgue Lemma, it is incorrect. But I don't know how to prove it is integrable.

A: Suppose function $f$ is continuous at all rationals.  Let $r_n$ be an enumeration of the rationals in $[0,1]$.  Construct a sequence of nested closed intervals $I_n = [a_n, b_n]$ with $I_0 = [0,1]$ as follows.  Given $I_n$, take a rational number  $t_{n+1} \in (a_n, b_n)$ that is not $r_{n+1}$, and let $I_{n+1} = [t_{n+1}-\delta, t_{n+1}+\delta]$ where $0 < \delta < \min(|r_{n+1} - t_{n+1}|, |a_n - t_{n+1}|, |b_n - t_{n+1}|)$ and $\delta$ is small enough that
$|f(x) - f(t_{n+1})| < 1/(n+1)$ for all $x \in I_{n+1}$.  The intersection of these intervals contains no rationals, but does contain a point where $f$ is continuous.


text:
Q: Sending description to NSError I think I've found a bug on NSError but want to run it passed you guys and see if it's actually just me doing something wrong.
I get a crash when sending description to an NSError instance that makes use of userInfo.
If userInfo is set to nil description works as expected.
NSString* const domain = @"DOMAIN";

NSError* nsError1 = [NSError errorWithDomain:domain code:1 userInfo:nil]; // Not using Dic
NSLog(@"nsError1 description %@",[nsError1 description]);

NSMutableDictionary* errorDetail = [NSMutableDictionary dictionary];
NSString* underlying = [NSString stringWithFormat:@"Error Domain=%@ Code=%d", NSPOSIXErrorDomain, 1];
[errorDetail setObject:underlying forKey:NSUnderlyingErrorKey];

NSError* nsError2 = [NSError errorWithDomain:domain code:1 userInfo:errorDetail]; // Useing  Dic
NSLog(@"nsError2 description %@",[nsError2 description]); // CRASH

Output:
2013-04-26 22:36:03.703 CategoryTest[14271:11303] nsError1 description Error Domain=DOMAIN Code=1 "The operation couldn't be completed. (DOMAIN error 1.)"
2013-04-26 22:37:30.459 CategoryTest[14271:11303] -[__NSCFString localizedDescription]: unrecognized selector sent to instance 0x901cca0

A: This is a mistake in your code, not a bug in Apple's. NSUnderlyingErrorKey is documented to have an NSError object as the value corresponding to it. Your code should instead do something like:
NSError *underlying = [NSError errorWithDomain:NSPOSIXErrorDomain code:1 userInfo:nil];


text:
Q: A question about localization of integral domains Let $R$ be an integral domain and $P,Q$ be proper prime ideals of $R$. Let $R_P,R_Q$ be localizations of $R$ at $P,Q$. If $R_P\subseteq R_Q$, is $Q\subseteq P$?

A: Take any element $q\in Q$. If it was not it $P$, then it would be invertible in $R_P$, but not in $R_Q$, which would contradict the fact that $R_P\subseteq R_Q$.

A: More generally, if $R$ is a commutative ring, then $R$-algebra homomorphisms $R_P \to R_Q$ exist and are unique - by the universal property of localizations - iff $R \to R_Q$ maps $R \setminus P$ to $(R_Q)^* = R_Q \setminus Q R_Q$ iff (since $Q R_Q \cap R = Q$)  $R \setminus P \subseteq R \setminus Q$ iff $Q \subseteq P$.
More generally, if $X$ is a scheme with points $x,y$, then $x$ is a specialization of $y$ iff there is a morphism of $X$-schemes $\mathrm{Spec}(\mathcal{O}_{X,y}) \to \mathrm{Spec}(\mathcal{O}_{X,x})$.


text:
Q: Turn off suggestions bar for Chrome in Android phone I am looking to turn off spelling suggestions for a input box and I am not able to achieve it.
I used autocomplete="off" , autocapitalize="off" and spellcheck="off" for the input but am able to see the bar above keypad showing suggestions.
This is affecting my layout. Looking for working solutions.

A: If you are using Cordova for this, in html5 there is the spellcheck attribute.
<input type="text" spellcheck="false">

A: you need to be clear about the input box, is it an edit text? if yes using the following in your xml could help :
android:inputType="textNoSuggestions"

A: For html input , you can use autocorrect attribute
<input autocorrect="off"/>

For native android xml EditText, you can specify inputType
<EditText
    android:inputType="textNoSuggestions"/>

Hope this helps.


text:
Q: Read uploadedFile's content with it's original format string(text) I uploaded a file and i can get the file name, type, size and content. The content is in a format of byte array. I want the cotnet in it's original format, which is text file(String). Is there a way to read the uploadedFile of the primefaces like the File in io. or is there a way i can read the content in a string format.

A: It's simple. The uploaded file will contain a byte[] of the contents of the uploaded file, so you can simply construct a String from it:
public void handleUpload(final FileUploadEvent event) throws IOException {
  String content = new String(event.getFile().getContent(), StandardCharsets.UTF_8);
}

See also:

*

*How to convert byte array to string and vice versa?


text:
Q: StreamBuilder updates' performance (One vs Multiple) what is the performance difference between updating a single parent widget with multiple children
versus updating each child on their own.
which is more performant and by how much :
StreamBuilder(
  stream:sameStream,
  builder(ctx,snapshot){
    return Column(
      children:[
       Text("1"),
       Text("2"),
       Text("3")
      ]
    )
  }
)

Or
Column(
  children:[
    StreamBuilder(
      stream:sameStream,
      builder(ctx,snapshot){
        return  Text("1"):
      }
    ),
    StreamBuilder(
      stream:sameStream,
      builder(ctx,snapshot){
        return  Text("2"):
      }
    ),
    StreamBuilder(
      stream:sameStream,
      builder(ctx,snapshot){
        return  Text("3"):
      }
    )
  ]
)

An Other question : What happens if we scale the children widgets to 100 ? does the performance change ?

A: Having more Listeners to the same Stream (or any other state) will decrease the performance.
Check this benchmark when adding Listeners
value notifier benchmarks : https://github.com/knaeckeKami/changenotifier_benchmark
ChangeNotifier benchmarks : https://github.com/flutter/flutter/pull/62330
Having a list of expensive widgets with only one Listener will also decrease the performance (when they all get rebuild).
Anyways if you are using the same Stream with multiple children you should only use one Listener because when the state is changed they will all get a rebuild call whether they are on the same Listener or any of them have a Listener, but in the second case when the state is changed the Stream has to do more work notifying every Listener it has.
I got your problem, it occurs when you are having a list (of state) and yeah if you could have one Listener it would be faster for the notifying when the state changed but also it might be expansive to rebuild all the children which they don't have any update.
A solution for that case is using ProviderScope form Riverpod which can be used with to overwrite another provider for particular widget or using
.select method.


text:
Q: How to set a proper context for a ListBox ItemTemplate property in a custom user control Here is my ListBox Custom control: UCListBox. The MainLabel is the property I have issues with. It is used as a "label" for a ListBox item:
<ListBox ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"
         SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"
         >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding MainLabel, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

CodeBehind:
public partial class UCListBox : UserControl
{
    public UCListBox()
    {
        InitializeComponent();
    }

    public object ItemsSource
    {
        get { return (object)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(object), typeof(UCListBox), new PropertyMetadata(null));

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(object), typeof(UCListBox), new PropertyMetadata(null));

    public string MainLabel
    {
        get { return (string)GetValue(MainLabelProperty); }
        set { SetValue(MainLabelProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MainLabel.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MainLabelProperty =
        DependencyProperty.Register("MainLabel", typeof(string), typeof(UCListBox), new PropertyMetadata(string.Empty));
    }

Here I try to use my custom control in a window:
<local:UCListBox
    ItemsSource="{Binding Participants}"
    SelectedItem="{Binding SelectedParticipant}"
    MainLabel ="{Binding NameShort1}"
/>

I get a binding error:
Property "NameShort1 is not found for WindowEditCaseVM.

The context of the MainLabel property is my View Model like the rest of the properties and not the context of a ListBox item. How do I fix the context of my custom control's property to display listbox items correctly?

A: The thing that helped me to solve my problem with help of @Clemens was to make the DataTemplate into a resource and define a DataType property for it.
First, define a namespace, containing my Participant class in the head of my UserControl:
         xmlns:model="clr-namespace:DocConstructor.BusinessModel"

Then define the resource
<UserControl.Resources>
    <DataTemplate DataType="{x:Type model:Participant}">
        <StackPanel>
            <TextBlock Text="{Binding NameShort1}"/>
            <TextBlock Text="{Binding CaseStatusType.Description}"/>
        </StackPanel>
    </DataTemplate>
</UserControl.Resources>

Full code:
<UserControl x:Class="DocConstructor.UserControls.UCListBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:DocConstructor.UserControls"
             mc:Ignorable="d"
             xmlns:model="clr-namespace:DocConstructor.BusinessModel"
>
    <UserControl.Resources>
        <DataTemplate DataType="{x:Type model:Participant}">
            <StackPanel>
                <TextBlock Text="{Binding NameShort1}"/>
                <TextBlock Text="{Binding CaseStatusType.Description}"/>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>
    <ListBox ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"
             SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"
             >
    </ListBox>
</UserControl>


text:
Q: What could go wrong when transferring Minecraft data through an Xbox 360 data transfer cable? I have an issue with a RRoD and my biggest consern is Minecraft - my precious worlds, my data... Is that also transferable? Because it may seem however that Minecraft is a little different from other games considering the fact that you only generate one very specific landscape and build the map up, while Fallout and all those other games have everything already built the same way on every game in the world.
My question is, if I use a data transfer cable to move everything, is all my data going to be transferred and put on the new hard drive the exact same way as it was on the Xbox? Same spawn point, same version, same worlds, same skins, clothing, and name? I've been anxious about this specific game for 4 months.

A: Yes, of course you can, and nothing will change. Nothing will change, because copying data from one memory to another is like ctrl + C and ctrl + V. Nothing changes.
For some more clarification: Copying data luckily does not change them in any way. Data are not like a painting, that when you want to copy, you have to re-draw it by hand onto another paper, and in the process make some small errors. When you copy data, eg. bytes, it's like when you copy a number from one paper to another.
If the data transfer is possible, all stuff on your old Minecraft will be exactly the same. To the last detail.


text:
Q: Does Objective-C Method Swizzling affect code in other process? Does Objective-C Method Swizzling affect code in other process?
For example, I do the method swizzling on the -[NSArray count] in my app. Will the code in other processes be affected by that method swizzling?
AFAIU method resolution should be within the process. But I'm not sure about the code from system frameworks. Do they have their own method resolution shared between processes or they have the method resolution per process

A: No.  Think about the security holes if it did.....
Btw: why in he world would you want to swizzle 'count'?
In general, sizzling is bad.  Fragile, a maintenance nightmare, and a good way to get rejected from the store.


text:
Q: Can't run parallel zgrep with regex When I run this:
find . -name "my.log*.gz" -print | \
parallel zgrep -e "\(text1\|text2\).*Exception"

to find all lines that match /(text1|text2).*Exception/ in all files in the folder, I get this error message:
zsh:1: no matches found: (text1|text2).*Exception

From the error message, I think (text1|text2).*Exception is being treated as a file name. What am I doing wrong here?

A: Use -E for extended regex
find . -name "my.log*.gz" -print | \
parallel zgrep -E "\(text1\|text2\).*Exception"

A: You need more quoting:
find . -name "*.gz" -print |
  parallel -q zgrep -e "\(text1\|text2\).*Exception"

Use -vv and --dr to see what is really being run.

A: If you are using the parallel command from the moreutils package, your command could be simplified like this:
parallel zgrep -e "\(text1\|text2\).*Exception" -- my.log*.gz

This will run parallel instances of zgrep, one for each file matching the shell pattern my.log*.gz. Note that the pattern is expanded by the shell before the command is executed. Hence there is no need for a separate invocation of find.
Use zgrep with option -H if you want to know which file matches.


text:
Q: incompatible types: org.apache.http.impl.client.CloseableHttpClient cannot be converted to org.apache.hc.client5.http.classic.HttpClient Am upgrading 'spring-boot-starter' version from 2.5.7 to 3.0.2 then am getting compilation error saying like
'incompatible types: org.apache.http.impl.client.CloseableHttpClient cannot be converted to org.apache.hc.client5.http.classic.HttpClient'
can you please some one help on this?
Thanks in advance.
am expecting the resolution for the problem

A: org.apache.http.impl.client.CloseableHttpClient is part of the older Apache HttpComponents library, which has been deprecated in favour of the newer Apache HttpComponents Client 5 library.
Here you can find more details:
https://hc.apache.org/httpcomponents-client-5.2.x/migration-guide/migration-to-classic.html

There will be compilation errors due to API incompatibilities between
version series 4.x and 5.x mostly related to SSL/TLS and timeout
settings and CloseableHttpClient instance creation. Remove old
org.apache.http imports and re-import HttpClient classes from
org.apache.hc.httpclient5 package namespace.

If you are using version 5.x of the library, you will need to make sure that you are using the correct classes and interfaces from that version, rather than the older ones from version 4.x.


text:
Q: jquery to only allow one rollover at a time I created a .slideDown & .slideUp effect on a div based on mouseover and mouseleave.
The problem is that when I rollover multiple divs to fast then rolloff it seems to keep a memory of how many times I rolled over and will not stop until all of the slideDowns and slideUps are carried out.
Example: http://juliosalvat.com/IconTest/

A: Yeah, this is A nasty one. Jquery keeps a queue of events, to short cut that queue you can use .stop()
http://api.jquery.com/stop/
What you'll probably need is .stop(true, true) which will remove all animation in the queue and just play the last one.

A: You should look into the HoverIntent jQuery plugin
http://cherne.net/brian/resources/jquery.hoverIntent.html

hoverIntent is a plug-in that attempts to determine the user's
  intent... like a crystal ball, only with mouse movement! It works like
  (and was derived from) jQuery's built-in hover. However, instead of
  immediately calling the onMouseOver function, it waits until the
  user's mouse slows down enough before making the call.


text:
Q: Javascript Toggle open by width i have actually an Simple/Standart Toggle System from Bootstrap, my Knowledge about Javascript is 0, what i want is following, if the width size min. 700px then everytime open else the standart system. I Need only the function if desktop/media width size min. 700px so stay it open.
$("#menu-toggle").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
});

A: My Bad! Syntax error in my code before thats the right way
<script>
$("#menu-toggle").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
});

function resize() {
    if ($(window).width() > 614) {
     $('#wrapper').removeClass('toggled');
    }
}

$(document).ready( function() {
    $(window).resize(resize);
    resize();
});
</script>


text:
Q: Ctrl+Space for omni and keyword completion in vim I Want to use Ctrl+Space for omni-completion (and keyword completion if there is no omni-completion) in vim. I've tried this which I found somewhere on the web:
inoremap <expr> <c-space> pumvisible() ? "\<C-n>" : "\<C-x>\<C-o>\<C-n>\<C-p>\<C-r>=pumvisible() ? \"\\<Down>\" : \"\\<CR>\""

however it's not working. Anyone who is using Ctrl+Space for this too who can show me the correct way (which works) to do it?
Worth noting is that it needs to work in the terminal version of vim NOT gvim.

A: Try this:
inoremap <expr> <C-Space> pumvisible() \|\| &omnifunc == '' ?
\ "\<lt>C-n>" :
\ "\<lt>C-x>\<lt>C-o><c-r>=pumvisible() ?" .
\ "\"\\<lt>c-n>\\<lt>c-p>\\<lt>c-n>\" :" .
\ "\" \\<lt>bs>\\<lt>C-n>\"\<CR>"
imap <C-@> <C-Space>

A: The above way is "kind of" working, but it's so unreadable that almost nobody could say what it actually does. The solution above is not good.
Short Answer - Use this:
function! Auto_complete_string()
    if pumvisible()
        return "\<C-n>"
    else
        return "\<C-x>\<C-o>\<C-r>=Auto_complete_opened()\<CR>"
    end
endfunction

function! Auto_complete_opened()
    if pumvisible()
        return "\<Down>"
    end
    return ""
endfunction

inoremap <expr> <Nul> Auto_complete_string()
inoremap <expr> <C-Space> Auto_complete_string()

This answer also respects that there are two possible values (depending on terminal/gvim usage) for Ctrl+Space: <C-Space> and <Nul>.
I use a similar approach as the first one in jedi-vim, but more customizable.

Long Answer - What the above does:
The whole escaping of the above answer is so confusing, that I've split the above answer into a readable format:
function! Auto_complete_string()
    if pumvisible()
        return "\<C-n>"
    else
        return "\<C-x>\<C-o>\<C-r>=Auto_complete_opened()\<CR>"
    end
endfunction

function! Auto_complete_opened()
    if pumvisible()
        return "\<c-n>\<c-p>\<c-n>"
    else
        return "\<bs>\<C-n>"
    end
endfunction

inoremap <expr> <Nul> Auto_complete_string()

This clearly shows what it is doing. There's some weird stuff happening in Auto_complete_opened. It's not just doing completion, it's doing two additional things after trying to complete:

*

*When trying to use the omnicompletion, it somehow does a <C-n><C-p><C-n>, which could IMHO just be abbreviated to <C-n>.

*In case completion is unsuccessful, it uses a backspace and does a completion again, not <C-o><C-x> but <C-n>, which just doesn't make a lot of sense.

I'm not saying that this is not what some user might want, but it's probably not what most users want! My short answer takes that in credit and gives you a simple way to edit it. You can now just easily change things if you want to (for example <Down> to <C-n>, if you want the first entry to be written from the beginning on).

A: For iterm2 and vim these lines works for me, I got from jedi-vim
" Next three lines are to enable C-Space to autocomplete, omnicomplete
inoremap <C-Space> <C-x><C-o>
imap <buffer> <Nul> <C-Space>
smap <buffer> <Nul> <C-Space>


text:
Q: How to use a method multiple times in one? Objective:
So I'm using Eleventy as an SSG and want to create multiple folders and copy some files into these folders, before Eleventy is doing the building or site generation.
A JSON file is for the array of site titles (folder names).
And I chose to make use the fs-extra module instead of the Node.js fs module.
Inside .eleventy.js (config file):
    const fse = require('fs-extra');
    const arrayFromJSON = require('./_data/sites.json');
    const arrayTitles = arrayFromJSON.titles;

      eleventyConfig.on("beforeBuild", () => {
  // Create site folders and copy layout and frontmatter data to the folders
    arrayTitles.forEach(element =>
      fse.copySync(`sitesource/index.njk`, `src/_sites/${element}/${element}.njk`, { recursive: true }));
    arrayTitles.forEach(element =>
      fse.copySync(`sitesource/fm.11tydata.js`, `src/_sites/${element}/${element}.11tydata.js`, { recursive: true }));
  });

I've been looking around for ideas and examples to combine these two actions into one, where it's only needed once to call arrayTitles.forEach. But I haven't found it.
Is this possible, and anyone with suggestions to improve this code?

A: I may be confused, but why not simply use one forEach?
eleventyConfig.on("beforeBuild", () => {
    // Create site folders and copy layout and frontmatter data to the folders
    arrayTitles.forEach(element =>
      fse.copySync(`sitesource/index.njk`, `src/_sites/${element}/${element}.njk`, { recursive: true });
      fse.copySync(`sitesource/fm.11tydata.js`, `src/_sites/${element}/${element}.11tydata.js`, { recursive: true });
    );
  });


text:
Q: create listview on fragment custom drawer i have trouble with my code,
im trying to create a new listview on my fragment.
im using custom drawer.
this my code and my error on line 53.
View rootView = inflater.inflate(R.layout.fragment_layout_schedule, container, false);  //ERROR CODE HERE
this my complete code.
package com.example.blackcustomzier.skripsi;

import android.app.ListFragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Blackcustomzier on 10/2/14.
 */
public class FragmentSchedule extends ListFragment {

    // Array of strings storing country names
    String[] countries = new String[] {
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan"
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
            "Indian Rupee",
            "Pakistani Rupee",
            "Sri Lankan Rupee",
            "Renminbi",
            "Bangladeshi Taka",
            "Nepalese Rupee",
            "Afghani",
            "North Korean Won",
            "South Korean Won",
            "Japanese Yen"
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("ZZZ", "ada di oncreateView");
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_layout_schedule, container, false);
        List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

        for(int i=0;i<10;i++){
            HashMap<String, String> hm = new HashMap<String,String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur","Currency : " + currency[i]);
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = { "flag","txt","cur" };

        // Ids of views in listview_layout
        int[] to = {R.id.txt,R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to);

        setListAdapter(adapter);

        return rootView;
    }

}

this my fragment_layout_schedule
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/country_fragment"
        android:name="com.example.blackcustomzier.skripsi.FragmentSchedule"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

and this the catlog error
10-02 07:59:42.207    2103-2103/com.example.blackcustomzier.skripsi E/AndroidRuntime﹕ FATAL EXCEPTION: main
    android.view.InflateException: Binary XML file line #7: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at com.example.blackcustomzier.skripsi.FragmentSchedule.onCreateView(FragmentSchedule.java:53)
            at android.app.Fragment.performCreateView(Fragment.java:1695)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:861)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
            at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1137)
            at android.app.Activity.onCreateView(Activity.java:4746)

thanks before

A: This is because you are trying to expand a layout that does not contain a ListView object with the id "@android:id/list". You need to have this object in your layout xml. What you are trying to do is to inflate a regular fragment and map the list fragment to this but the thing is that there is no backing ListView object to map your ListFragment to.
Please see the description at http://developer.android.com/reference/android/app/ListFragment.html on how to create custom views for your list fragments.


text:
Q: How to horizontal scroll other items in list view by scrolling one item? I have many items in the listView, each item in the listView has an HorizontalScrollView. When I scroll one item, all the other items in the listView should scroll itself. How can I implement this?
The code for my listview is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/admin_ip_listView"
    android:padding="15dp"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView_ip_picture"
        android:background="@mipmap/ic_launcher_round"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView_ip_ref_number"
        />
    <HorizontalScrollView
        android:layout_width="900dp"
        android:layout_height="wrap_content"
        android:scrollbars="horizontal">
    <LinearLayout
        android:layout_width="900dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView_ip_q1"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView_ip_q2"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView_ip_q3"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView_ip_q4"/>

      </LinearLayout>
  </HorizontalScrollView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/texview_ip_avg"/>

</LinearLayout>

Thanks!

A: But why you fix android:layout_width with 900dp in HorizontalScrollView and LinearLayout?
Can you try to change: layout_width
like this:
<HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="horizontal">

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


text:
Q: Php - name = function() callback var I use a function in a foreach loop. And I update some var inside this loop and I would like to pass it inside a function.
However, I don't understand and if it's possible to pass callback argument.
It seems to not working like that.
foreach($infos as $info) {
    $i = $info;
    $a = 'aaa';
    $b = 'bbb';
    $datas[$i] = function($a,$b) {
        $data['a'] = $a;
        $data['b'] = $b;
        return $data;
    };
}
return $datas;

How can I pass the var $a, $b?

A: It's not clear why you have to write it like that. Use a direct assignment instead
$datas = array();
foreach($infos as $info) {
    $a = 'aaa';
    $b = 'bbb';
    $datas[$info] = array('a' => $a, 'b' => $b);
}

A: Not sure what you wan't to accomplish here but anonymous function can inherit variables from the parent scope with "use". So try:
foreach($infos as $info) {
    $i = $info;
    $a = 'aaa';
    $b = 'bbb';
    $datas[$i] = function() use ($a, $b) {
        $data['a'] = $a;
        $data['b'] = $b;
        return $data;
    };
}
return $datas;

A: See here - http://php.net/manual/en/functions.anonymous.php#example-195.
Must be something like this:
$datas[$i] = function() use($a,$b) {
   $data['a'] = $a;
   $data['b'] = $b;
   return $data;
};


text:
Q: Does ExternalInterface support dot notation access to a function owned by an object? Does ExtenalInterface.call support dot access to functions?
I'm trying to write a wrapper class and not have all my functions on the window document so I've put them in my own class MyClass.MyFunction.
But does that work with external interface? Will this work:
var result:Object = ExtenalInterface.call("MyClass.MyFunction", "hello");

A: From the documentation

The alphanumeric name of the function to call in the container. Using a non-alphanumeric function name causes a runtime error (error 2155). You can use a try..catch block to handle the error.

You'll need a dispatcher function to refer things to your class:
function dispatcher() {
    var name = arguments[0];
    var func = MyClass[name];

    func.apply(null, arguments);
    //You may also wish to consider slicing the array to remove the function name before calling the function
}

And use it like this from AS3:
var result:Object = ExtenalInterface.call("dispatcher", "MyFunction", "hello");


text:
Q: Why the name of FTp file is with HTML code? I have a simple VisualBasic project that downlad file from FTP server. So this is the code to do this:
 Public Sub TestMethod1()
    Dim fileList As New Generic.List(Of String)
    'GET FILE FROM SERVER
    Dim objFTPRequest As FtpWebRequest = CType(FtpWebRequest.Create(New Uri("ftp://ftp.address.it")), FtpWebRequest)
    objFTPRequest.Credentials = New NetworkCredential("user", "pass")
    objFTPRequest.KeepAlive = False
    objFTPRequest.UsePassive = False
    objFTPRequest.UseBinary = True
    objFTPRequest.Method = WebRequestMethods.Ftp.ListDirectory

    Dim response As FtpWebResponse = CType(objFTPRequest.GetResponse(), FtpWebResponse)
    Using respStream As StreamReader = New StreamReader(objFTPRequest.GetResponse().GetResponseStream())
        Dim line As String = respStream.ReadLine()
        While line IsNot Nothing

        If Regex.IsMatch(line, "^.*\.(pdf|doc|txt|zip|xlsx)$", RegexOptions.IgnoreCase) Then
            'If line Like _config.FileSearch Then
            fileList.Add(line)
        End If

        line = respStream.ReadLine()
        End While
    End Using

    'DOWNLOAD FILE INTO FILELIST
    For Each fileName As String In fileList
        DownloadFile(fileName)
    Next

    End Sub

Public Function DownloadFile(ByVal pFileName As String) As String
    Dim strPath As String = String.Empty

    Dim objFTPRequestDownload As FtpWebRequest = CType(FtpWebRequest.Create(New Uri("ftp://ftp.address.it/" & pFileName)), FtpWebRequest)
    objFTPRequestDownload.Credentials = New NetworkCredential("user", "pass")
    objFTPRequestDownload.KeepAlive = False
    objFTPRequestDownload.UsePassive = False
    objFTPRequestDownload.UseBinary = True
    objFTPRequestDownload.Method = WebRequestMethods.Ftp.DownloadFile

    Using respDownloadStream As StreamReader = New StreamReader(objFTPRequestDownload.GetResponse().GetResponseStream())
        Using destination As New StreamWriter("D:\" & pFileName)
        destination.Write(respDownloadStream.ReadToEnd())
        End Using
    End Using
    Return strPath
End Function

If I try to run this code from my PC with visualstudio 2010 and .NET framework = 4.0 I can read the all file into my FTP server like this:

file1.txt
file2.xlsx
...

And it is ok. But if I try to run this code from another pc with VisualStudio 2010 with .NET framework 4.0, if I try to run my code, the name of file are show in this mode:

10/06/15 12:00AM backup14,252 Cartel1.xlsx
EDIT
If I try to inspect on objFTPRequest, I can see the content type on my pc = "" (on my pc works). The content type on another pc, the content type is "html/text" (on another pc not works)


text:
Q: Android SharedPreferences returns two different values for the same key in two different classes I want to use one shared counter (int) for an android service. It's called from two different receivers, incremented and put back. At first call, both counters have the same value. However, after that, each one is incemented by itself. I couldn't find the problem.
FirstReceiver:
public class UserPresentBroadcastReceiver extends BroadcastReceiver {

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

    private int counter=0;
    @Override
    public void onReceive(Context context, Intent intent) {

        DataSource dataSource = new DataSource(context);
        dataSource.open();

        List<Note> notes = new ArrayList<>();
        notes.addAll(dataSource.findAllActiveNotes());

        SharedPreferences counterP =  context.getSharedPreferences(HatirlaticiService.COUNTER_LABEL, Context.MODE_PRIVATE);
        counter = counterP.getInt(HatirlaticiService.COUNTER_LABEL,0);
        setCounter(counter);

        if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){

            Toast toast = Toast.makeText(context, notes.get(counter%notes.size()).getName(),Toast.LENGTH_LONG);

            toast.setGravity(Gravity.BOTTOM,0,0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.show();
            counter++;
            SharedPreferences.Editor editor = counterP.edit();
            editor.putInt(HatirlaticiService.COUNTER_LABEL, counter);
            editor.apply();

            Log.i("Unlock:", "Counter: "+counter);

        }

    /*Device is shutting down. This is broadcast when the device
     * is being shut down (completely turned off, not sleeping)
     * */
        else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {

        }
        dataSource.close();
    }
}

Second Receiver:
public class Alarm extends BroadcastReceiver {

public int getCounter() {
    return counter;
}

public void setCounter(int counter) {
    this.counter = counter;
}

private int counter = 0;

@Override
public void onReceive(Context context, Intent intent)
{
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
    wl.acquire();

    SharedPreferences counterP =  context.getSharedPreferences(HatirlaticiService.COUNTER_LABEL, 0);
    counter = counterP.getInt(HatirlaticiService.COUNTER_LABEL,0);
    setCounter(counter);

    DataSource dataSource = new DataSource(context);
    dataSource.open();

    List<Note> notes = new ArrayList<>();
    notes.addAll(dataSource.findAllActiveNotes());

    Toast toast = Toast.makeText(context, notes.get(counter%notes.size()).getName(),Toast.LENGTH_LONG);
    toast.show();

    counter++;

    SharedPreferences.Editor editor = counterP.edit();
    editor.putInt(HatirlaticiService.COUNTER_LABEL, counter);
    editor.apply();

    Log.i("Alarm", "Counter: "+counter);

    dataSource.close();
    wl.release();
}
}

Output log:
hatirlatici I/Unlock: Counter: 234
hatirlatici:remote I/Alarm: Counter: 234
hatirlatici:remote I/Alarm: Counter: 235
hatirlatici:remote I/Alarm: Counter: 236
hatirlatici:remote I/Alarm: Counter: 237
hatirlatici I/Unlock: Counter: 235
hatirlatici:remote I/Alarm: Counter: 238
hatirlatici:remote I/Alarm: Counter: 239
hatirlatici:remote I/Alarm: Counter: 240
hatirlatici I/Unlock: Counter: 236

Normally, it should be like this:
hatirlatici:remote I/Alarm: Counter: 234
hatirlatici:remote I/Alarm: Counter: 235
hatirlatici I/Unlock: Counter: 236
hatirlatici:remote I/Alarm: Counter: 237
hatirlatici:remote I/Alarm: Counter: 238
hatirlatici I/Unlock: Counter: 239

Note: New to Android


text:
Q: Programming the Virtual Disk Service API in C# using COM Interop I would like to write a small utility/class library in C# that can enumerate the primary partitions on the disk associated with volume C on Windows 7. I would like to modify the active flag for any one the primary partitions on that disk. I would like to "consume" this library from managed code (C#). As I understand it, I will need to use the Virtual Disk Service described in http://msdn.microsoft.com/en-us/library/bb986750(v=VS.85).aspx.
There seems to be something like a "primary interop assembly" for this API for Windows 2008: Windows.Storage.Vds.dll (see http://blogs.msdn.com/taylorb/archive/2008/09/19/using-the-virtual-disk-service-vds-from-powershell-to-mount-and-use-vhd-s.aspx). I can't find this for Windows 7. Does it exist? If so, how do I obtain it? I can't find it, so I guess it's not publicly available.
The next step would be to generate this code using tlbimp, but VDS doesn't export a type library. Is this true? I can't find it.
That leaves doing the COM stuff "by hand" either in C++ directly, along the lines of the examples above. These examples work, but are virtually inscrutable. Likewise I could create the client assembly by hand from the midl using techniques described in http://msdn.microsoft.com/en-us/library/aa645736(VS.71).aspx. But I don't enough COM/COM Interop/VDS to do this in a reasonable way.
It strikes me the VDS dcom client api is virtual unusable and therefore everyone ends up scripting diskpart.exe. Surely I'm wrong about this.


text:
Q: How to Restrict Sales Rep users for not creating the Schedules Can any help me out with this?
I have a requirement where i would like to restrict few users Say As "Sales Rep Users" for not creating the Schedules .I mean their can create a Opportunity record with the products but should not have the access for scheduling.How can i do this ?
For Example :When a Sales Rep is creating a Opportunity record say as "XYZ" and opportunity product given as "ABC".Now the Sales Rep should not have the Access to Schedule or Reschedule the products.How can i achieve this.
Any help very much appreciated.


text:
Q: Kendo DatePicker Disable Dates jQuery I have a date picker on my page that I am trying to disable all days except Sunday when a value is selected in a Kendo Drop Down.   My function is below. The function is called but I am not sure how to or if I can set the disabled dates this way.  Can anyone point me in the right direction of syntax to do this?
I have tried
function dropdownChanged() {

    var startdate = $("#startdate").data("kendoDatePicker");

    //tried this with no luck
    var start_disabled = ["mo", "tu", "we", "th", "fr", "sa"];
    startdate.disableDates(start_disabled);

}

Thanks!

A: See the documentation here.
<input id="datepicker" />
<script>
$("#datepicker").kendoDatePicker({
    value: new Date(),
    disableDates: function (date) {
        var disabled = [13,14,20,21];
        if (date && disabled.indexOf(date.getDate()) > -1 ) {
            return true;
        } else {
            return false;
        }
    }
});
</script>

<input id="datepicker" />
<script>
$("#datepicker").kendoDatePicker({
    value: new Date(),
    disableDates: ["we", "th"],
});
</script>


text:
Q: How to get a particular upcoming week day for the entered datestring using Java I am a beginner in Java and new to this web world as well. I have a requirement to implement in my assignment project as below:
We need to add the days in input date such that it create the date of upcoming Monday.
example 1: If DateString = 17/02/2015 (Tuesday) then Output Date = 23/02/2015 (Monday).
example 2: If DateString = 18/02/2015 (Wednesday) then output Date = 23/02/2015 (Monday).
example 3: If DateString = 23/02/2015 (Monday) then output Date = 02/03/2015 (Monday).
input:Date string
output: upcoming Monday for the entered Date string

A: If I got you correct, I guess below code is what you are looking for -
String dateString = "23/02/2015";

Calendar cal=Calendar.getInstance();
DateFormat df=new SimpleDateFormat("dd/MM/yyyy");
Date date = df.parse(dateString);
cal.setTime(date);
cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
cal.add(Calendar.DATE,7);

System.out.println(df.format(cal.getTime()));

A:  public static void main(String[] args) throws IOException,ParseException{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter date(dd/mm/yyyy) : ");
            String input = br.readLine();
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            Calendar cal = Calendar.getInstance();
            Date date = df.parse(input);
            cal.setTime(date);
            int toAdd = (9 -cal.get(Calendar.DAY_OF_WEEK));
                cal.add(Calendar.DATE,toAdd);
                System.out.println("coming monday is on: " + cal.getTime());
        }

A: With Java 8, you can use TemporalAdjusters:
public String getNextMonday(String date, DateTimeFormatter formatter) {
    LocalDate startDate = LocalDate.parse(date, formatter);
    LocalDate monday = startDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
    return formatter.format(monday);
}

Call with
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String nextMonday = getNextMonday("23/02/2015", formatter);


text:
Q: PHP client IP is invalid I running latest PHP with Nginx. I'm trying to get the client's IP address.
Since my web server is behind CloudFlare, I'm using this code to get client's IP address.
It works for almost all the clients.
However, for some USERS IP is different for different providers. It is not the same.
$_SERVER["HTTP_CF_CONNECTING_IP"]

For example,
On My website => 103.241.21.61
On https://www.whatismyip.com/  => 103.241.21.26
On https://nordvpn.com/what-is-my-ip/ => 103.241.21.116
On https://www.iplocation.net/ => 103.241.21.78
On https://www.expressvpn.com/what-is-my-ip => 103.241.21.101
On https://www.whatismyip-address.com/?check => 103.241.21.51

Note that 103.241.21 is static. Last subnet is dynamic for different websites.
All these above providers are showing wrong IP address.
So I did google search "What is my IP" and Google actually showed the correct IP address.
Now how do I know that Google is showing the real IP ?
It is because if I block that IP on Firewall ( Amazon EC2 Security Group ), they can't access the website. So I know this is the real IP.
If I try to block other IPs it doesn't work as those IPs are not the real ones.
Is there any way to know how Google is finding their IP ?
Thanks!


text:
Q: Uninstalling Anaconda Safely While Maintaining Pip Installs I am unable to open the Anaconda Navigator after what I believe was trying to install nbviewer a couple of months ago. Whatever it was I was trying to install, I now get this error using any sort of conda command line:

Would the installations I've made with pip be erased and overwritten if I uninstalled Anaconda? I really don't want to deal with software again, I'd rather pip install everything but at the same time, I still do not want to ruin my workflow with Jupyter notebook. I'm worried that uninstalling Anaconda will reset everything.

A: Conda is a package manager, just like pip. But conda also manages the python environments which are used to run your code. If you uninstall conda, it is very likely that it will uninstall all your current packages.
After re-installation, I recommend that you only use conda or pip for your packages but not both at the same time, and that you use conda for environment managing.
For each different kinds of projects, you should create a new python environment by running
conda create -n my-new-environment python=3
#example

And only installing your packages with pip or conda.
This way each python environment is not polluted by the others and you have less risk to lose everything if one environment fails.
For more information of Python environments I recommend that you read the Python documentation on these subjects: https://docs.python.org/3/tutorial/venv.html