text:
Q: How can I specify the return types in GCD blocks How can i specify the return types in GCD blocks? Here I want to return my result as NSData ...
- (NSData *)returnData:(NSString *)urlString{
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_sync(concurrentQueue, ^{   // here return type showing error

        NSString *strUrl = urlString;
        if([strUrl length] == 0)
            return nil; // from this point i want to stop the execution of the block and return nil .

        // otherwise only continue the left operations

    });
}

A: - (NSData *)returnData:(NSString *)urlString {
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // Declare your local data outside the block.
    // `__block` specifies that the variable can be modified from within the block.
    __block NSData *localData = nil;

    dispatch_sync(concurrentQueue, ^{
        // Do something with `localData`...
        localData = somethingWonderful;
    });

    // `localData` now contains your wonderful data.
    return localData;
}

The block's format (parameters/return type) are specified in the function's signature. In this case, dispatch_sync uses a block with no return type and no parameters. If you want further variables to work with you need to declare them outside the block, as in the code above.

A: Since a block shares the scope with the parent, it's easiest not to specify a return type at all. For example:
- (NSData *)returnData:(NSString *)urlString{
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    __block NSData *data; // the __block keyword allows this variable to be changed by a block

    dispatch_sync(concurrentQueue, ^(NSData *)){   // here return type showing error

        data = [NSData dataWithContentsOfURL:@"http://stackoverflow.com"];

    });

    return data;
}

If you do want to specify a return type, then you cannot use dispatch_sync(), because it only accepts blocks with no return type. An example of how to use blocks manually is:
typedef NSData *(^MyDataBlock)();
MyDataBlock getData = ^ NSData *() {
  return [NSData data];
};

NSData *data = getData();

Note that because you are not using dispatch_sync() in the second example this code will execute immediately on the current queue instead of waiting until there is some available CPU time. Waiting for the CPU have some idle time can actually be faster than executing it immediately.
The advantage is this approach is much more flexible, you can pass the getData variable around to other methods and so on, and they could even execute it inside their own dispatch_sync() call to take advantage of GCD's priority system.

A: What's the exact error you're seeing? Because this line
dispatch_sync(concurrentQueue, ^(NSData *)){   // here return type showing error

has a syntax error. You've got a stray ) after your block argument list.
Even if you fix that, you have another problem, which is that you're trying to return a value from a block passed to dispatch_sync(), and yet dispatch_sync() expects a block that returns void. It seems that what you're really trying to do is return the data from the function, but to do this you need to pass the data from the block back to your outer function. You can do this with a __block-qualified variable, like this:
- (NSData *)returnData:(NSString *)urlString{
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    __block NSData *localData = nil;

    dispatch_sync(concurrentQueue, ^{
        if ([urlString length] == 0) {
            // we don't have any data to return
            return; // localData is already nil
        }
        // calculate localData
        localData = ...;
    });
    // Now localData should be populated
    return localData;
}

A: To expand on Frioze's caution:  if you you call any API not recommended for use on the main thread on the queue you _sync to, and you call dispatch_sync from the main thread you may as well have called that API from the main thread as you have asked to wait for it to complete.   This is true not just for the block in your _sync call, but also for any prior blocks sent via _async that have not yet completed.


text:
Q: How to change a local class varible node js I don't really know how to explain this but I will try my best
so I have a Card class in the file card.js that look like this:
class card {
    constructor(name = "", portrait = "", bloodCost = 0, boneCost = 0, power = 0, health = 1, sigilList = []) {
        this.name = name
        this.portrait = portrait;
        this.bloodCost = bloodCost;
        this.boneCost = boneCost;
        this.power = power;
        this.health = health;
        this.sigilList = sigilList;
    }
    attack(sigilList = [], board = [], oppositeCard = new card(), scale = 0) {
        var oppositeCardHealth = 0
        if (oppositeCard == blank) {
            scale += this.power;
        }
        else {
            oppositeCardHealth += this.power;
        }
        return [scale, oppositeCardHealth];
    };

var wolf = new card("Wolf", ":wolf:", 2, 0, 3, 2);
module.exports = { wolf };
}

And a 'main.js' file like this:
const cardLib = require("./lib/card");
var broad = [cardLib.wolf, cardLib.wolf]
broad[0].health -= 2;
console.log(broad);

So what I want to do is only changing the health of the wolf in broad[0] with out changing the other one health. Which mean the program should return something like this:
[
  card {
    name: 'Wolf',
    portrait: ':wolf:',
    bloodCost: 2,
    boneCost: 0,
    power: 3,
    health: 0,
    sigilList: []
  },
  card {
    name: 'Wolf',
    portrait: ':wolf:',
    bloodCost: 2,
    boneCost: 0,
    power: 3,
    health: 2,
    sigilList: []
  }
]

A: This statement:
var broad = [cardLib.wolf, cardLib.wolf]

Put's two references to the exact same wolf object in your array.  So, naturally, if you change one, the other will appear changed also because both spots in the array point at the exact same object.
If you want two separate, independent objects in the array, then you have to create two separate objects by creating a separate card.  To do that from outside that file, it would be best to export the Card constructor so you can call it and create a separate card to put into the array.  Another option would be to add a .copy() method to your Card object so you can create a copy of an existing object.

Here's an example of a .copy() method:
class card {
    constructor(name = "", portrait = "", bloodCost = 0, boneCost = 0, power = 0, health = 1, sigilList = []) {
        this.name = name
        this.portrait = portrait;
        this.bloodCost = bloodCost;
        this.boneCost = boneCost;
        this.power = power;
        this.health = health;
        this.sigilList = sigilList;
    }
    attack(sigilList = [], board = [], oppositeCard = new card(), scale = 0) {
        var oppositeCardHealth = 0
        if (oppositeCard == blank) {
            scale += this.power;
        } else {
            oppositeCardHealth += this.power;
        }
        return [scale, oppositeCardHealth];
    }
    copy() {
        let newCard = new card(
            this.name,
            this.portrait,
            this.bloodCost,
            this.boneCost,
            this.power,
            this.health,
            this.sigilList.slice(0);
        )
        return newCard;
    }
}

let wolf = new card("Wolf", ":wolf:", 2, 0, 3, 2);
module.exports = { wolf };

Which you can then use like this:
let broad = [cardLib.wolf, cardLib.wolf.copy()];

This implementation assumes that none of the instance variables except sigilList are objects that have to be copied themselves in order to be separate and that the sigilList array can be shallow copied with .slice(0) in order to be independent.

A: In your current code, wolf is a specific instance of a card. Your array has two references to the same object, so changing one of them will change them "both".
One approach could be to not hold a wolf variable, but instead provide a function to create such a wolf card:
// card.js:
class card {
     // constructor and attack unchanged, removed for brevity's sake
}

var wolf = () => new card("Wolf", ":wolf:", 2, 0, 3, 2);
module.exports = { wolf };

// main.js:
const cardLib = require("./lib/card");
var broad = [cardLib.wolf(), cardLib.wolf()]; // wolf is a function that creates a a card
broad[0].health -= 2;
console.log(broad);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set the rotation of an object to that of another object with a offset? im having problems with my game, i want to have a pistol orbit around my charecter and the position is allready done by a joint. however the joint doesn't rotate the object so i try to do that by code, but the problem is that i need to set an offset becouse the gun is 90degrees rotated around the y axes but than a weird thing happens.
i made a video to damonstrate this: https://youtu.be/HxNj6keyQ5U
i don't know how to fix this and i tryed everything.
thanks for your awnsers! (if i get any xD)
here's the code:
    {
        EulerRotation = new Vector3(Player.transform.rotation.eulerAngles.x, Player.transform.rotation.eulerAngles.y - 90, Player.transform.rotation.eulerAngles.z);
        transform.rotation = Quaternion.Euler(EulerRotation);
    }

A:
if you are using Standard First Person Controller, It contains two parts: Main Object, Main Camera.
by a script, rotation on Y-axis is attached to Main Prefab, and rotation on the Z axis is attached to the Main camera. so when you use Player.transform.rotation.eulerAngles.z in fact you are using Z axis on Main Object and so it will never change.


text:
Q: Specify which config transform to use for continuous deployment to Azure web app Is there a way to specify which config transform should be applied when deploying to an Azure web app through continuous integration (i.e. not through Publish in Visual Studio)?
We have continuous integration set up with Github, but it seems the Web.Release.config transform is always applied on deployment.
We would prefer to have a custom transform name, e.g. Web.Azure.config.
Is deployment slots used for this? And if so, is that the only way to do it?
Thanks!
PS. Does this question belong on ServerFault? I think it's more related to programming? DS.

A: The environment name can be set for a specific Azure web app by adding an application setting, in the Azure portal, called SCM_BUILD_ARGS with a value of -p:Environment MyAzureSite
This will set the environment name, resulting in a config transform named Web.MyAzureSite.config to be applied during build.
More information here

A: The first thing you might consider is whether that configuration setting is appropriate for the web.config file whether it might be better managed in the Web App configuration inside of Azure. Any AppSettings managed in the portal will override anything in the web.config file.
See here for guidance: https://github.com/projectkudu/kudu/wiki/Managing-settings-and-secrets
However, to answer your question, the Azure Continuous Deploy uses the Kudu build process. The msbuild command that is passed to build your project on azure (after you git push/github pull) is something like:
MSBuild MyWebApp\MyWebApp.csproj /t:pipelinePreDeployCopyAllFilesToOneFolder /p:_PackageTempDir="%DEPLOYMENT_TARGET%";AutoParameterizationWebConfigConnectionStrings=false;Configuration=Debug;SolutionDir="%DEPLOYMENT_SOURCE%"

This step does web.config transformation too.  To customize deployment like the way you would like you might want to also take a look at:
https://github.com/projectkudu/kudu/wiki/Deployment-hooks


text:
Q: C# SQL Database Windows Form Login System Im working on a SQL database project in C#. I'm looking to create a login form which will be presented when someone starts the application.
The connection is made to the database, however they must enter a correct username and password into the first form before they can proceed to see the rest.
I have created 2 text boxes, and a button txtusername and txtpassword and a button login.
Here is my SQL command:
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE Username ='" + txtUsername + "' AND Password = '" + txtPassword + "'", Program.cs);

I'm looking for a way to show in a label if the sql command yields a result meaning the username and password is stored in the user table then it returns true or something. If there is a more efficient or effective way to this also let me know :).

A: You should never create command texts by concatenating strings. Use SqlParameter. That is to put first things first.
And it seems to me that you have no (or very little) understanding how data access works in .net. So I'd recommend you to read some books on that topic, for example, Microsoft's "Accessing Data with .NET Framework 4".

A: This code is a Vulnerability in your project
See this for details

A: strong text*code for login page
b
tn_click() //button click event
{
    Sqlconnection con=new
    sqlconnection(Strcon);

    String sqlquery="select usrname,password from loginpage where username='textname.text' and password='textpassword.text'";

    Sqlcommand sqlcom=new Sqlcommand(Sqlquery,con);
    con.open();

    Sqldatareader dr;
    dr=sqlcomm.executereader(commandbehavior close connection);

    if(dr.read())
    {
        session["un"]=dr["username"].Tostring();
        session["pwd"]=dr["userpassword"].Tostring();

        if(dr["userpassword"].Tostring()!=null);
            respone.redirect("userdetail.aspx");
    }
    else
    {
        respone.redirect("login.aspx");
    }
    else
    {
        lblmsg.text="invalid user";
    }
}


text:
Q: Bootstrap columns in a row overlap with thymeleaf image tag I have a div contains a row with 2 columns. Left column contains an image and right side contains some text. I've tried 100s of different combinations but couldn't figure out how to avoid overlapping problem. As you can see the images, when I start to resize the window, it starts to overlapping.

About Us

                        Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                        when an unknown printer took a galley of type and scrambled it to make a type
                        specimen book. It has survived not only five centuries, but also the leap into
                        electronic typesetting, remaining essentially unchanged. It was popularised in
                        the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
                        and more recently with desktop publishing software like Aldus PageMaker
                        including versions of Lorem Ipsum.

I would love to have some margin top when its small as well, to have a clear separation.
UPDATE
Ryan Maffey, your solution works good up until a certain point. This is the result just before going for mobile view. Looks so bad at this point. I would love to have image on its own row if it shrinks more than 50%. Is it possible?

UPDATE 2
I finally found the combination I was looking for. This result solved all my problems.

Header

Lorem ipsum...

A: It looks as though the image is overflowing the column.
Adding CSS width: 100% onto the image will mean that it is only ever as wide as the width of the column it's in.

A: In the Mobile view you need to center the image vertically. Just use the parent div's style of that image to display: inline-block; height: 100%; vertical-align: middle; and that image to vertical-align: middle; max-height: 100px;


text:
Q: add class to parent ul on sub item click javascript I try to keep my menu open when a sub item with link is open. I have same class name for the parent menu and sub item link. I need the corresponding menu to remain open when sub item is clicked
thank you
here is what I have try so far

                finance

                        SubMenu1

                        submenu2

                Expenses

                        SubMenu1

                        submenu2

and js
 $(document).ready(function () {
        $('.sub').click(function () {

            $(this).parent('nav-content collapse > ul').addClass('show');

        });
    });

A: When you call .parent() on an element it gives you the immediate parent of that specific element.
In your case it will be the
 element above the anchor elements. If you want to access
 element, you will have to get the parent of the
 element.
You can do this by calling .parent() again on the element returned by .parent().
$(this).parent().parent().addClass('show');

A: To find a specific element in jquery if they have many levels
use
$(target_element).closest() to find parent level or
$(target_element).find() to find children level.
Ref: https://api.jquery.com/closest/
Ref: https://api.jquery.com/find/
Hope this might help you.


text:
Q: Recursive function in PHP function : how to prevent return value? I am working on an API to get data, just like the other standard API, it limit on the return numbers of item , e.g. each page return only 1 item in my case. So , I have to get the

*

*total_count,

*page_size (it is 1 at my case),

*and current_page_number.

The problem is, no matter I set it to recursive , it still return the value at the first cycle.  e.g. If there is total 3 items, and limit to 1 item per page, it will return the value during the 1st loop.
Why and how to fix that?
Thanks a lot
function get_video_list($page_no = 0, $filter_video = array()) {
    $api = "http://api.brightcove.com/services/library?command=search_videos&page_size=1&video_fields=id%2Cname%2CcreationDate%2CFLVURL%2CpublishedDate%2ClinkURL%2CthumbnailURL%2Clength&media_delivery=http&sort_by=CREATION_DATE%3AASC&page_number=$page_no&get_item_count=true&token=" . READ_TOKEN;

    try {
        $ch = curl_init();

        if (FALSE === $ch) {
            throw new Exception('failed to initialize');
        }

        curl_setopt($ch, CURLOPT_URL, $api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $content = curl_exec($ch);

        if (FALSE === $content) {
            throw new Exception(curl_error($ch), curl_errno($ch));
        }

        $video_list = json_decode($content, false, 512, JSON_BIGINT_AS_STRING);

        $page_number = ($video_list->page_number) + 1; //start at 0
        $page_size = $video_list->page_size;
        $total_count = $video_list->total_count;

        foreach ($video_list->items as $video) {
            if (in_array($video->id, $stored_video)) {
                $filter_video [] = $video;
            }
        }

        if ($total_count > $page_size * $page_number) {
            get_video_list($page_number, $filter_video);
        }

        return $filter_video;
    } catch (Exception $e) {
        trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
    }
}

A: You are not assigning the return value of the recursive call back to $filter_video, change to:
if ($total_count > $page_size * $page_number) {
    $filter_video = get_video_list($page_number, $filter_video);
}

Or, even better: pass by reference. This eliminates the need for return values altogether, especially useful for recursive functions (notice &$filter_video in the function declaration, see http://php.net/manual/en/language.references.pass.php).
function get_video_list($page_no = 0, &$filter_video = array()) {
    $api = "http://api.brightcove.com/services/library?command=search_videos&page_size=1&video_fields=id%2Cname%2CcreationDate%2CFLVURL%2CpublishedDate%2ClinkURL%2CthumbnailURL%2Clength&media_delivery=http&sort_by=CREATION_DATE%3AASC&page_number=$page_no&get_item_count=true&token=" . READ_TOKEN;

    try {
        $ch = curl_init();

        if (FALSE === $ch) {
            throw new Exception('failed to initialize');
        }

        curl_setopt($ch, CURLOPT_URL, $api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $content = curl_exec($ch);

        if (FALSE === $content) {
            throw new Exception(curl_error($ch), curl_errno($ch));
        }

        $video_list = json_decode($content, false, 512, JSON_BIGINT_AS_STRING);

        $page_number = ($video_list->page_number) + 1; //start at 0
        $page_size = $video_list->page_size;
        $total_count = $video_list->total_count;

        foreach ($video_list->items as $video) {
            if (in_array($video->id, $stored_video)) {
                $filter_video [] = $video;
            }
        }

        if ($total_count > $page_size * $page_number) {
            get_video_list($page_number, $filter_video);
        }
    } catch (Exception $e) {
        trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
    }
}

Then call it like this:
$myVideoList = [];
get_video_list(0, $myVideoList);

// Do stuff with $myVideoList

A: this should resolve your problem.
if ($total_count > $page_size * $page_number) {
      return get_video_list($page_number, $filter_video);
}


text:
Q: GPO not being applied I am using the powershell GroupPolicy module to create and link new GPOs. I have a large number of GPOs to create, and thus I wish to automate the process without having to interact with the Group Policy Editor.
I noticed while creating GPOs through the editor that each policy object would be contained in either one or several XML files or .INI files.
Having noted above, I started creating GPOs with the New-GPO command, passing the -Name and -Domain flags. After the GPO has been successfully created, I would (via my script) generate an XML file containing all of the information that the policy would consume. Shown below is an extract of the XML file that I would create to set up a mapped drives policy.
When inspecting the policy in the editor, everything looks fine. The correct drives are showing up and all of the settings appear to be correct. However, the policy is never applied. If I create an identical policy manually via the Group Policy Editor, all of the policies start working, including the ones that I created with powershell.
The error therefore seems to be that the domain controller is never made aware of the changes, but they get applied when a manual change is made.
I have tried running gpupdate /force, which does not seem to update or propagate the changes
    New-Item \\$($MappedDrivesGPO.DomainName)\SYSVOL\$($MappedDrivesGPO.DomainName)\Policies\$("{"+$MappedDrivesGPO.Id+"}")\User\Preferences\Drives\Drives.xml -ItemType File -Force
    Set-Content \\$($MappedDrivesGPO.DomainName)\SYSVOL\$($MappedDrivesGPO.DomainName)\Policies\$("{"+$MappedDrivesGPO.Id+"}")\User\Preferences\Drives\Drives.xml $xml

<?xml version="1.0" encoding="utf-8"?>
    <Drives clsid="{8FDDCC1A-0C3C-43cd-A6B4-71A6DF20DA8C}">
        <Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="P:" status="P:" image="2" changed="2019-04-26 10:41:54" uid="{$guid1}" bypassErrors="1">
            <Properties action="U" thisDrive="NOCHANGE" allDrives="NOCHANGE" userName="" path="\\fs1\Projects" label="Projects" persistent="0" useLetter="1" letter="P"/>
            <Filters>
                <FilterGroup bool="AND" not="0" name="$($domainName)\Drive P Access" sid="$($filterGroupSidDriveP)" userContext="1" primaryGroup="0" localGroup="0"/>
            </Filters>
        </Drive>
        <Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="S:" status="S:" image="2" changed="2019-04-26 10:39:21" uid="{$guid2}" bypassErrors="1">
            <Properties action="U" thisDrive="NOCHANGE" allDrives="NOCHANGE" userName="" path="\\as1\Software" label="Software" persistent="0" useLetter="1" letter="S"/>
            <Filters>
                <FilterGroup bool="AND" not="0" name="$($domainName)\Drive S Access" sid="$($filterGroupSidDriveS)" userContext="1" primaryGroup="0" localGroup="0"/>
            </Filters>
        </Drive>
    </Drives>

I expected the policy to start working as intended after the XML file had been created
The actual result is that the policy appears to be well formed, but never applied

A: I managed to resolve this on my own, posting here in case someone else runs into the same issue. If you're creating GPOs programmatically and not via the editor, you will have to extend your script/program to add CSE (in this case for drive mapping) and SnapIn GUID to gPCUserExtensionNames.
[{00000000-0000-0000-0000-000000000000}{2EA1A81B-48E5-45E9-8BB7-A6E3AC170006}][{5794DAFD-BE60-433F-88A2-1A31939AC01F}{2EA1A81B-48E5-45E9-8BB7-A6E3AC170006}]

The 0000.. is the Core GPO Engine, 23EA.. is the Preference Tool CSE GUID Drives, 5794.. is Preference CSE GUID Drives.
If you create the policy manually with the desired changes, you can then open dsa.msc, enable advanced features and then view the policy object properties. Under gPCUserExtensionNames you will be able to see the arrays containing the GUIDs that you need to incorporate in your software.


text:
Q: Proof that if $v_1,. . .v_n$ spans $V$, then $v_1 -v_2,. . .,v_{n-1} - v_n, v_n$ also spans $V$. I saw the following problem in Linear Algebra Done Right and thought if the general version of it would hold.
Problem: Suppose that $v_1,.  .  .,v_4$. spans $V$. Prove that $v_1 - v_2,v_2-v_3,v_3-v_4,v_4$ also spans $V$.
I would like if someone could confirm if the following proof is correct.
Q: Suppose that $v_1,.  .  .,v_n$ spans $V$. Prove that $v_1-v_2,v_2-v_3,.  .  .,v_{n-1}-v_n,v_n$ also spans $V$ for $n\geq 2$.
Proof: It suffices to show that there exists scalars such that $a_1(v_1-v_2)+.  .  .+a_{n-1}(v_{n-1}-v_n)+a_nv_n = c_1v_1+.  .  .+c_nv_n$.
Let
$a_1 = c_1$
$a_2 =c_1+c_2$
.
.
.
$a_{n-1}=c_1+.  .  .+c_{n-1}$
$a_n=c_1+. . .+c_n$
Then, $a_1(v_1-v_2)+.  .  .+a_{n-1}(v_{n-1}-v_n)+a_nv_n=c_1v_1+.  .  .+c_nv_n$.
Proving the desired result.
Is this reasoning correct?

A: Let me denote the span of a set $S$ by $L(S)$ . So let us denote the set $\{v_{1}-v_{2},...,v_{n-1}-v_{n},v_{n}\}=T$ and $S=\{v_{1},...,v_{n}\}$
Two equivalent definitons of span:-
1:- The span of a set $S$ is the set of all finite linear combinations of the elements of $S$ .
2:- The span of a set $S$ is the smallest subspace $L(S)$ of $V$ such that $S\subseteq L(S)$ . By smallest we mean the intersection of all subspaces of $V$ that contain $S$.
Now notice that $(v_{n-1}-v_{n})+(v_{n})=v_{n-1}\in L(T)$
Then again $v_{n-2}-v_{n-1}+v_{n-1}=v_{n-2}\in L(T)$ .
Use a simple induction to prove that $\{v_{1},...,v_{n}\}\in L(T)$
This directly gives you that $L(\{v_{1},...,v_{n}\})\subseteq L(L(T))=L(T)$
Also $T\subset L(S)\implies L(T)\subseteq L(L(S))=L(S)$
Thus $L(T)=L(S)$ .

A: There is another way to tackle the problem. Notice that there is an $nxn$ matrix $A$ which is
which satisfies

It is easy to notice that $A$ is invertible and therefore any
linear combination of the one side can be written as a linear
combination of the other side and vice versa. That is if a vector is a linear combination of v's is

which is a linear combination of $v_{i-1}-v_{i}$'s and we can do the same the inverse way, and that proves the result!


text:
Q: How to use two if statement into foreach in razor? I tried to use two if statements into foreach such as this but I get this error:

Encountered end tag "div" with no matching start tag.  Are your
  start/end tags properly balanced?

I want this to be the condition: If the variable i is smaller than the one I want to be the part of this code inside a div element with row class.
<text>

</text>

.Please advice,
       @{
    string path = System.Configuration.ConfigurationManager.AppSettings["ImageEdit"];
    int i = 0;
    }
    @foreach (var item in Model.PhotoTables)
    {
        if (i == 7)
        {
            i = 0;
        }
        if (i < 1)
        {
            @:

        }

        <text>

        </text>
        if (i < 1)
        {

            @:

            }

        i++;
    }

A: That
 above i++ looks suspiciously lonesome.
EDIT:
Now I think I understand, you want 7 text items each in each div row (with any remainder in the last row). Here's one of many ways..
@foreach (var item in Model.PhotoTables) {
  if (i < 1) {
    @:

  }
  <text>
    ...item...
  </text>
  i++;
  if (i == 7) {
    i = 0;
    @:

  }
}
if (i > 0) {
  @:

}

That produces this, if that's what you want..

   <text>..1..</text>
   <text>..2..</text>
   <text>..3..</text>
   <text>..4..</text>
   <text>..5..</text>
   <text>..6..</text>
   <text>..7..</text>

   <text>..8..</text>

A: If I am not wrong, you want to wrap text tag in
 when i < 1. So you can try this. It works for me.
@{
    string path = System.Configuration.ConfigurationManager.AppSettings["ImageEdit"];
    int i = 0;
}
    @foreach (var item in Model.PhotoTables)
    {
        if (i == 7)
        {
            i = 0;
        }
        if (i < 1)
        {

                <text>

                </text>

        }
        else
        {
            <text>

            </text>
        }

        i++;
    }

A: I think this will do the trick. use the modulus operator to find out if you are at the beginning or at the end of counting to 7 and if the items are not up to 7 the closing div will still be in place
    @{
string path = System.Configuration.ConfigurationManager.AppSettings["ImageEdit"];
int i = 0;
int modelCount = Model.PhotoTables.Count();
}
@foreach (var item in Model.PhotoTables)
{
    //if (i == 7)
   // {
    //    i = 0;
   // }
    if (i % 6 == 0)
    {
        @:

    }

    <text>

    </text>
    if (i % 6 == 5 || i == modelCount - 1)
    {

        @:

        }

    i++;
}


text:
Q: php replace paragraph to newline how to replace
hello

world
 to hello
world

I've tried searching on stack but there is no matched result.

A: You could do this by using str_replace() function.
For instance:
$string = "
hello

world
";
$string = str_replace('
', '', $string);
$string = str_replace('
', '
' , $string);

A: I try this myself and get what I expected
$pattern = '/
(\w+)\<\/p>/';
$subject = '
hello

world
';
$replacement = '${1}
';
$out = preg_replace($pattern, $replacement, $subject);

I just wonder which is better regex or str_replace
I wrote a better solution, hope everybody can see it helpful and maybe improve it
$pattern = '/
((.*?)+)\<\/p>/';
$replacement = '${2}
';
$subject = 'html string';
$out = preg_replace($pattern, $replacement, $subject);

A: Use this to prevent breaking the first and last

 :
$string = str_replace($string, '

', '');

But if a space comes between the tags, it won't work.

A: <?php
$str = '
hello

world
';
$replaceArr = array('
', '
', '

');
$replacementArr = array('', '', '
');
$str = str_replace($replaceArr, $replacementArr, $str);
echo $str;
?>

Try above code.


text:
Q: While creating an AMI the ansible_distribution_version for a specific OS the value should be picked dynamically instead of mentioning it manually Currently when we are creating an AMI in AWS using packer then we Read variables for detected OS from /vars/var_<linux-os>.yml files
example
- name: read variables for ubuntu 20.04
  include_vars: "vars_os_ubuntu-20.yml"
  when: ansible_distribution == "Ubuntu" and ansible_distribution_version == "20.04"

As you can see in the above code, we have specifically mentioned the Ubuntu version, now, if the version changes to 22.04 or let say 24.04, how can we set this value dynamically?
Is there any way where we can implement the same in Ansible?

A: You can use variables in the include_vars:
- name: >-
    Include variables for {{ ansible_distribution }}
    {{ ansible_distribution_version }}
  include_vars: >-
    vars_os_{{ ansible_distribution | lower }}-
    {{- ansible_distribution_version.split('.')[0] }}.yml

This would, in my Alpine container, give me, when running the playbook in verbose mode — so, with a -v flag:
TASK [Include variables for Alpine 3.15.4] ***********************************
ok: [localhost] => changed=false
  ansible_facts: {}
  ansible_included_var_files:
  - /usr/local/ansible/vars_os_alpine-3.yml

And so, as stated by the verbose message, include the file vars_os_alpine-3.yml, which match the pattern in your requirement.


text:
Q: Sparse approximate representation of a collection of vectors Suppose I have a collection of $n$ vectors $C \subset \mathbb{F}_2^n$. They are of course spanned by the canonical set of $n$ basis vectors.
What I would like to find is a much smaller (~ $\log n$) collection of basis vectors that span a collection of vectors which well approximate $C$. That is, I would like basis vectors $b_1,\ldots,b_k$ such that for every $v \in C$, there exists a $u \in span(b_1,\ldots,b_k)$ such that $||u-v||_1 \leq \epsilon$.
When is this possible? Is there a property that $C$ might posses to allow such a sparse approximation?

A: By triangle inequality, preserving the property you wish for means that you can find "representatives" for each $v$ so that the $\ell_1$ distances between any $v, v'$ are preserved to within 2$\epsilon$ additive error.
There is a general result by Brinkman and Charikar that says that in general, for a collection of $n$ vectors in an $\ell_1$ space, there's no way to construct a set of $n$ vectors in a smaller (e.g $\log n$) dimensional space) that preserves distances approximately even multiplicatively (let alone additively). This distinction is important if you have vectors in the original space that are $O(\epsilon)$ apart, but otherwise doesn't matter greatly.
Brinkman, B. and Charikar, M. 2005. On the impossibility of dimension reduction in l1. J. ACM 52, 5 (Sep. 2005), 766-788. DOI= http://doi.acm.org/10.1145/1089023.1089026
So I'm guessing that the answer to your first question should be no.


text:
Q: TS2345: Argument of type 'Role[]' is not assignable to parameter of type 'object[]' I am using Angular 8.
I am facing this 'Role[]' is not assignable to parameter of type 'object[]'
Did I implement the checkRoleExist and the allowedToAccess wrongly?
Role Enum class:
export enum Role {
  A = 'role-a',
  B = 'role-b',
  C = 'role-c',
  D = 'role-d',
  E = 'role-e',
}

I have a util class:
export function allowedToAccess(allowedRoles: object[], currentRoles: object[]) {
  let i: number;

  if (currentRoles === undefined || currentRoles === null || allowedRoles === undefined || allowedRoles === null) {
    return false;
  }
  console.log('allowedRoles:' + allowedRoles);
  console.log('currentRoles:' + currentRoles);

  allowedRoles.forEach(givenAllowedRoles => checkRoleExist(givenAllowedRoles, currentRoles))

  for(i = 0; i < allowedRoles.length; i++) {
    if (checkRoleExist(allowedRoles[i], currentRoles)) {
      return true;
    }
  }

  return false;
}

function checkRoleExist(allowedRoles: object, currentRoles: object[]) : boolean {

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.A, Role.B]
   */

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.A]
   */

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.E]
   */

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.A, Role.B, Role.F]
   */

  // check if allowedRoles is an array
  if (Array.isArray(allowedRoles)) {
    allowedRoles.forEach(allowedRole => {
      if (!currentRoles.includes(allowedRole)) {
        return false;
      }
    })

    return true;
  }

  // allowedRoles is an object
  return currentRoles.includes(allowedRoles);
}

In my header class:
export class HeaderComponent implements OnInit {
  ...

  constructor(
    ...
  ) {}

  ngOnInit() {
this.credentialsService.currentUserSubject.subscribe((u: User) => {
      const currentUserRoles: Role[] = u.role.slice();

      this.navigationlinks = [
        {
          id: 'library',
          label: 'library',
          index: 0,
          icon: '../assets/header/library.svg',
          disabledIcon: '../assets/header/library_disabled.svg',
          render: allowedToAccess([Role.A, Role.B], currentUserRoles),
          isActive: false,
          subLinks: [
...

Error log:
src/app/shell/header/header.component.ts:43:59 - error TS2322: Type 'Role.A' is not assignable to type 'object'.

43           render: allowedToAccess([Role.A, Role.B], currentUserRoles),


text:
Q: Limits and continuity of a derivative So I'm starting to learn about continuity and I'm having a slight problem. I've had a look around online but can't really find the explanation I'm looking for. I've been looking at the classic example of a derivative which is not continuous:
$$f(x) =
\begin{cases}
x^2\sin(\frac{1}{x}) & \quad x\ne0 \\
0 & \quad x=0
\end{cases}
$$
I understand the process of using limits to check that $f(x)$ is continuous and differentiable, how to get to the conclusion that $f'(0) = 0$, and that the $\lim\limits_{x \to 0} (-\cos(\frac{1}{x})+2x \sin(\frac{1}{x}))$ does not exist.
What I don't understand is that if $f'(x)$ has no limit as $x$ appoaches $0$, then how can it be the case that we can calculate that $f'(0) = 0$? How have we managed to calculate the derivative at a point of discontinuity? Is the limit of the difference quotient used only to determine that $f(x)$ has a derivative at $0$ and is this result completely overruled by the fact that we have calculated there is a discontinuity at $x=0$. I thought the point of a discontinuity was that you couldn't do things like come up with an expression for its derivative.

A: Using MVT, you can prove easily that if $ f $ is continuous at $ [a,b] $ and differentiable at $ (a,b] $ with $$\lim_{x\to a^+}f'(x)= L \in \Bbb R $$
Then, $ f $ is differentiable at $ [a,b] $ and
$$f'(a)=L$$
Your counterexample simply proves that the Converse is not always true.

A: Suppose the derivative were defined as
$$ f^\dagger(x) = \lim_{y,z \to x} \frac{f(y) - f(z)}{y-z} ,$$
then $f(x) = x^2 \sin(\frac1x)$ wouldn't be differentiable at $x = 0$.  That is, you could find a sequence of points $y_n,z_n \to 0$ such that the slope between these points oscillates.  You could do this, for example, by making the distance between $x_n$ and $y_n$ much smaller than the distance between $x_n$ and $0$.  I think this definition would have been very reasonable, but that wasn't the one they chose.
I think this picture illustrated what is happening.  See that there is a sequence of points going to zero such that the slope between those points is definitely not close to 0.  But the derivative at 0 definitely is zero.


text:
Q: setting and checking a 32 bit variable I am wondering if setting a 32 bit variable after checking it will be faster than just setting it? E.g. variable a is of uint32
if( a != 0)
{
    a = 0;
}

or
a = 0;

The code will be running in a loop which it will run many times so I want to reduce the time to run the code.
Note variable a will be 0 most of the time, so the question can possibly be shortened to if it is faster to check a 32 bit variable or to set it. Thank you in advance!
edit: Thank you all who commented on the question, I have created a for loop and tested both assigning and if-ing for 100 thousand times. It turns out assigning is faster.(54ms for if-ing and 44ms for assigning)

A: What you describe is called a "silent store" optimization.
PRO: unnecessary stores are avoided.
This can reduce pressure on the store to load forwarding buffers, a component of a modern out-of-order CPU that is quite expensive in hardware, and, as a result, is often undersized, and therefore a performance bottleneck. On Intel x86 CPUs there are performance Event Monitoring counters (EMON) that you can use to investigate whether this is a problem in your program.
Interestingly, it can also reduce the number of loads that your program does. First, SW: if the stores are not eliminated, the compiler may be unable to prove that the do not  write to the memory occupied by a different variable, the so-called address and pointer disambiguation problem, so the compiler may generate unnecessary reloads of such possibly but not actually conflicting memory locations. Eliminate the stores, some of these loDs may also be eliminated. Second, HW: most modern CPUs have store to load dependency predictors: fewer stores increase accuracy. If a dependency is predicted, the load may actually not be performed by hardware, and maybe converted into a register to register move. This was the subject of the recent patent lawsuits that the University of Wisconsin asserted against Intel and Apple, with awards exceeding hundreds of millions of dollars.
But the most important Reason to eliminate the unnecessary stores is to avoid unnecessarily dirtying the cache. A dirty cache line eventually has to be written to memory, even if unchanged.  Wasting power. In many systems it will eventually be written to flash or SSD, wasting power and consuming the limited write cycles of the device.
These considerations have motivated academic research in silent stores, such as http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.28.8947&rep=rep1&type=pdf. However, a quick google scholar search shows these papers are mainly 2000-2004, and I am aware of no modern CPUs implementing true silent store elimination - actually having hardware read the old value. I suspect, however, that this lack of deployment of silent stores us mainly because CPU design went on pause for more than a decade, as focus changed from desktop PCs to cell phones. Now that cell phones are almost caught up to the sophistication of 2000-era desktop CPUs, it may arise again.
CON: Eliminating the silent store in software takes more instructions. Worse, it takes a branch. If the branch is not very predictable, the resulting branch mispredictions will consume any savings. Some machines have instructions that allow you to eliminate such stores without a branch: eg Intel's LRBNI vector store instructions with a conditional vector mask. I believe AVX has these instructions. If you or your compiler can use such instructions, then the cost is just the load of the old value and a vector compare  if the old value is already in a register, then just the compare.
By the way, you can get some benefit without completely eliminating the store, but by redirecting it to a safe address. Instead if
If a[i] != 0 then a[i] := 0
Do
ptr = a+I; if *ptr == 0 then ptr.:= &safe; *ptr:=0
Still doing the store, but not dirtying so many cache lines. I have used this way if faking a conditional store instruction a lot. It is very unlikely that a compiler will do this sort of optimization.
So, unfortunately, the answer is "it depends".  If you are on a vector mask machine or a GPU, and the silent stores are very common, like, more than 30%, worth thinking about. If in scalar code, probably need more like 90% silent.
Ideally, measure it yourself. Although it can be hard to make realistic measurements.
I would start with what is probably the best case for thus optimization:
char a[1024*1024*1024]; // zero filled
const int cachelinesize = 64;
for(char*p=a; p

Every store is eliminated here - mAke sure that the compiler still emits them. Good branch prediction, etc
If this limit case shows no benefit, your realistic code is unlikely to.
Come to think if it, I ran such a benchmark back in the last century.  The silent store code was 2x faster, since totally memory bound, and the silent stores generate no dirty cache lines on a write back cache. Recheck thus, and then try on more realistic workload.
But first, measure whether you are memory bottlenecked or not.

By the way: if hardware implementations of silent store elimination become common, then you will never want to do it in software.
But at the moment I am aware of no hardware implementations of silent store elimination in commercially available CPUs.
As ECC becomes more common, silent store elimination becomes almost free - since you have to read the old bytes anyway to recalculate ECC in many cases.

A: The assignment would do you better as firstly the if statement is redundant and it would make it clearer if you omitted it, also the assignment only should be faster and even if you are not quite sure of it you can just create a simple function to test it with and without the if statement.


text:
Q: Vapor MySQL - not showing as an Import value This question is about the Swift Web Framework, Vapor.
I am trying to import VaporMySQL framework using Swift's Package Manager.
I already have the database running locally, the mySQL port is open & working, the mySQL database is working, the Vapor app is working [I have written several GET / POST requests that work].
But I can't Import VaporMySQL.  This may be related to my lack of knowledge with Package.swift.
    let package = Package(
    name: "HelloWorld",
    dependencies: [
    .Package(url: "https://github.com/qutheory/vapor.git", majorVersion: 0, minor: 10),
    .Package(url: "https://github.com/qutheory/cmysql.git", majorVersion: 0, minor: 2)

A: The VaporMySQL package comes from the qutheory/vapor-mysql repository.
It looks like you've mistakenly included the libmysql wrapper into your project which just provides a module map for MySQL's C library.
let package = Package(
    name: "HelloWorld",
    dependencies: [
        .Package(url: "https://github.com/qutheory/vapor.git", majorVersion: x, minor: x),
        .Package(url: "https://github.com/qutheory/vapor-mysql.git", majorVersion: x, minor: x)
    ]
)

Your Package.swift file should look like the above. The major and minor version numbers will need to be determined based on which version of Swift and Vapor you want to use.


text:
Q: Ionic app Run time error - Didn't find class com.vladstirbu.cordova.plugin.utils.AssetProvider I am getting the following error when I try to run an ionic android application.
java.lang.RuntimeException: Unable to get provider com.vladstirbu.cordova.plugin.utils.AssetProvider: java.lang.ClassNotFoundException: Didn't find class "com.vladstirbu.cordova.plugin.utils.AssetProvider"

The app has been builded successfully and no error when installing it. But it is crashing when I try to open the app.
Can anyone please help me to solve the issue here?

A: It appears to be an issue with the recent 0.5.6 release of InstagramPlugin !
ionic cordova plugin remove cordova-instagram-plugin
ionic cordova plugin add cordova-instagram-plugin@0.5.5
ionic cordova run android

I compiled with 0.5.5 and did not encounter this issue!

A: Same problem here!

*

*ionic 3.20.0

*cordova 8.0.0

*OS: Mac OS X 10.13.4


text:
Q: using break in ternary/operator expression giving "Expected Output" I created a function for getting last child element using TypeScript.
If I use normal if/else typescript not raising any error.
function lastChildElement(element: HTMLElement) {
  let lastChild = element.lastChild

  while (lastChild && lastChild.nodeType != 1) {
    if (lastChild.previousSibling) {
      lastChild = lastChild.previousSibling
    } else {
      break
    }
  }

  return lastChild
}

but when using ternary/conditional expression
function lastChildElement(element: HTMLElement) {
  let lastChild = element.lastChild

  while (lastChild && lastChild.nodeType != 1) {
    lastChild.previousSibling ? lastChild = lastChild.previousSibling : break
  }

  return lastChild
}

typescript underlining break keyword and raising Expression expected.

A: The conditional operator evaluates to a value. That is, if you have
someExpression ? someOtherExpression : yetAnotherExpression

The entire thing will then evaluate to either someOtherExpression or yetAnotherExpression.
But break is not a value - it's not an expression - it's a statement that can't be evaluated as anything, so it's not permitted in the context where an expression is expected.
For similar reasons, you can't do:
while (someCondition) {
  const something = break;
  // ...

which just doesn't make sense.
Use if/else, so that you can break as a standalone statement if needed.
That said, a better alternative to iterating through all children is to select the last element child directly.
const lastChildElement = (element: HTMLElement) => element.lastElementChild;

No loops needed.


text:
Q: Image View is not Appearing in widget @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

    // Get all ids
    ComponentName thisWidget = new ComponentName(context,
            MyWidgetProvider.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    for (int widgetId : allWidgetIds) {

        mRemoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget_layout);
        mRemoteViews.setImageViewResource(R.id.photo, R.drawable.photo1);

        // Register an onClickListener
        Intent intent = new Intent(context, MyWidget.class);

        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, mRemoteViews);

    }

A: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dip"
    android:orientation="vertical"
     >

    <ImageView
        android:id="@+id/photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/photo1"/>

</LinearLayout>

try using this as your layout i have checked its working properly.
and make it this file as your app widget provider keep it in res/xml/ directrory

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/widget_layout"
    android:minHeight="72dp"
    android:minWidth="300dp"
    android:updatePeriodMillis="300"
    android:widgetCategory="keyguard|home_screen" >

</appwidget-provider>


text:
Q: Carousel : Y-axis with numbers not displayed on slide change I have added charts onto carousel, problem is charts does not show y-axis with numbers, it shows only on load, on slide change it`s not displaying, I tried changing colors, reduced width, but not coming at all.
HTML Complete code:
<!DOCTYPE html>

    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />

    <link rel='icon' type='Icon.ico' href='Icon.ico' />

Carousel Example

          Previous

          Next

Charts should be displayed with y-axis values even on slide change too.

A: cannot draw charts in a hidden container.
the chart cannot properly calculate the placement of all the chart elements.
need to wait until the chart is shown before drawing for the first time...
first, only need to draw the first chart when the page is first displayed.
remove the following lines (assuming GoogleColChart_0 is shown first by default)...
google.charts.setOnLoadCallback(function () { drawChart(80, 10, 'GoogleColChart_1'); });
google.charts.setOnLoadCallback(function () { drawChart(90, 15, 'GoogleColChart_2'); });

next, remove the

    <link rel='icon' type='Icon.ico' href='Icon.ico' />

Carousel Example

          Previous

          Next


text:
Q: Remove brackets in Sweave output I want to know if there is a way to print R object directly in a text (Sweave), but directly in a line of text.
I'd like to print this code
\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}

YO MANNNNNNN 2+2 =
<<here, results=tex, echo=FALSE>>=
2+2
@
YEAHHHH!

\end{document}

And I want an output similar to this:
YO MANNNNNNN 2+2 = 4 YEAHHHH!

But, R is adding the answer brackets like this
YO MANNNNNNN 2+2 = [1] 4YEAHHHH!

A: Code:
\documentclass{article}

\begin{document}
% \SweaveOpts{concordance=TRUE}

YO MANNNNNNN 2+2 = \Sexpr{2+2} YEAHHHH!

\end{document}

n.b. For me commenting out \SweaveOpts{concordance=TRUE} worked just fine, but you made need to uncomment depending on your setup.
Prints:
YO MANNNNNNN 2+2 = 4 YEAHHHH!

Update - extra info per comment...
You can define an object within a 'chunk' to be later evaluated in line using \Sexpr{}
<<somechunk, results='tex',echo=FALSE, results='hide'>>=
x <- 2
@

Inline evaluation of x prints the number \Sexpr{x}.


text:
Q: Slow transfer speed of 4mbps on a Seagate Central 3TB NAS I have a Seagate Central 3TB NAS which is returning very slow file transfer speeds of just 4mbps.
My router is a Buffalo Airstation WHR-G300N and is showing 300mbps connection speed. It is in N (2.4GHz) mode only with 40MHz channel width.
My laptop's wireless card is limiting my connection speed to 65mbps but I would expect to be able to achieve a transfer speed higher than 4Mbps.
Is there anything else I can check/change? The review sites I've seen claim to have achieved more than 20mbps write speed and I'd be happy with that!

A: Unfortunately, that speed is quite close to what I get in a similar wireless setup. The theoretical max would be (65/8) megabytes/second, and network overhead takes care of the remaining difference.


text:
Q: Cannot access radtextbox inside radDock from child Here is my radTextBox inside radDock , I set this in my ParentPage
   <telerik:RadDockZone ID="ZoneDescription" runat="server" BorderStyle="None" Width="600px">
                <telerik:RadDock ID="DockDescription" runat="server" EnableDrag="false" EnableRoundedCorners="true"
                    Title="Itinerary Description" Width="600px" Skin="Vista" DefaultCommands="None">
                    <ContentTemplate>
                        <div style="padding-top: 5px;">
                            <telerik:RadTextBox ID="rtxtDescription" runat="server" Width="100%" TextMode="MultiLine">
                            </telerik:RadTextBox>
                        </div>
                    </ContentTemplate>
                </telerik:RadDock>
            </telerik:RadDockZone>

From my child Page , I get rtxtDescription's text value likes ,
 (((this.Parent.FindControl("ZoneDescription") as RadDockZone).
 FindControl("DockDescription") as RadDock).
 FindControl("rtxtDescription") as RadTextBox).Text;

and
(this.Parent.FindControl("rtxtDescription") as RadTextBox).Text;

But both doesn't work , cannot access rtxtDescription .
How can I solve it ? Thanks in advance :)

A: Please try with the below code snippet.
((ZoneDescription.FindControl("DockDescription") as RadDock).ContentContainer.FindControl("rtxtDescription") as RadTextBox).Text = "Your text here";


text:
Q: Why telegram bot don't work if participants left group or new one add to group? When I run my app and someone in group left or new participant add to group, my bot stop working.
Below you can see code of my app:

const TelegramBot = require('node-telegram-bot-api');

const token = '1928095766:AAGf5aU7E1_FAM_fWzQs3SSGy-1AJS0DjcY';

const bot = new TelegramBot(token, { polling: true });

bot.on('message', async msg => {
                const reg = /\d\d\-\d\d$/;
                if (msg.text.match(reg)) {
                    bot.sendMessage(msg.chat.id, 'Gh')
                }

})

And what I received in terminal if someone left group or new one add into, when my app is running:

(node:21155) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'match' of undefined
    at TelegramBot.<anonymous> (/Users/romansavka/Telegram-Bot-Node/telegram-bot/reminder.js:11:30)
    at TelegramBot.emit (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/eventemitter3/index.js:182:35)
    at TelegramBot.processUpdate (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/node-telegram-bot-api/src/telegram.js:634:12)
    at /Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/node-telegram-bot-api/src/telegramPolling.js:110:22
    at Array.forEach (<anonymous>)
    at /Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/node-telegram-bot-api/src/telegramPolling.js:106:17
    at tryCatcher (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/promise.js:547:31)
    at Promise._settlePromise (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/promise.js:604:18)
    at Promise._settlePromise0 (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/promise.js:649:10)
    at Promise._settlePromises (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/promise.js:729:18)
    at _drainQueueStep (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/async.js:93:12)
    at _drainQueue (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/async.js:86:9)
    at Async._drainQueues (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/async.js:102:5)
    at Immediate.Async.drainQueues (/Users/romansavka/Telegram-Bot-Node/telegram-bot/node_modules/bluebird/js/release/async.js:15:14)
    at processImmediate (internal/timers.js:462:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:21155) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:21155) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

A: It's because the message received has no attribute text, so the error raised UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'match' of undefined


text:
Q: Update UI constraints in Xcode 8 for a specific device As you can see on the image below my View Controller is packed with labels, everything looks good on iPhone SE but not on a larger screen phone. Is it possible to increase space between UI elements on iPhone 6,7,+ but keep same on SE without implementing Scroll View?

A: You can use Stack View, it will automatically set space for every device. Embed labels in stack view (Editor -> Embed In -> Stack View) and choose Distribution property that works for you ("Fill Equally" or maybe "Equal Spacing"). You can embed any view - also stack view (so you can have 12 stack views with label and result and embed them in external stack view for proper row spacing).


text:
Q: CSS clean animation repeat I have an animation using keyframes in CSS
I would like to perform the animation everytime I call a function animate() which adds a class with the animation keyframes
So I looked around and found I have to clear the class using webkitTranstionEnd, But that would mean I also need to write something for Mozilla, Opera.. Is there a cleaner way to perform a keyframe animation every time I call a function?

A: I would strongly recommend to use a javascript framework like jQuery (or any other) which is supposed to be cross browser compliant.


text:
Q: Create a singlepart polygon with several polygons in QGIS I would like to create one polygon including others polygons that has an ID < 16 .

The yellow polygons have ID < 16 and I would like to create a polygon like this:

EDIT : I do not want to get a multipart polygon, but a singlepart polygon and fill the spaces in between.
Probably not a good idea, but polygons being always alligned by ascendant numbering (  1 - 2 - 3 - 4 - ...) , a logics could be to join polygon ID 1 to the polygon ID 2, then the polygon ID 2 to the polygon ID 3, etc. by joinning the closest corners to the next ID polygon.
I've no idea how to accomplish this task, is there a way to automatize it?
EDIT :
the aim is to have only one polygon at the end

A: *

*Select by expression with the expression ID < 16

*Merge Selected Features

To further proceed to fill the space between the parts of the merged polygon to get a contiguous single-part polygon, you can use concave hull:

*Extract vertices (you might use this with Selected features only, then you can skip step 2 from above).

*Run Menu Processing > Toolbox > Concave Hull (alpha shapes) on the vertices layer. Set an appropriate value for Threshold - in my case, 0.14 produced the result shown below.
The pink polygon represents the output of Concave Hull (alpha shapes):


text:
Q: sprite kit: verify if touch is inside a node I'm trying to figure out how to detect if I touch a node in sprite kit. I thought it was function like this in UIView:
[myView pointInside:point withEvent:nil];

But so far I can not have found an alternative to this. What I'm trying to accomplish is to know I have touch the sprite node in the screen.
I'll really appreciate if you can help me to I acomplish this
Here is what I have in my code. I'm adding animated node:
-(void)addMyNodeAnimated
{
    NSMutableArray *myNodeArray = [NSMutableArray array];
    NSArray *animatedFrames = [NSArray new];
    SKTextureAtlas *AnimatedAtlas = [SKTextureAtlas atlasNamed:@"pc2"];
    int numImages = (int)AnimatedAtlas.textureNames.count;

    for (int i=1; i <= numImages; i++) {
        NSString *textureName = [NSString stringWithFormat:@"%@-%d", @"pc2", i];
        SKTexture *temp = [AnimatedAtlas textureNamed:textureName];
        [myNodeArray addObject:temp];
    }
    animatedFrames = myNodeArray;

    SKTexture *temp = animatedFrames[0];
    SKSpriteNode *animationNode = [SKSpriteNode spriteNodeWithTexture:temp];
    animationNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    animationNode.userInteractionEnabled = YES;
    animationNode.name = @"AnimationNode";
    [self addChild:animationNode];

    [animationNode runAction:[SKAction repeatActionForever:
                                  [SKAction animateWithTextures:animatedFrames
                                                   timePerFrame:0.1f
                                                         resize:NO
                                                        restore:YES]] withKey:@"AnimationRuning"];

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint _touchLocation = [[touches anyObject] locationInNode:self];

     SKNode *node = [self nodeAtPoint:_touchLocation];

    if (node != nil)
    {
        NSLog(@"node name %@", node.name);
    }

}

When I touch the node in the screen the node returns null.
Any of know why is this?

A: -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];
    if ([node.name isEqualToString:@"yourSpriteName"] && [node.name isEqualToString:@"yourEffectName"]) {
        //Whatever you want.
    }
}


text:
Q: Не работает массовое выделение флажков на jquery Здравствуйте!
Помогите разобраться, почему в найденном мною примере не работает выделение флажков:
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
    $(document).ready( function() {
       $("#maincheck").click( function() {
            if($('#maincheck').attr('checked')){
                $('.mc').attr('checked', true);
            } else {
                $('.mc').attr('checked', false);
            }
       });
    });
</script>
<input type="checkbox" name="numbers[]" class="mc" value="0" />
<input type="checkbox" name="numbers[]" class="mc" value="1" />
<input type="checkbox" name="numbers[]" class="mc" value="2" />
<input type="checkbox" name="numbers[]" class="mc" value="3" />
<input type="checkbox" name="numbers[]" class="mc" value="4" />
<input type="checkbox" name="numbers[]" class="mc" value="5" />
<input type="checkbox" name="numbers[]" class="mc" value="6" />
<input type="checkbox" name="numbers[]" class="mc" value="7" />
<input type="checkbox" name="numbers[]" class="mc" value="8" />
<input type="checkbox" name="numbers[]" class="mc" value="9" />

<br /><input type="checkbox" name="maincheck" id="maincheck" />

Задача: выделять все флажки по классу .mc, если флажок стоит у #maincheck. Снятие флажков работает, а выделение почему-то нет(
Подозреваю, что функция на снятие у последней версии jquery изменилась, а этот код был написан неизвестно когда. Помогите, плиз.
A: Не attr, а prop используйте.
 $(document).ready( function() {
       $("#maincheck").click( function() {
            if($('#maincheck').prop('checked')){
                $('.mc').prop('checked', true);
            } else {
                $('.mc').prop('checked', false);
            }
       });
       //Добавлено
       $('.mc').click(function(){
         if($('.mc:not(:checked)').length==0){
            $('#maincheck').prop('checked',true);
         }else{
            $('#maincheck').prop('checked',false);
         }
       });

    });

http://jsfiddle.net/atcjjbqw/
P.S. Хотя в некоторых браузерах и attr работатет, его использование тут не совсем корректно.


text:
Q: Why cannot use if statement in AppDelegate?
why I cannot pass the constant in if statement?
 if UIDevice.current.orientation.isLandscape{
        let storyboard = UIStoryboard(name: "landscape", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "landscape")
    }else{
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewController")
    }

    self.window?.rootViewController = initialViewController

A: You need to insert the error line inside the if else block as of scope
if {
  let initialViewController = ////
  self.window?.rootViewController = initialViewController
}
else {
  let initialViewController = ////
  self.window?.rootViewController = initialViewController
}

OR
var initialViewController:UIViewController!
if {
  initialViewController = ////
}
else {
  initialViewController = ////
}
// use it here

A: The initialViewController is only available within the scope of the if else block so you need to declare the initialViewController before the if else block begin and set initialViewController property within the block and later use it as required.
let initialViewController: UIViewController
if UIDevice.current.orientation.isLandscape {
    let storyboard = UIStoryboard(name: "landscape", bundle: nil)
    initialViewController = storyboard.instantiateViewController(withIdentifier: "landscape")
} else {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewController")
}
window?.rootViewController = initialViewController

Note: You should probably do more research on scope in programming.

A: Look carefully at the error Swift is reporting: it's unable to find the variable with the name initialViewController in this part of the code.
Variables are only available in the scope of the block in which they are created. In other words, you need to lift the initialViewController declaration out of the if statement if you want to use it somewhere else outside of the if statement. You can do this by making it a var instead:
// Let Swift know that we're going to make this a UIViewController
var initialViewController: UIViewController
if condition {
  // Now, initialViewController has been instantiated; it just needs a value
  initialViewController = storyboard.instantiateViewController(withIdentifier: "landscape")
} else {
  initialViewController = storyboard.instantiateViewController(withIdentifier: "portrait")
}

// We can safely use it outside of the if statement, but it may need unwrapping since it was declared as a var
self.window?.rootViewController = initialViewController!

Note that copy/pasting this exact code won't work since I haven't defined the storyboard or condition variables: see if you can change your current code to fix the issue the way I've described here!


text:
Q: Cordova + Vue.js : Block-scoped declarations (let, const, function, class) not yet supported outside strict mode I'm buiding mobile app using Cordova + Vue.js
I'm facing this issue :Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
When building for browser (cordova build browser + cordova run browser), it works perfectly as expected
When building for Android (cordova build android + cordova run android), build is sucessfull but when I launch it on my device, Vue components are not displayed at all (there are no errors in the app).
However, HTML tags like < p > are correctly displayed.
When inspecting with Chrome Devtools, I'm facing this in the error log :
bundle.js:4917 Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
Bundle.js is an auto generated file so I should not modify it
Node version : v10.3.0
npm version : 6.1.0
Device Android Version : 5.0.1
If someone can help me, don't hesitate


text:
Q: Proving if $f$ is differentiable at 0 when f(0) = 0 Suppose that we have a function $f$ that $f(0)=0$ and for any $x$,
$$|f(x)|>=\sqrt{|x|}$$
How could we prove that $f(x)$ is differentiable at zero or not?
P. S. My first attempt was to prove something like a discontinuity for $f$ at zero that not being differentiable would be quickly implied from it, but haven't reached to anything interesting. However, any solution is acceptable.

A: Hint :
\begin{align*}
\left| f(x) \right| \geq \sqrt{\left|x\right|} &\Leftrightarrow \left| f(x)\right| - \left| f(0)\right| \geq \sqrt{\left| x\right|} - \left|f(0)\right| \\ &\Leftrightarrow \frac{\left|f(x)\right| - \left|f(0)\right|}{\left|x\right|-0} \geq \frac{\sqrt{\left|x\right|} - \left|f(0)\right|}{\left|x\right|-0} \\ &= \frac{\left|f(x)\right|}{\left|x\right|} \geq \frac{\sqrt{\left|x\right|}}{\left|x\right|} \\ &= \frac{\left|f(x)\right|}{\left|x\right|} \geq \frac{1}{\sqrt{\left|x\right|}}
\end{align*}

A: Suppose $f'(0)$ exists. Call $l$. There exists $\delta$ such that $|\frac {f(x)-f(0)} x-l|<\epsilon$ for $|x| <\delta$. Hence $\frac {|f(x)|} {|x|} <|l|+\epsilon$ for $|x| <\delta$. This implies $1 <\sqrt |x| (|l|+\epsilon)$ for  $|x| <\delta$. You get a contradiction by letting $x \to 0$


text:
Q: How use Rminer and nnet I'm new programmer in R and i'm writing my thesis for training a neural network.
First i use rminer for datamining and after nnet for training.
Now i don't know which function use for divide data-set in training set and validation set, therefore k-fold cross validation, and after use nnet for each of this.
sorry for my english.
Thanks in advance

A: Here is a way to get help on a new topic / package in R when you don't know how to go about it:
library(help=package.name)

This will give you an overview of all the functions and data sets defined in the language with a brief title of each. After you have identified the functions that you need, you can consult the documentation of the functions of interest like so:
?function.name

In the documentation, also pay attention to the See Also section which typically lists functions that are useful in conjunction with the function being considered. Also, work the examples. You can also use
example(function.name)

for a demonstration of the function's use and common idioms using it.
Lastly, if you are lucky, the package author may have written a vignette for the package. You can search for all vignettes in a package like this:
vignette(package="package.name")

Hopefully, this will get you started with the rminer and nnet packages.

A: It's maybe too late, but I found this Q while I was looking for an answer to my Q.
You can use something like this
    # Splitting in training, Cross-Validation and test datasets
        #The entire dataset has 100% of the observations. The training dataset will have 60%, the Cross-Validation (CV) will have 20% and the testing dataset will have 20%.
        train_ind <- sample(seq_len(nrow(DF.mergedPredModels)), size = floor(0.6 * nrow(DF.mergedPredModels)))
        trainDF.mergedPredModels <- DF.mergedPredModels[train_ind, ]

        # The CV and testing datasets' observations will be built from the observations from the initial dataset excepting the ones from the training dataset
        # Cross-Validation dataset
        # The CV's number of observations can be changed simply by changing "0.5" to a fraction of your choice but the CV and testing dataset's fractions must add up to 1.
        cvDF.mergedPredModels <- DF.mergedPredModels[-train_ind, ][sample(seq_len(nrow(DF.mergedPredModels[-train_ind, ])), size = floor(0.5 * nrow(DF.mergedPredModels[-train_ind, ]))),]

        # Testing dataset
        testDF.mergedPredModels <- DF.mergedPredModels[-train_ind, ][-sample(seq_len(nrow(DF.mergedPredModels[-train_ind, ])), size = floor(0.5 * nrow(DF.mergedPredModels[-train_ind, ]))),]

        #temporal data and other will be added after the predictions are made because I don't need the models to be built on the dates. Additionally, you can add these columns to the training, CV and testing datasets and plot the real values of your predicted parameter and the respective predicitons over your time variables (half-hour, hour, day, week, month, quarter, season, year, etc.).
        # aa = Explicitly specify the columns to be used in the temporal datasets
        aa <- c("date", "period", "publish_date", "quarter", "month", "Season")
        temporaltrainDF.mergedPredModels <- trainDF.mergedPredModels[, c(aa)]
        temporalcvDF.mergedPredModels <- cvDF.mergedPredModels[, c(aa)]
        temporaltestDF.mergedPredModels <- testDF.mergedPredModels[, c(aa)]

        # bb = Explicitly specify the columns to be used in the training, CV and testing datasets
        bb <- c("quarter", "month", "Season", "period", "temp.mean", "wind_speed.mean", "solar_radiation", "realValue")
        trainDF.mergedPredModels.Orig <- trainDF.mergedPredModels[, c(bb)]
        trainDF.mergedPredModels <- trainDF.mergedPredModels[, c(bb)]
        smalltrainDF.mergedPredModels.Orig <- trainDF.mergedPredModels.Orig[1:10,] #see if the models converge without errors
        cvDF.mergedPredModels <- cvDF.mergedPredModels[, c(bb)]
        testDF.mergedPredModels <- testDF.mergedPredModels[, c(bb)]
# /Splitting in training, Cross-Validation and test datasets


text:
Q: What is the probability that Miss Lear wins exactly 3 of these matches? Miss Lear plays Miss Gill at chess.  The probability that Miss Lear wins a match is 0.6. Miss Lear and Miss Gill play $5$ matches against each other. What is the probability that Miss Lear wins exactly $3$ of these matches?
I make the answer to be $0.6^3 = 0.216$.
or should it be $0.6^3\times0.4^2$?

A: The first answer, $0.6^3$, is the probability that Lear wins the first three matches. And it's the probability that she wins the last three matches. For any subset $\{i,j,k\}\subseteq\{1,2,3,4,5\}$, $0.6^3$ is the probability that Lear wins matches $i,j$ and $k$ (with no limits on what happens on the rest of the matches). So this is not the right answer.
The second answer, $0.6^30.4^2$, is the probability that Lear wins the first three matches and loses the second two matches. This is closer, but you are still not quite there, because Lear might also win matches number $2,3,5$ and lose matches $1$ and $4$. So again, this is not the right answer.

To get the right answer, you need to modify your second result. Think about all the possibilities in which Lear wins exactly three matches. How many are there? What are their probabilities?


text:
Q: Multiple WebResources output to html when using recursive server controls I have created a server control which uses recursion to create a menu. It essentially outputs nested lists with anchors inside them.
Now, this works perfectly, however, since the control is calling itself to render the child menus, it is also rendering multiple identical WebResource.axd javascript file references in .
Any idea how to stop this from happening? I just want the one reference in my  tag.

A: I ended up solving my own problem by making a private constructor of the form:
private CustomControl(int level)
{
  this._Level = level + 1;
}

The public constructor looked like:
public CustomControl() : base()
{
  _Level = 1;
}

Then, when outputting the client scripts in the OnInit method, I checked whether _Level == 1, only outputting the client scripts if _Level == 1, like so:
protected override void OnInit(EventArgs e)
{
  base.OnInit(e);

  if(_Level == 1)
  {
    // Add client scripts to this.Page.Header.Controls
  }
}

I'm not sure if this was the best way, but it worked for me.


text:
Q: A java practice problem I came across this problem in javabat(http://www.javabat.com/prob/p183562):

We want to make a row of bricks that
  is goal inches long. We have a number
  of small bricks (1 inch each) and big
  bricks (5 inches each). Return true if
  it is possible to make the goal by
  choosing from the given bricks. This
  is a little harder than it looks and
  can be done without any loops.
makeBricks(3, 1, 8) → true
  makeBricks(3, 1, 9) → false
  makeBricks(3, 2, 10) → true

I came up with this solution:
public boolean makeBricks(int small, int big, int goal) {
    if (goal > small + big * 5)
        return false;
    else if (goal % 5 == 0)
        return goal / 5 <= big;
    else
        return goal % 5 <= small;
}

This passed the test. But I found a counter-example myself: makeBricks(10, 0, 10) -> true. My logic will return false. How should I fix my logic? Or is there a better way to do this?

A: The second test is entirely unnecessary.  The first one checks to see that you have enough total length, and all is good.
But the second one again checks if you have enough total length (return goal / 5 <= big;) but this ignores the length added by small bricks.  The issue is you are checking if it is a multiple of 5, and automatically assuming that you are going to use only large bricks if it is.  In reality, you could use five small bricks instead. (or, as in your example, 10 small bricks.)  The last check is correct, testing if you have enough granularity to get the right length, assuming you have enough length.

A: I think you can just remove your second test. I would try this:
public boolean makeBricks(int small, int big, int goal) {
    if (goal > small + big * 5)
        return false;
    else
        return goal % 5 <= small;
}

The first test just checks how long the row would be if we just put all the bricks in a row. If that's not as long as the goal, then we know that it's impossible.
Next, we calculate the minimum number of small bricks: goal % 5. For example, if the goal is 8 and we have 1000 large bricks, how many small bricks do we need? 8 % 5 is 3, so we need 3 small bricks at the end of the row.
If we have enough small bricks, and the total length of all the bricks is enough, then we can meet the goal.

A: Your logic is incorrect. This should do it:
public boolean makeBricks(int small, int big, int goal) {
  if (goal < 0 || big < 0 || small < 0) {
    throw new IllegalArgumentException();
  } else if (goal > big * 5 + small) {
    return false;
  } else if (goal % 5 <= small) {
    return true;
  } else {
    return false;
  }
}

is sufficient. This can be simplified to:
public boolean makeBricks(int small, int big, int goal) {
  if (goal < 0 || big < 0 || small < 0) {
    throw new IllegalArgumentException();
  } else {
    return goal <= big * 5 + small && goal % 5 <= small;
  }
}

Of course, the sanity check on negative goal, small or big is not strictly required but recommended. Without those checks, the result can simply be obtained by:
public boolean makeBricks(int small, int big, int goal) {
  return goal <= big * 5 + small && goal % 5 <= small;
}

A: it's returning false because your second check is only comparing it to the bigs, which in your counter example you have zero of.
so 2<=0 is false.
here's a good way to do it:
return (Math.min(goal/5,big)*5 + small) >= goal;

This way you're sure to use only as many large bricks as you need, but no more, guaranteeing that the only way to reach the goal is if you have enough small bricks.

A: I tried some other scenarios: "makeBricks(8, 1, 13)" "makeBricks(1, 2, 6)" where either you have not enough or too many big bricks, but you need some.  To account for both possibilities You would need something like:
public boolean makeBricks(int small, int big, int goal) {
  /* Not enough bricks to make the goal so don't bother */
  if (goal > small + big * 5)
     return false;

  /* How many big bricks can we use */
  int bigBricksToUse = Math.min(big, (goal / 5) );

  /* If we use that many bigs, do we have enough small */
  return goal - (bigBricksToUse * 5) <= small;
 }

A: This is my answer.
private static boolean makeBricks (int small, int big, int goal) {

    return ((big * 5 + small) >= goal) && (goal % big <= small);
}

A: private boolean makeBricks (int small, int big, int goal) {
    return !(big*5 + small < goal || small < goal%5);
}

Uses only boolean operators to check for the absence of both failure cases !(fail || fail). The obvious, not enough bricks to make the goal big*5 + small < goal. The less obvious, not enough small bricks when goal is not an even multiple of 5 small < goal%5.

A: public class Bricks {
public boolean checkMethod(int small, int big, int goal) {
    if (goal <= small + big * 5 && goal >= big * 5) {
        return true;
    } else
        return false;
}

public static void main(String args[]) {
    Bricks brick = new Bricks();
    System.out.println(brick.checkMethod(10, 0, 10));
}

}

A: private boolean  makeBricks(int small, int big, int goal)
{
    if (goal < 0 || big < 0 || small < 0)
    {
        throw new IllegalArgumentException();
    }
    else return goal - (5 * big + small) <= 0;
}

This is it. That's how it is done.

A: Here's the perfect solution:
public static boolean makeBricks(int small, int big, int goal) {

    int totalInches = small + big*5;
    if(totalInches < goal){
        return false;
    }

    int bigInches= big*5;
    int smallRequired = goal %5;

    if(smallRequired > small && bigInches != goal){
        return false;
    }else if(smallRequired <=small){
        if( bigInches >= goal || smallRequired + bigInches == goal || small +bigInches ==goal
                || small+ bigInches == goal){
            return true;
        }if(bigInches + small > goal){
            if(small > goal-bigInches){
                return true;
            }
        }

    }
    return false;
}

A: Probably no perfect solution, but perhaps a bit more understandable than the previous ones:
public boolean makeBricks(int small, int big, int goal) {
    //not testing for invalid input - no invalid input from codingbat.com (in this case)

    int obviousDemandSmall = goal%5;
    if (obviousDemandSmall>small) return false;

    boolean needSmallToMakeUpForBig = (goal/5>big) ? true : false;
    if (!needSmallToMakeUpForBig) return true;

    int superfluousSmallFromFirstGlance = small-obviousDemandSmall;
    int extraSmallCanMakeThisManyBig = superfluousSmallFromFirstGlance/5;
    int missingBig = goal/5-big;
    if (extraSmallCanMakeThisManyBig>=missingBig) return true;

    return false;
}

A: if (goal < 0 || big < 0 || small < 0) {
            throw new IllegalArgumentException();
        } else {
            int reqBig = goal / 5;
            int reqSamll = goal % 5;

            if (reqBig <= big && reqSamll <= small)
                return true;
            else if (reqBig > big) {
                int remainingLen = goal - (big * 5);
                if (remainingLen <= small)
                    return true;
                else
                    return false;
            } else
                return false;
        }

A: Also you can try this:
public boolean makeBricks(int small, int big, int goal) {
return goal - big * 5 <= small
        && goal % 5 <= small;
}

A: This is quite short and easy solution I've used when solving codingbat issue:
public boolean makeBricks(int small, int big, int goal) {

// first we check if we have enough bricks to reach the goal

 if ((small + big * 5) >= goal) {

  //if yes then we check if the goal can be achieved by building it with our big bricks and how much small bricks should be needed then.

   if (goal % 5 <= small) {

    return true;

    }
  }

 return false;

}

A: public boolean makeBricks(int small, int big, int goal) {
  if ((goal % 5) <= small && ((Math.floor(goal/5)) <= big || (5*big + small) >= goal))
     return true;
  return false;
}

A: You can try this:
function makeBricks(small, big, goal){
    return (small * 1) + (big * 5) >= goal;
}


text:
Q: How can I solve "Cannot Start Family Sharing" error, when trying to set up family sharing? On my iPhone I go to Settings -> Apple ID, and click "Set Up Family Sharing", and this error appears:

But... I am Jon, and I'm not familiar with any family sharing setup.
And my Mac says basically the same thing, when going to System Preferences -> Family Sharing (via Catalina 10.15.1):

I've called Apple Support about this but they say I need to log in with the iCloud account my primary account is associated with, but I've no idea what account that could be. As far as I'm concerned I have one and only one iCloud account, and I haven't made any account changes in years. Apple Support insists they can't look up more information.
So how do I use Family Sharing in this situation? Or even just debug this? Apple Support insists there's nothing they can do so I'm not sure what to do next, anyone got any ideas??

A: Oh.
Okay, I found a hint in an email from 2012 (!) when MobileMe transitioned into iCloud (remember that!?), and I guess I had another account back then which for reasons unknown I apparently family shared to my new account ♂
My strange past behaviour aside this looks to resolve my issue (waiting for account deletion to go through before I can know for sure).
If anyone else comes across this: https://appleid.apple.com guided me towards my long-lost account, and https://privacy.apple.com is where I put it up for deletion.


text:
Q: Appengine Django Template - Read template tags UPDATE 1
ADDED UPDATED CODE
I have a django template on app engine.  Currently all my data is in several templates and I would like to read the templates off disk. Very easy, but I would like to get the values out of these templates in AppEngine.
eg. file : p1.html
{%block price%}$259{%endblock%}
{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}
{%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%}

Can I load and read these template into some value and go.
template['price']

which would be

$259

I can easily inject data into the template, but I want to parse out the data between my block tags.
UPDATED 2
With the help of aaronasterling (THANKS) the final code is this.
Final code to get the value out of a Django template on app engine.
        path = os.path.join(os.path.dirname(file), 'home/p2.html')
    file = open(path)
    entry = file.read()
    file.close()
    entry = entry.replace("{% extends \"product.html\" %}","")

    t = Template(entry)

    product = {}
    for node in t.nodelist[0].nodelist  :
       if hasattr(node, 'name'):
          product[node.name] = node.render(Context())

A: Sounds like you've shot yourself in the foot.  Lets just pretend we aren't to blame and fix it:
entry = """{%block price%}$259{%endblock%}
{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}
{%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%}   """

parsedentry = dict([(j[0].split(' ')[-1], j[-1]) for j in [i.partition("%}") for i in entry.split("{%endblock%}")] if j[0].split(' ')[-1]])

print parsedentry['price']

A: Update 1 fixed to traverse the whole node tree.
Update 2 Actually tested it so now it works.
Here's one way to do it.
from django.template import Template, Context

t = Template(template_string) # get it with open(filename).read() I guess

def get_block_contents(t, block_name, context=None):
    if context is None:
        context = Context()
    stack = t.nodelist[:]
    while stack:
        node = stack.pop()
        if hasattr(node, 'name') and node.name == block_name:
            return node.render(context)
        if hasattr(node, 'nodelist'):
            stack.extend(node.nodelist)
    return False # Or raise an error


text:
Q: How to set text color for MaterialButton from code? I am using MaterialButton with outline style and can't set text color from code. Is there setTextColor method? I can change it via android:textColor from XML, but not from code.
Using com.google.android.material:material:1.0.0-rc01

A: There was bug in 1.0.0-rc01 version and it was fixed in release version.


text:
Q: When should gravitational potential energy be included in the law of conservation of energy I have a problem that says:

A block of mass 0.249 kg is placed on top of a light, vertical spring
  of force constant 4 975 N/m and pushed downward so that the spring is
  compressed by 0.090 m. After the block is released from rest, it
  travels upward and then leaves the spring. To what maximum height
  above the point of release does it rise?

My first intuition was to use the law of conservation of energy which goes like this
$$mgh_1+\frac{Kh^2}{2} = mgh_2$$
$$0.249*9.8*(-0.09)+\frac{4975 * (-0.09)^2}{2} = 0.249*9.8*h_2$$
Here, I defined the point in which the spring is at equilibrium as my reference point (as per convention) which means that when the string is compressed we have two forms of energy, gravitational and elastic, and at point two which is when the object has reached it's maximum height, there is but only one form of energy which is gravitational potential energy.However, this does not seem to give the correct answer. The correct answer seems to come when i don't include the negative gravitational potential energy at the left side of the equation, but i don't know why is that. can someone please explain? thanks


text:
Q: Memorising Words And Phrases For IELTS? I'm a non-English native speaker going to take an Academic IELTS exam in few months. At the moment, I'm toying with the problem of memorising the English words, so that when I want to write/state sentences in English, I can recall them for use well. They're nearly more than 1000 new words and phrases.
What methods do you friends bestow upon me, please?

A: Although flashcards can help with rote learning, actually using words well requires greater familiarity with not just the word itself, but also how it interacts with other words.
For example, consider the word saw. The following sentences seem to be very similar, but they use different definitions of the term:

*

*I saw his bicycle. (Natural reading: I looked at the bicycle.)

*I sawed his bicycle. (Natural reading: I cut the bicycle.)

You can try looking up a word in a dictionary to get a feel for its range of meanings as well as some examples of how the word might be used in sentences. You can then try googling the word to see how it is used.
Note that search engines don't normally comment on whether a word is used 'correctly' in any given instance, so you might want to look at published works instead. Published work stand a higher chance of having been reviewed prior to publication. Ngram is said to be a large database of published work. At the bottom of the Ngram chart, there are links to the material used in compiling the stats making up the chart. You can click through to the broader context to see how the word is actually used in print.
After this, try putting together your own sentences and getting your teacher to look through them.
All this takes time, but if you want to recall the words so that you can use them well, you need to work out how they are used well.


text:
Q: LayoutTransition.DISAPPEARING animations don't run when removing child views I have a FrameLayout container that I'm trying to have animate it's changes.  I call container.setLayoutTransition(layoutTransition) on the view, but when I later call container.removeView(v) the DISAPPEARING animation isn't executed, the view is simply immediately removed.
Here's my code for the transition:
LayoutTransition layoutTransition = new LayoutTransition();
layoutTransition.setAnimator(LayoutTransition.APPEARING,
    ObjectAnimator.ofFloat(null, View.TRANSLATION_Y, toolHeight, 0f));
layoutTransition.setStartDelay(LayoutTransition.APPEARING, 0);
layoutTransition.setDuration(LayoutTransition.APPEARING, 1000);
layoutTransition.setAnimator(LayoutTransition.DISAPPEARING,
    ObjectAnimator.ofFloat(null, View.TRANSLATION_Y, 0f, toolHeight));
layoutTransition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
layoutTransition.setDuration(LayoutTransition.DISAPPEARING, 1000);
container.setLayoutTransition(layoutTransition);

And to swap views I do this:
if (container.getChildCount() > 0) {
  for (int i = container.getChildCount() - 1; i >= 0; i--) {
    container.removeViewAt(i);
  }
}
container.addView(newView);

I've slowed down the animations to confirm the situation, and I can clearly see that the APPEARING transition is executed appropriately, but the DISAPPEARING transition isn't, the view is simply removed immediately.
I've found that if I remove the view from the LayoutTransition.removeChild() method it works, but that adds quite a bit of complexity that doesn't seem necessary.  Here's what that becomes:
if (container.getChildCount() > 0) {
  final View v = container.getChildAt(0);
  container.getLayoutTransition().removeChild(container, v);
  container.getLayoutTransition().addTransitionListener(new LayoutTransition.TransitionListener() {
    @Override
    public void startTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
    }

    @Override
    public void endTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
      transition.removeTransitionListener(this);
      if (transitionType == LayoutTransition.DISAPPEARING) {
        container.removeView(view);
      }
    }
  }
}
container.addView(newView);

Think that's bad?  That's only for removing a single view at a time, if there is more than one view in the container then I've got to add a transition listener that counts executions to know when to remove itself, and that's just a mess.
The removing itself is interesting, because if I simply put that transition listener on the LayoutTransition and it doesn't remove itself, then the disappearing transition doesn't run again.
Clearly I'm missing something pertaining to making the remove transition execute.  Any help would be appreciated.
EDIT
It's been pointed out to me that adding views cancels the DISAPPEARING transitions:
public class ViewGroup {
  private void addViewInner(...) {
    if (mTransition != null) {
      // Don't prevent other add transitions from completing, but cancel remove
      // transitions to let them complete the process before we add to the container
      mTransition.cancel(LayoutTransition.DISAPPEARING);
    }
  }
}

This doesn't make a lot of sense to me.  Wonder what the reasoning is here.

A: As you've noticed, LayoutTransition doesn't really sequence animation types the way some of the newer APIs do. It's designed to handle a single item change at a time. The cleanest code will come from sequencing the add yourself with a delay, rather than chaining listener calls:
if (container.getChildCount() > 0) {
  for (int i = container.getChildCount() - 1; i >= 0; i--) {
    container.removeViewAt(i);
  }

  //Start the add once removals are complete
  long duration =
    container.getLayoutTransition().getDuration(LayoutTransition.DISAPPEARING);
  container.postOnAnimationDelayed(new Runnable(){
    @Override
    public void run() {
      container.addView(newView);
    }
  }, duration);
} else {
  container.addView(newView);
}

You might get better choreography out of Scenes for something like this, but that is API 19+


text:
Q: Porting of Plural string from Localizable.strings to Localizable.stringsdict with %@ input formatter in the middle of stirng In Localizable.strings, I have below plural strings with one and other

"User added %@ posts.##{one}" = "User added a post.";
"User added %@ posts.##{other}" = "User added %@ posts.";

I wish to remove it from Localizable.strings and add it to Localizable.stringsdict.
I have done this before for the basic strings with the input format (%d) at the start of string. But, I have never user Localizable.stringsdict for strings having input format in middle of the string
Could anyone help me with exporting the above string in below format?
<key>Fill_Here</key>
<dict>
    <key>NSStringLocalizedFormatKey</key>
    <string>Fill_Here</string>
    <key>Fill_Here</key>
    <dict>
        <key>NSStringFormatSpecTypeKey</key>
        <string>NSStringPluralRuleType</string>
        <key>NSStringFormatValueTypeKey</key>
        <string>Fill_Here</string>
        <key>one</key>
        <string>Fill_Here</string>
        <key>other</key>
        <string>Fill_Here</string>
    </dict>
</dict>

Thanks in advance

A: I figured out a way to do this, by modifying dictionary as below
<key>User added %@ posts.</key>
<dict>
    <key>NSStringLocalizedFormatKey</key>
    <string>%#@posts@</string>
    <key>posts</key>
    <dict>
        <key>NSStringFormatSpecTypeKey</key>
        <string>NSStringPluralRuleType</string>
        <key>NSStringFormatValueTypeKey</key>
        <string>d</string>
        <key>one</key>
        <string>User added %d post.</string>
        <key>other</key>
        <string>User added %d posts.</string>
    </dict>
</dict>

Using %@ input format crashes the application in this case. So I modified it to use %d instead.