text:
Q: PHP IMAP Receive Attachment from Microsoft Exchange Server Hello my client has asked me to make a website using PHP using which he can read/reply all his emails from all his accounts. Now he has a company account on Microsoft Exchange Server, I am using PHP imap_open to get emails from the mail-servers, I am able to get Email Attachments from Gmail account but I am not able to retrieve attachments from Microsoft Exchange server accounts. No error is getting generated so I am not sure what is wrong. Do I need to write some kind of special code in order to retrieve Attachments from Microsoft Exchange server email accounts?
Also a similar problem persists when trying to send emails, I am able to send emails from the PHP system using Gmail SMTP details, but not with Microsoft Exchange server
I am still researching but a little help would be much appreciated, maybe if you can just point me in the right direction I'll be able to understand what is wrong with my code. I don't know much about what Microsoft Exchange server is or how it is different from other email providers like Gmail, so I would really appreciate if you can just point me in the right direction.
The attachment retrieval code is working fine for Gmail accounts

A: Regarding SMTP mail sending problem for outlook server. I had the same problem, the problem is with the PORT Number.
Use Port:587 instead of Port:25 or any other options... I have been sending from Outlook with this port and I am successful every time.
And For IMAP attachment issue the solution is hidden in the case sensitivity...
If we look at the function object imap_fetchstructure ( resource $imap_stream , int $msg_number) which is generally responsible for fetching attachments.
What we get for Gmail And Others:

stdClass Object
(
    [type] => 1
    [encoding] => 0
    [ifsubtype] => 1
    [subtype] => MIXED
    [ifdescription] => 0
    [ifid] => 0
    [ifdisposition] => 0
    [ifdparameters] => 0
    [ifparameters] => 1
    [parameters] => Array
        (
            [0] => stdClass Object
                (
                    [attribute] => BOUNDARY    // Notice Here...
                    [value] => b1_04114a96a39b7789f88fdabc7feadc61
                )

        )

    [parts] => Array
        (
            [0] => stdClass Object
                (
                    [type] => 0
                    [encoding] => 1
                    [ifsubtype] => 1
                    [subtype] => HTML
                    [ifdescription] => 0
                    [ifid] => 0
                    [lines] => 20
                    [bytes] => 597
                    [ifdisposition] => 0
                    [ifdparameters] => 0
                    [ifparameters] => 1
                    [parameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => CHARSET   // Notice Here...
                                    [value] => iso-8859-1
                                )

                        )

                )

            [1] => stdClass Object
                (
                    [type] => 5
                    [encoding] => 3
                    [ifsubtype] => 1
                    [subtype] => JPEG
                    [ifdescription] => 0
                    [ifid] => 0
                    [bytes] => 266988
                    [ifdisposition] => 1
                    [disposition] => ATTACHMENT     // Notice Here...
                    [ifdparameters] => 1
                    [dparameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => FILENAME    // Notice Here...
                                    [value] => oIROo0jJDb-15.jpg
                                )

                        )

                    [ifparameters] => 1
                    [parameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => NAME    // Notice Here...
                                    [value] => oIROo0jJDb-15.jpg
                                )

                        )

                )

        )

)

What We Get for OUTLOOK:

 1
    [encoding] => 0
    [ifsubtype] => 1
    [subtype] => MIXED
    [ifdescription] => 0
    [ifid] => 0
    [ifdisposition] => 0
    [ifdparameters] => 0
    [ifparameters] => 1
    [parameters] => Array
        (
            [0] => stdClass Object
                (
                    [attribute] => boundary
                    [value] => b1_df2cd0669f50efc788d5aecfdded4957
                )

        )

    [parts] => Array
        (
            [0] => stdClass Object
                (
                    [type] => 0
                    [encoding] => 1
                    [ifsubtype] => 1
                    [subtype] => HTML
                    [ifdescription] => 0
                    [ifid] => 0
                    [lines] => 23
                    [bytes] => 729
                    [ifdisposition] => 0
                    [ifdparameters] => 0
                    [ifparameters] => 1
                    [parameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => charset    // Notice Here...
                                    [value] => iso-8859-1
                                )

                        )

                )

            [1] => stdClass Object
                (
                    [type] => 5
                    [encoding] => 3
                    [ifsubtype] => 1
                    [subtype] => JPEG
                    [ifdescription] => 0
                    [ifid] => 0
                    [bytes] => 266988
                    [ifdisposition] => 1
                    [disposition] => attachment    // Notice Here...
                    [ifdparameters] => 1
                    [dparameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => filename    // Notice Here...
                                    [value] => cqLaQAZSei-15.jpg
                                )

                        )

                    [ifparameters] => 1
                    [parameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => name    // Notice Here...
                                    [value] => cqLaQAZSei-15.jpg
                                )

                        )

                )

        )

)
?>

So now, generally for fetching attachments somewhere we use an if statement for checking if there is any attachments in that part of the email. For this context I would refer to PHP IMAP Library Part 1 And PHP IMAP Library Part 2... The Fetching Attachment function is in the Part 2 of the Tutorial.
Get Attachment Function:
function getAttachments($imap, $mailNum, $part, $partNum) {
    $attachments = array();

    if (isset($part->parts)) {
        foreach ($part->parts as $key => $subpart) {
            if($partNum != "") {
                $newPartNum = $partNum . "." . ($key + 1);
            }
            else {
                $newPartNum = ($key+1);
            }
            $result = getAttachments($imap, $mailNum, $subpart,
                $newPartNum);
            if (count($result) != 0) {
                 array_push($attachments, $result);
             }
        }
    }
    else if (isset($part->disposition)) {
        if ($part->disposition == "ATTACHMENT") {    // Notice here...
            $partStruct = imap_bodystruct($imap, $mailNum,
                $partNum);
            $attachmentDetails = array(
                "name"    => $part->dparameters[0]->value,
                "partNum" => $partNum,
                "enc"     => $partStruct->encoding
            );
            return $attachmentDetails;
        }
    }

    return $attachments;
}
Notice the if statement inside the else if statement You can see it is comparing with capital ATTACHMENT but Outlook result has no Capital ATTACHMENT they have attachment. So instead of that line I'll recommend using: strtoupper($part->disposition) == 'ATTACHMENT'...
In this way we have the attachment working...
So the final function should be:
function getAttachments($imap, $mailNum, $part, $partNum) {
    $attachments = array();

    if (isset($part->parts)) {
        foreach ($part->parts as $key => $subpart) {
            if($partNum != "") {
                $newPartNum = $partNum . "." . ($key + 1);
            }
            else {
                $newPartNum = ($key+1);
            }
            $result = getAttachments($imap, $mailNum, $subpart,
                $newPartNum);
            if (count($result) != 0) {
                 array_push($attachments, $result);
             }
        }
    }
    else if (isset($part->disposition)) {
        if (strtoupper($part->disposition) == "ATTACHMENT") {
            $partStruct = imap_bodystruct($imap, $mailNum,
                $partNum);
            $attachmentDetails = array(
                "name"    => $part->dparameters[0]->value,
                "partNum" => $partNum,
                "enc"     => $partStruct->encoding
            );
            return $attachmentDetails;
        }
    }

    return $attachments;
}
I hope that will fix the problem... Because it did for me...
Thank you...


text:
Q: Latest available PHP version for Linux not sufficient for Passport I want to install Passport for my API, and when I type composer require laravel/passport, I get the error:

[...] requires php ^7.1.3 -> your PHP version (7.0.27) does not satisfy that requirement.

The problem is, I have done an apt-get upgrade and it seems that I have the latest version of PHP for Linux (PHP 7.0.27). I am on Debian.
What should I do?
Thank you for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to ready a file using python, where data is appended continuously? Assuming a server dumps logs to a file and we need to read last 100 lines.
In the meantime, the file is loaded with more lines.
How to tackle this kind of cases?

A: Well, what you shouldn't do is dump all the contents of the file into a string. That would be horrible, as log files can get up to sizes of 100 MB. If you were only allowed one file handler, what I would recommend is to have a queue to write the lines, and every once in a while, dump the lines into the log. In the free time, it can read the last 100 lines.


text:
Q: How to handle array formated JSON in SwiftUI? I'm trying to fetch latitude and longitude coordinates from this API in Xcode. My problem is that the JSON file starts off as an array and therefore I'm not entirely sure how to access all the parts of it. Here is my function for it:
func FetchOriginCoordinates() {
        let locationUrl = URL(string: "https://nominatim.openstreetmap.org/search?country=Sweden&city=Stockholm&street=odenplan&format=json")

        URLSession.shared.dataTask(with: locationUrl!) {data, response, error in
            if let data = data {

                if let decodedJson = try? JSONDecoder().decode([NominationStructure].self, from: data) {

                    self.originLat = String(decodedJson[0].lat)
                    self.originLon = String(decodedJson[0].lon)
                }
            }
        }.resume()
    }

I tried looking online on how to write the struct and this is what I found, but I doesn't work.
struct NominationStructure: Decodable {
    var lat: Float
    var lon: Float

    enum CodingKeys: String, CodingKey {
        case lat = "lat"
        case lon = "lon"
    }
}


text:
Q: Position fixed with bootstrap columns I have a sibdebar which I want always to appear on the top of the screen when the user scroll down and get to it, so I use this thread for help:
Make element fixed on scroll
Problem is, when I scroll down something with the width is going wrong.
First is OK:

But when I scroll down:

The code:

                    <?php dynamic_sidebar('single_post_sidebar');?>

                <?php the_content(); ?>

Any help will be appreciate.

A: Checkout the example below,I have just added style "right:0" and "position:fixed" to the col-3 inside col-9.

First item

Second item

Third item

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                Lorem Ipsum is simply dummy text of the printing and typesetting industry.

First item

Second item

Third item

First item


text:
Q: Need to access InstaOn.com from Ubuntu I need to access my DVR over Internet using Firefox on Ubuntu. The web site is www.instaon.com, but when I try to login it asks for ActiveX plug-in. Is there a alternate for ActiveX for Ubuntu or any other way to make it work?
Thanks,
Ataullah

A: Short answer No.
Long answer:
ActiveX only works on Microsoft Internet Explorer. Unfortunately, there aren't any alternatives, just like there isn't and alternative to Flash. Not to mention, ActiveX is really old and outdated, full of security holes and vulnerabilities, and really should be killed with fire.


text:
Q: Procedural terrain programming in Unity 3D I am trying to get along with procedural generation, I definitely not a pro in unity, however I was following this guide: click  and got some results. For now I have 2 problems, I have some basic idea how to resolve them, however I would like to hear some other opinions.
(I have already posted this question on Unity answers, however I have got no response at all, if there is some missing information or it is impossible to explain in a few words, please let me know or give some advice how to find this information)
The main issue is : gaps between chunks:

they kinda disappear if I will zoom, however textures remain unfit and it is remarkable.
The second, as you can see I have a problem with red (I don't really know how to call it) marks on the ground. I have tried to use material from guide, but got same effect.
Besides, Perlin Noise ( I know that I can use Diamond square or simplex) is pseudo-random algorithm, so it will return the same values for the same input parameters, so does it mean that my chunks will always be the same?
My code ( I am using LibNoise library from guide):
    void Awake()
    {
        var settings = new TerrainChunkSettings(129, 129, 100, 40, FlatTexture, SteepTexture, TerrainMaterial);
        var noiseProvider = new NoiseProvider();
        for (var i = 0; i < 4; i++)
            for (var j = 0; j < 4; j++)
                new TerrainChunk(settings, noiseProvider, i, j).CreateTerrain();
    }
public class TerrainChunkSettings
{
    public int HeightmapResolution { get; private set; }

    public int AlphamapResolution { get; private set; }

    public int Length { get; private set; }

    public int Height { get; private set; }

    public Texture2D FlatTexture { get; private set; }

    public Texture2D SteepTexture { get; private set; }

    public Material TerrainMaterial { get; private set; }

    public TerrainChunkSettings(int heightmapResolution, int alphamapResolution, int length, int height, Texture2D flatTexture, Texture2D steepTexture, Material terrainMaterial)
    {
        HeightmapResolution = heightmapResolution;
        AlphamapResolution = alphamapResolution;
        Length = length;
        Height = height;
        FlatTexture = flatTexture;
        SteepTexture = steepTexture;
        TerrainMaterial = terrainMaterial;
    }
}

public class TerrainChunk
{
    private Terrain Terrain { get; set; }

    private TerrainChunkSettings Settings { get; set; }

    private NoiseProvider NoiseProvider { get; set; }

    public int X { get; private set; }

    public int Z { get; private set; }

    private TerrainData Data { get; set; }

    private float[,] Heightmap { get; set; }
    public TerrainChunk(TerrainChunkSettings settings, NoiseProvider noiseProvider, int x, int z)
    {
        X = x;
        Z = z;
        Settings = settings;
        NoiseProvider = noiseProvider;
    }

    public void CreateTerrain()
    {
        var terrainData = new TerrainData();
        terrainData.heightmapResolution = Settings.HeightmapResolution;
        terrainData.alphamapResolution = Settings.AlphamapResolution;

        var heightmap = GetHeightmap();
        terrainData.SetHeights(0, 0, heightmap);
        ApplyTextures(terrainData);
        terrainData.size = new Vector3(Settings.Length, Settings.Height, Settings.Length);

        var newTerrainGameObject = Terrain.CreateTerrainGameObject(terrainData);
        newTerrainGameObject.transform.position = new Vector3(X * Settings.Length, 0, Z * Settings.Length);
        Terrain = newTerrainGameObject.GetComponent<Terrain>();
        Terrain.Flush();
    }

    private float[,] GetHeightmap()
    {
        var heightmap = new float[Settings.HeightmapResolution, Settings.HeightmapResolution];

        for (var zRes = 0; zRes < Settings.HeightmapResolution; zRes++)
        {
            for (var xRes = 0; xRes < Settings.HeightmapResolution; xRes++)
            {
                var xCoordinate = X + (float)xRes / (Settings.HeightmapResolution - 1);
                var zCoordinate = Z + (float)zRes / (Settings.HeightmapResolution - 1);

                heightmap[zRes, xRes] = NoiseProvider.GetValue(xCoordinate, zCoordinate);
            }
        }

        return heightmap;
    }

    private void ApplyTextures(TerrainData terrainData)
    {
        var flatSplat = new SplatPrototype();
        var steepSplat = new SplatPrototype();

        flatSplat.texture = Settings.FlatTexture;
        steepSplat.texture = Settings.SteepTexture;

        terrainData.splatPrototypes = new SplatPrototype[]
        {
            flatSplat,
            steepSplat
        };

        terrainData.RefreshPrototypes();

        var splatMap = new float[terrainData.alphamapResolution, terrainData.alphamapResolution, 2];

        for (var zRes = 0; zRes < terrainData.alphamapHeight; zRes++)
        {
            for (var xRes = 0; xRes < terrainData.alphamapWidth; xRes++)
            {
                var normalizedX = (float)xRes / (terrainData.alphamapWidth - 1);
                var normalizedZ = (float)zRes / (terrainData.alphamapHeight - 1);

                var steepness = terrainData.GetSteepness(normalizedX, normalizedZ);
                var steepnessNormalized = Mathf.Clamp(steepness / 1.5f, 0, 1f);

                splatMap[zRes, xRes, 0] = 1f - steepnessNormalized;
                splatMap[zRes, xRes, 1] = steepnessNormalized;
            }
        }

        terrainData.SetAlphamaps(0, 0, splatMap);
    }
}

public interface INoiseProvider
{
    float GetValue(float x, float z);
}
public class NoiseProvider : INoiseProvider
{
    private Perlin PerlinNoiseGenerator;

    public NoiseProvider()
    {
        PerlinNoiseGenerator = new Perlin();
    }

    public float GetValue(float x, float z)
    {
        return (float)(PerlinNoiseGenerator.GetValue(x, 0, z) / 2f) + 0.5f;
    }
}

A: 1) The main issue is : gaps between chunks
You can stitch terrain together to ensures they get the same LOD with SetNeighbors(Terrain left, Terrain top, Terrain right, Terrain bottom);
From the documentation:

Lets you setup the connection between neighboring Terrains.
This ensures LOD matches up on neighboring terrains. Note that it is
  not enough to call this function on one Terrain, you need to set the
  neighbors of each terrain.

2) The second: red marks on the ground
This problem should come from the textures you are using in your terrain object.

A: The gaps happen because you're creating different terrain objects. The main point of using terrains is to have a procedural piece of mesh you can optimize as you see fit.
The engine optimizes terrains by decreasing their LOD the farther you are from them. This means that two neighboring chunks may get two different LODs, effectively meaning one has half the vertex resolution of the other, which causes the gaps. You'll notice how they seem to happen with every other vertex if you pay close attention. It also seems to disappear up-close because you don't get any LODs up-close.
The way the engine solves this is by stitching the extra vertex to the lower-resolution part of the terrain. It can't do this in your case, however, because there are separate terrain objects and they're unaware of each other's existence. What you probably want to do to solve the problem is to merge all the smaller terrain objects into one big terrain.


text:
Q: How to run an hardhat script on NodeJs so that you can fork multiple evm chains on different ports? I want to be able to fork more chains (ethereum, bsc, etc.) than just one on my system.
 Hardhat doc shows, how to fork 1 chain npx hardhat node --fork https://... and it works fine.

But I would like to fork them programmatically on a Nodejs script.

When I try to fork a chain on NodeJs like below, it does not work. What can I do?
Thanks!

`hre.config.networks.networks = {
     hardhat: {
        forking: {
          url: http://localhost:8545
        },
    }
}

await hre.network.provider.request({
    method: "hardhat_reset",
    params: [
      {
        forking: {
          jsonRpcUrl: http://localhost:8545,
          chainId: chainObj.chain_id,
          blockNumber: blockNumber,
        },
      },
    ],
});

`

A: Maybe it would help.
hardhat.config.ts:
networks: {
    hardhat: {
        mining: {
            auto: false,
            interval: [10000, 10000],
        },
        chainId: Number(process.env.CHAIN_ID),
        forking: {
            url: process.env.NETWORK_URL || "",
            // blockNumber: Number(process.env.FROM_BLOCK) || 228,
        },
        accounts: [
            {
                balance: "100000000000000000000000000000",
                privateKey: process.env.PRIVATE_KEY as string,
            },
        ],
    }
}

package.json:
"scripts": {
"bsc": "NETWORK=bsc NETWORK_URL=https://rpc.ankr.com/bsc FROM_BLOCK=22828104 CHAIN_ID=100 npx hardhat node --port 8541 ",
"eth": "NETWORK=eth NETWORK_URL=https://rpc.ankr.com/eth FROM_BLOCK=15720107 CHAIN_ID=101 npx hardhat node --port 8542 ",
"avax": "NETWORK=avax NETWORK_URL=https://api.avax.network/ext/bc/C/rpc CHAIN_ID=102 FROM_BLOCK=20899475 npx hardhat node --port 8543 ",
"ftm": "NETWORK=ftm NETWORK_URL=https://rpc.ankr.com/fantom CHAIN_ID=103 FROM_BLOCK=48883683 npx hardhat node --port 8544 ",
}


text:
Q: Removing personal data from SVG file For the first time I needed to perform a diff on an SVG file created with Inkscape, because I had a conflict in SVN.
While checking the differences, I noticed that the SVG file contains a lot of personal information. The personal information is about paths used for exporting. The SVG source looks like this:
<text ... inkscape:export-filename="<personal information here>" ... />

In my case it has a lot of folder names going back to projects I worked for in 2009.
How can I remove this personal information from Inkscape SVG files?
Of course I could do it in a text editor manually, but that has some disadvantages:

*

*it's error-prone. You need to be quite sure what you're doing. There should be a safer way to do it.

*it's time-consuming. There should be a quicker way to do it.

*it might be incomplete. Maybe there is other personal data I have not discovered yet.

A: I have a lot of SVGs from different sources, so I was looking for an automated solution.
1. SVGO (NodeJS, javascript)
There is a very good NPM package: SVGO
Since I use gulp as a task-runner, so the gulp-svgmin (or gulp-svgo) is very helpful
2. XSLT (transform SVG)
The other automated approach — use XSLT. Here is an XSL transformation I have used to cleanup SVG.
This XSLT does the following:

*

*removes all inkscape and sodipodi attributes

*removes all inkscape and sodipodi elements

*removes metadata element with all ancestors

*removes style attributes (we use CSS) - only when the variable preserve-style is set to false
As output you will get the clean SVG file.
How to run transformation
Javascript (gulp build)
If you use gulp as build system, you could use this plugins:

*

*gulp-xslt

*or gulp-saxon requires the presence of the saxon.jar in the system
Python and lxml.etree
Use this short python script:
#!/usr/bin/python

import lxml.etree as ET

def clean_file(path, pathto):
    svg1 = ET.parse(path)

    xslt = ET.parse('cleanup-svg.xsl')
    transform = ET.XSLT(xslt)
    svg2 = transform(svg1)
    with open(pathto, 'w') as f:
        f.write(ET.tostring(svg2, pretty_print=True))

clean_file('a.svg', 'b.svg')

A: The easiest way to do this is to save the file as an Optimized SVG file. This option is available in the Save As... dialog dropdown. When you click save a dialog will popup asking you what to remove. Make sure the box Keep Editor Data is left unchecked.


text:
Q: Compact, readable, efficient C++ algorithm to reverse the words of a string IN-PLACE So I'm trying to come up with a good C++ solution to the prompt

"Reverse words in a string (words are separated by one or more
  spaces). Now do it in-place. By far the most popular string question!"

and what I have now is a monstrosity:
void reverse_words ( std::string & S )
{
/*
    Programming interview question: "Reverse words in a string (words are separated by one or more spaces). Now do it in-place. By far the most popular string question!"
    http://maxnoy.com/interviews.html
*/
    if (S.empty()) return;
    std::string::iterator ita = S.begin() , itb = S.end() - 1;
    while (ita != itb)
    {
      if (*ita != ' ')
      {
         std::string sa; // string to hold the current leftmost sequence of non-whitespace characters
         std::string::iterator tempa = ita; // iterator to the beginning of sa within S
         while (ita != ' ' && ita != itb) sa.push_back(*ita++); // fill sa
         while (*itb == ' ' && itb != ita) --itb; // move itb back to the first non-whitespace character preceding it
         std::string sb; // string to hold the current rightmost sequence of non-whitespace characters
         std::string::iterator tempb = itb; // iterator to the end of sb within S
         while (*itb != ' ' && itb != ita) sb.push_back(*itb--); // fill sb
         S.replace(tempa, ita-tempa, sb); // replace the current leftmost string with the current rightmost one
         S.replace(tempb, itb-tempb, sa); // and vice-versa
       }
      else
      {
         ++ita;
      }
    }
}

I think I have the right idea (find the first string, swap it with the last, find the next string after the first, swap it with the one before the last, etc.), but I need some better tools to make this happen. How can I exploit the standard library to solve this problem?

A: This is pretty simple if you use the following approach:

*

*Reverse the whole string.

*Reverse each word individually.

This algorithm is already O(n), you just run through the whole string once and then again to find an reverse each word.
Now, in order to make this a bit more efficient, look at the algorithm to reverse a sequence, which reads one from the front and back and stores each at the other's position. Now, whenever you store a space, you just terminated a word, so just reverse the word right now. The reason that is more efficient is that the cache containing that word is still hot on the CPU. The difficulty here is getting this right in cornercases. You have to consider the middle word, multiple consecutive spaces and spaces at either end of the string.

A: I guess this is it. Simple, efficient, and clear. Note that std::basic_string::find... returns npos when pos >= str.size().
void ReverseWords(std::string& msg) {
    std::string::size_type pos_a = 0, pos_b = -1;
    while ((pos_a = msg.find_first_not_of(' ', pos_b + 1)) != msg.npos) {
        pos_b = std::min(msg.find(' ', pos_a + 1), msg.size());
        std::reverse(msg.begin() + pos_a, msg.begin() + pos_b);
    }
    std::reverse(msg.begin(), msg.end());
}


text:
Q: implementation 'com.jmedeisis:draglinearlayout:1.1.0' showing error started a new blank template project and just after adding draglinearlayout dependency i started getting these errors, while before adding this dependency i ran my project and it worked fine. the error is as follows

Execution failed for task ':app:checkDebugDuplicateClasses'.
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
Duplicate class android.support.v4.app.INotificationSideChannel found in modules core-1.5.0-runtime (androidx.core:core:1.5.0) and support-v4-22.1.1-runtime (com.android.support:support-v4:22.1.1)
Duplicate class android.support.v4.app.INotificationSideChannel$Stub found in modules core-1.5.0-runtime (androidx.core:core:1.5.0) and support-v4-22.1.1-runtime (com.android.support:support-v4:22.1.1)
Duplicate class android.support.v4.app.INotificationSideChannel$Stub$Proxy found in modules core-1.5.0-runtime (androidx.core:core:1.5.0) and support-v4-22.1.1-runtime (com.android.support:support-v4:22.1.1)

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

this is the error i'm getting
and this is my module grade file
plugins {
   id 'com.android.application'
}

android {
   compileSdkVersion 30
   buildToolsVersion "30.0.3"

   defaultConfig {
       applicationId "com.ujjwal.drag_and_drop"
       minSdkVersion 19
       targetSdkVersion 30
       versionCode 1
       versionName "1.0"

       testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
   }

   buildTypes {
       release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
       }
   }
   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
   }
}

dependencies {

   implementation 'com.jmedeisis:draglinearlayout:1.1.0'
   implementation 'androidx.appcompat:appcompat:1.3.0'
   implementation 'com.google.android.material:material:1.4.0'
   implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
   testImplementation 'junit:junit:4.13.2'
   androidTestImplementation 'androidx.test.ext:junit:1.1.3'
   androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

A: Android has a solution to this problem where a new Android project uses AndroidX with some old libraries that use the legacy android support libraries, you are in that case.
The solution is to enable Jetifier in your gradle.properties, like this:
android.enableJetifier=true

You can find more info in these two posts:

*

*Can I use library that used android support with Androidx projects.

*What is Jetifier?


text:
Q: opencv, python: How to track live trackers from environment and find changes in environment I'm trying my hands on OpenCV with Python and 'am kind of stuck.
I want to find specific trackers from every frame of a live camera and detect changes in the environment with a tracker of different color (say red).
Right now, my code takes a frame of my video which I select, and shows trackers which are too much to understand.
Can you help me in fixing this code?
import numpy as np
import cv2
from matplotlib import pyplot as plt

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)

    # Initiate feature detector
    orb = cv2.FastFeatureDetector_create()

    # find the keypoints with ORB
    kp = orb.detect(gray)

    img2 = cv2.drawKeypoints(frame, kp, outImage=None, color=(0, 255, 0), flags=0)
    plt.imshow(img2), plt.show()

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

This is my image without an object (bottle)
This is me with an object
Now what I want to track changes in between the images (with bottle and without bottle), i.e changes in environment of an image should be tracked live on videocam!


text:
Q: MOQ C# QUERIES It.IsAny returning a List I have made a lot of progress during the night. I finally managed to set up my tests. Now my code will execute the first test and end up in the CREATE METHOD of the controller. What I am trying to see if I need to change my controller method so it can take a full object (perhaps create a new IF statement checking if the admin KEY and Admin Name are not null. Do yo have any suggestions as to the design pattern and realistic Unit Testing design?
Test:
public void Creating_One_Note()
    {

        var note = new AdminNote()
        {
            NoteId = 00003,
            UserKey = "89df3f2a-0c65-4552-906a-08bceabb1198",
            AdminKey = "4b942342-8f73-490c-b9df-f29ac859d7d7",
            NoteText = "TEST NOTE FOR THIS TEST YOU KNOW",
            CreateDate = DateTime.Now,
            ModifiedDate = DateTime.Now,
            AdminName = "Marco",
        };
        var a = _controller.Create(note);

        Assert.IsNotNull(a);
    }

Controller Create Method:
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(AdminNote adminNote)
    {
        try
        {
            if (ModelState.IsValid)
            {
                adminNote.AdminKey = System.Web.HttpContext.Current.User.Identity.GetUserId();
                adminNote.AdminName = System.Web.HttpContext.Current.User.Identity.GetUserName();
                adminNote.CreateDate = DateTime.Now;
                adminNote.ModifiedDate = DateTime.Now;

                adminNote.ObjectState = ObjectState.Added;
                _adminNoteService.Insert(adminNote);

                return RedirectToAction("UserDetails", "Admin", new { UserKey = adminNote.UserKey });
            }
        }
        catch (Exception ex)
        {
            ControllerConstants.HandleException(ex);
            ViewBag.PopupMessage(string.Format("We're sorry but an error occurred. {0}", ex.Message));
        }

        return View(adminNote);
    }

As you can see my controller method returns a VIEW I know I will have to adjust my test to be able to understand this. However the controller method will jump to the exception because its trying to set the AdminKey and AdminName (information I get from the front end). For this test I am hardcoding it in and I want to see if the method adds it to the repository. What could I do in this case?

A: _adminNoteRepository.Setup(r => r.Find(It.IsAny<AdminNote>())).Returns<List<AdminNote>>(null);

This is returning null because you told it to :). Moq returns the object that you pass as a parameter to the Returns method. The type argument for the Returns method (List<AdminNote> in your case) just specifies what the type of the returned value is, but Moq will not automatically create an instance of that type.
If you want Moq to return a non-null value, then you should pass a non-null value, for example:
_adminNoteRepository.Setup(r => r.Find(It.IsAny<AdminNote>()))
    .Returns<List<AdminNote>>(new List<AdminNote>());

Additionally, in this case the compiler can implicitly determine the the type argument for the Returns method, so you can omit it and simply write:
_adminNoteRepository.Setup(r => r.Find(It.IsAny<AdminNote>()))
    .Returns(new List<AdminNote>());


text:
Q: Atomic compare_exchange, but based on flag being set, rather than equality? std::atomic provides compare_exchange_strong(a,b) tests if the underlying value is currently "a", and if so, then replaces it with "b", in an atomic/thread-safe way.
Is there any lock-free, atomic way to perform a similar operation, but instead of testing for equality with "b", it would treat "b" as a flag, and perform the replacement if the underlying value has that flag set?
So in principle, something like
bool compare_exchange_flags(std::atomic<int>& underlying, int& flag, int replacement)
{
  auto tmp = underlying.load();

  if((tmp & flag) == flag) // only perform replacement if flag is set
  {
    flag = tmp; // emulate compare_exchange_strong, where expected value is replaced with actual value
    underlying = replacement;
    return true;
  } else {
    flag = underlying.load();
    return false;
  }
}

only in a version that would.. well, actually work ;) (above operations are not at all atomic of course)
Thanks!

For context: This is for a message bus. This bus has memory regions associated with some states (such as READABLE, WRITEABLE).
Each state needs to be enhanceable with some flags - for example, a state could just be "WRITEABLE", meaning a writer can freely write data to the fragment (readers are currently spinning / busy polling).
Or it could be "WRITEABLE | SIGNALED", which would imply a writer can acquire this memory for writing, but needs to trigger an event once data is written to notify the readers.
So (VERY conceptually, this isn't actual code - just to roughly demonstrate) something like
void send(...)
{
  auto expected = WRITEABLE;
  if(compare_exchange_flags(status, expected, WRITE_RESERVED))
  {
    // ... write data ...

    status = WRITTEN;

    if((expected & SIGNALED) = SIGNALED)
      wakeUpReaders();
  } else {
    tryAnotherRegion();
  }
}

A: There is not such instruction. But this kind of operations are usually performed with a loop that try to exchange the value while the value has the flag:
bool replace_if_flag(std::atomic<int>& underlying, int flag, int replacement){

  auto tmp = underlying.load();

  if(!(tmp & flag)) return false;

  while (!underlying.compare_exchange_weak(tmp,replacement)){
    if(!(tmp & flag)) return false;
    }

  return true;
  }


text:
Q: Matching a single word inside optional parentheses I am using java regex to match a specific platform.
For example, my list of strings are:
Ruby 2.1 (Puma)
Ruby 2.3 (Passenger Standalone)
Ruby 2.2 (Puma)
Ruby 2.2 (Passenger Standalone)
Ruby 1.9.6

From these I want to only pick the ones which are not Passenger standlone. ie. Ruby 2.1 (Puma) and Ruby 2.2 (Puma) and Ruby 1.9.6. The only restriction/condition is that the version name i.e Puma or Passenger Standalone is optional. And therefore the parenthesis and the string inside the parenthesis are optional
I am trying to use the following regex:
"Ruby (.*)\s+\(?\w{0,1}\)?$"

I have the options as an ArrayList of Strings. My method code looks like:
public void displayVersions(String platform) {
    String regex = "Ruby (.*)\s+\(?\w{0,1}\)?$";
    List<String> availableVersions = getAvailableVersions();
    List<String> filtered = availableVersions.stream()
        .filter(version -> version.matches(regex))
        .collect(Collectors.toList());

    System.out.println(filtered);

}
The regex is incorrect and I am not getting the correct results. I get the Passenger Standalone versions only. What am I doing wrong?

A: Fixed regex: Ruby ([0-9.]+)\s?\(?[^\s]*\)?$
You may also need to add /m option if the string to match is multiline
I personally suggest you https://regex101.com to check and debug regexes. For example https://regex101.com/r/c148v8/2

A: Ruby [0-9.]+ \((\S)\)
This will do the trick.
Ruby [0-9.]+ matches the ruby version
\((\S)\) matches any non-whitespace char within parenthesis.

A: Use nested optionals:
^Ruby \d+(\.\d+)*( \(?\w+\)?)?$

See live demo.


text:
Q: Role-based cross-account S3 access I have two aws accounts, A and B. Account A has a lambda function that needs access to a s3 bucket in Account B.
To simulate this case, I have the following settings:
The Account B (data source) has a role:
arn:aws:iam::${Account_B}:role/jeff-full-s3-access-role and is attached with AmazonS3FullAccess policy. This role has a trusted entity arn:aws:iam::${Account_A}:role/jeff-test-lambda-role
Meanwhile, arn:aws:iam::${Account_A}:role/jeff-test-lambda-role resides in Account A and it has a trusted entity lambda.amazonaws.com. And I've attached the following in-line policy with it:
{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::${Account_B}:role/jeff-full-s3-access-role"
    }
}

Now when I invoked the lambda function (python):
import json
from boto3 import client

def lambda_handler(event, context):
    conn = client('s3')  # again assumes boto.cfg setup, assume AWS S3
    for key in conn.list_objects(Bucket='Bucket_in_Account_B')['Contents']:
        print(key['Key'])

    return {}

But getting the following error:
{
  "errorMessage": "An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied",
  "errorType": "ClientError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 6, in lambda_handler\n    for key in conn.list_objects(Bucket='Bucket_in_Account_B')['Contents']:\n",
    "  File \"/var/runtime/botocore/client.py\", line 386, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n",
    "  File \"/var/runtime/botocore/client.py\", line 705, in _make_api_call\n    raise error_class(parsed_response, operation_name)\n"
  ]
}

Does anyone know the reason why this is not working? This post may work but it's a couple of years ago. I'm wondering if there's a way to achieve this without using Bucket Policy.
Thank you!

A: The easiest way to meet your requirement is to add a Bucket Policy on the bucket in Account B that permits access from the IAM Role used by the AWS Lambda function in Account A. This avoids any requirement to assume roles.
As for your current code, it is failing because your program needs to call assume_role() to obtain credentials from Account B. It then needs to use those credentials to create a new boto3.client() object for use when accessing resources in Account B. For an example, see: boto - AWS: Boto3: AssumeRole example which includes role usage - Stack Overflow


text:
Q: What does the ".classname.active" means in css? I am new to the css but never faced the code like this can anyone tell me what this piece of code actually means.
.icon.active {
    fill: $active;
}

A: It means that the element has multiple classes. It targets the .icon which has .active in its class value. It will inherit the properties made in the .icon class as well as .active if any.

.icon {
  background: lightgray;
  color: black;
  width: 200px;
  padding: 5px;
}
.active {
  background: tomato;
}
.icon.active {
  /* Inherits all the properties from .icon class and .active class */
  font-size: 0.75em;
}

I am an icon but not active

I am an icon as well as active. So I am lightweight.

A: .classname.active is a sequence of simple selectors which contains

*

*The universal selector *, which is omitted

*The simple class selector .classname

*The simple class selector .active
Therefore, it selects all elements which have the class classname and the class active.
From the CSS2.1 spec,

For example, the following rule matches any P element whose "class"
  attribute has been assigned a list of space-separated values that
  includes "pastoral" and "marine":
p.marine.pastoral { color: green }

A: This means an element having both classes.
for example:

this rule will only apply to an element that have both classes.

.icon.active {
  color: red;
  font-weight: bold;
  }

Hello

Hello


text:
Q: Declaring a function noexcept conditionally on the testing flag? If one is using exceptions to replace assertions for debugging/testing purposes.
Does it make sense to declare a function noexcept conditionally on the testing flag or this would mess too much with the function interface?
#ifdef MYTESTING
#define MYASSERT(x) if(not x) throw std::logic_error("error not "#x)
#else
#define MYASSERT(x) assert(x);
#endif

double f(double x)
#if not defined(MYTESTING)
noexcept
#endif
{
   MYASSERT(x >= 0);
   return legacy_c_function(x);
}

(I know that legacy_c_function is a C function and it is not going to throw an exception).
I know that many (standard) function are not declared noexcept just in case one wants to test the function internally.
In principle this could have the best of both worlds?
Although unlikely (?), I can see that this method of testing might have diminished value because it can have observable effects in other parts of the code that depend on the noexceptness of this function.
Am I missing something?


text:
Q: How do I make question active of other users?
Possible Duplicate:
How do I get attention for my old, unanswered questions?

There was a question with same description asked 8 months ago. It was no longer active. There is no point in asking same question(exact duplicate).
I have read What is the difference between "hot" and "active" questions? It says that active means "with recent activity." I have written a comment on the question; though, it didn't become active. The question becomes active by writing a new answer, editing the question, or any answer for that question.
I found three ways to make question active but I don't see any feasible way:

*

*Editing the question - I think there is no point in editing question without reason.

*Offering a bounty- I don't want to invest any bounty for that question.

*Answering the question, and deleting the answer- there is no point in doing stupid things like this.

*

*How do I make a question active, so that people will see that question?

*Is there any simple method to make a question active?

A: This unfortunately happens from time to time. Without looking at the question, I really can't help you figure out what's wrong with it. If it was asked eight months ago and has not received answers, something is wrong with it. Ask yourself the following questions:

*

*Is the question too broad, or difficult to understand?

*Is the question missing key pieces of information that are needed to provide answers?

*Does the question show no effort on the part of the author?

*Would answering the question simply take more time than most people in our community care to spend?

*Is the question tagged appropriately?

All of the above items are things you can probably fix with an edit.
If you think the existing question could not be fixed without radically changing it, flag it for our attention and let us know. If it's eight months old with no answers and blocking a similar but potentially better question along the same lines, we'll probably be happy to close it in order to get it out of your way.
If there is absolutely nothing wrong with the existing question, then you'll have to try your luck with the bounty system. You can also conveniently share links to the question in order to get it more attention.
Again, the best answer I can give you is it depends on the question. Without seeing the question, it's hard to say.

A: You can of course propose an edit to the question that improves it. If the question wasn't answered the first time then one reason may be that it was un-answerable, because it lacked detail, or poorly described the problem (at least in the opinion of the people who saw the question).

A: If the only thing you have to contribute is a desire to see some activity on the question, the bounty is the way to do it.  Having a comment make a question active is simply a cheap free way of getting attention for it.  Since comments can be deleted and not viewed (except by mods), it's not obvious to even high ranking users what is going on. A person could comment, make the question active, then delete the comment later.  This could be done repeatedly. I don't see any reason to change it and allow comments to make a question active.
I honestly don't know if adding a comment changes this state or not, but am assuming it doesn't based on the OP's description.  If it does, then I would suggest that it shouldn't.


text:
Q: Redirecting one file to another using dup2 and strtok I have to write a program, in which I need to use strtok and dup2 to redirect one file to another, but I need to also have the user to actually put the command cat < file1 > file2, but not from the shell, but instead by using my program. That's why I need strtok. And the reason my program doesn't work is probably because of that, because I don't really understand how strtok works. I found a similar program on the internet, but they just take the ls command and redirect it to the file. That's it. My program is much more complicated. I mean, it would've been easier just to say in shell cat < file1 > file2, but for some reason they want us to do it this way.
So, anyways, here is what I have so far (here I just combined what I have found on the internet with what I already had from before. We had to do something similar but then the user would just go ls or ls -l. Very simple stuff. This is much harder, for me, at least.)
 #include <fcntl.h>
 #include <unistd.h>
 #include <stdio.h>
 #include <errno.h>
 #include <sys/wait.h>
 #include <string.h>

 int main() {
     pid_t pid;
     char line[256];
     char *args[129];
     int i;
     int fd;
     int status;
     char *temp;

     while (1) {
            printf(">");
            if (fgets(line, 256, stdin) == 0) {
                 exit(0);
        }
            else {
            pid = fork();
            if (pid == 0) {
                i = 0;
                temp = strtok("<",line);
                while (temp != NULL) {
                   args[i++] = temp;
                   temp = strtok(">",line);
                   args[i] = '\0';
                 }
                fd = open("hello", O_RDONLY);
                dup2(fd, STDIN_FILENO);
                fd = open("world", O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
                dup2(fd, STDOUT_FILENO );
                close(fd);
                execvp(args[0], args);
               }

              else {
                  close(fd);
                  wait(&status);
              }
            }
       }
    }

Any help would be greatly appreciated.

A: Besides the backwards strtok arguments, there are other problems.

*

*the parent process closes fd which it never opened (it's an uninitialized variable there, so you're closing a random fd that may not exist)

*the child process does two opens and two dup2's but only one close. You're leaking an fd.

*hardcoded filenames

*you look for a single "<" but have a loop for detecting multiple ">"s

*lack of <stdlib.h> for exit()

*who really thinks S_IRWXU is more readable than 0700?

And if you're aiming to approximate the behavior of a real shell, you should at least ignore whitespace around the redirection operators.


text:
Q: Two Inner Joins in OleDb SQL query I'm trying to make an SQL query with an OleDbCommand into an Access database (.accdb).
While this command works fine (in a OleDbCommand.ExecuteReader()):
string command =
   "SELECT cred.* " +
   "FROM TB_CREDENTIALS cred " +
   "INNER JOIN TB_REL_USERS_CREDENTIALS rel ON cred.CRED_ID = rel.REL_USR_CRED_CRED_ID ";

This other doesn't, and I can't understand why (all examples I see around use the exact same syntax):
string command =
   "SELECT cred.* " +
   "FROM TB_CREDENTIALS cred " +
   "INNER JOIN TB_REL_USERS_CREDENTIALS rel ON cred.CRED_ID = rel.REL_USR_CRED_CRED_ID " +
   "INNER JOIN TB_USERS usr ON usr.USR_ID = rel.REL_USR_CRED_USER_ID ";

The exception given is the following System.Data.OleDb.OleDbException:

Syntax error (missing operator) in query expression 'cred.CRED_ID = rel.REL_USR_CRED_CRED_ID INNER JOIN TB_USERS usr ON usr.USR_ID = rel.REL_USR_CRED_USER_I' (message is cut here)

Version and details:

*

*The database is a .accdb file created on Access 2010

*The connection is created in C# with System.Data.OleDb.OleDbConnection

*The connection provider is "Microsoft.ACE.OLEDB.12.0"
(This seems like a useless query, but of course I'll add a WHERE usr.SOME_FIELD = some_condition)

A: "For multi-table joins, you have to nest the extra joins in brackets:"
SQL multiple join statement


text:
Q: Docker windows 10 can't ping LAN ip I have a container in my Docker under Windows 10.
From this container, i'm not able to ping a ip in my lan :
root@d02eb989ee4e:/home/wwwroot# ping api.xxx.be
PING kust.xxx.be (192.168.0.147) 56(84) bytes of data.
^C
--- kust.xxx.be ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4178ms

The DNS resolution is ok (api.xxx.be => kust.xxx.be => 192.168.0.147) but I have 100% packet loss.
When I ping a other ip/site on the net (like Google) than the ping is ok.
root@d02eb989ee4e:/home/wwwroot# ping www.google.com
PING www.google.com (172.217.168.228) 56(84) bytes of data.
64 bytes from ams15s40-in-f4.1e100.net (172.217.168.228): icmp_seq=1 ttl=37 time=19.0 ms
64 bytes from ams15s40-in-f4.1e100.net (172.217.168.228): icmp_seq=2 ttl=37 time=23.6 ms
^C
--- www.google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 19.051/21.370/23.689/2.319 ms

Why I'm loosing 100% of my packets when I ping a ip in the lan ?
I have made the test from my host and I was able to ping the same ip.
When I try with curl than I have a timeout response
Here is my Docker-composer file :
version: '3'
services:
  apache:
    build: .docker/apache
    container_name: ocr_apache
    ports:
      - '80:80'
    volumes:
      - '.docker/config/vhosts:/etc/apache2/sites-enabled'
      - '.:/home/wwwroot'
    depends_on:
      - php
  php:
    build: .docker/php
    container_name: ocr_php
    volumes:
      - '.:/home/wwwroot'

It's a very simple PHP/Apache containers.
I try to make the ping from the PHP container.
Thank you


text:
Q: Bug in jQuery script on Android I use the script below to change the height of a certain div, based on the window/viewport height:
<script type='text/javascript'>
$(document).ready(function() {
$('.my_container') .css({'min-height': (($(window).height()) - 630)+'px'});

$(window).resize(function(){
    $('.my_container') .css({'min-height': (($(window).height()) - 630)+'px'});

 });
});
</script>

Works great on Ios handheld devices, but on android devices I have a bug. In portrait mode all ok. When I move the device into landscape, (window).height remains with the same value as in portrait mode. If I refresh the page, (window).height gets the correct value for landscape mode.
Tried everything, no luck... Help please?
EDIT: The weirdest part is that if I move - 630 in the script like this:
$('.my_container') .css({'min-height': (($(window).height(-630)))+'px'});

Now it works great on android, not at all on ios!!!

A: Try listening for the onorientationchange and add a timeout to make sure the the properties have been adjusted.
$(document).ready(function() {
    $(window).resize(function(){
        $('.my_container').css({'min-height': (($(window).height()) - 630)+'px'});
     }).trigger("resize");
    $(window).on("orientationchange", function (event) {
        window.setTimeout( function(){ $(window).trigger("resize"); }, 250);
    });
});


text:
Q: How to arc patch a preview diff I created a diff (rather than revision) using arc diff --preview on one machine and I'd like to patch it on another machine. What command do I use? If I try arc patch <ID> I get:
Exception
The diff or revision you specified is either invalid or you don't have
permission to view it.

A: The correct command to run is arc patch --diff <ID>. The difference is that when you use arc patch <ID> it's referring a revision ID rather than a diff ID.


text:
Q: 502 bad gateway - aws application load balancer, ecs I'm having a simple app that I've been experimenting with to learn aws. I first created a http version of a docker image pushed to ecr, ecs using it to create services, and tasks, application load balancing with blue green deployment controlled by codedeploy, and auto-scaling.
The http version worked fine, health checks are passing, no issues.
Now I created the same app with https, with certificate assigned, but the same app fails health checks.
I modified the security group to receive all requests for testing purposes, and assigned a domain through route53 to the load balancer.
I get 502 bad gateway back.
I don't know if it's related to the health checks failing (I guess the load balancer just calls the IP of the container directly), but I have no idea how to debug that, couldn't find a way to find out why the health checks are failing.
But now that I'm trying to access the health check, it throws 502, and when I check the load balancer logs, it shows this (I modified the log to make it more readable):
type https
time 2023-02-10T14:37:00.099726Z
elb app/myapp-load-balancer-staging/c6aabdb240600ca8
client:port myip:38255
target:port targetip:3000
request_processing_time -1
target_processing_time -1
response_processing_time -1
elb_status_code 502
target_status_code -
received_bytes 360
sent_bytes 277
"request" "GET https://api.myapp.com:3000/rest/health HTTP/1.1"
"user_agent" "PostmanRuntime/7.29.0"
ssl_cipher <some text>-SHA256
ssl_protocol TLSv1.2
target_group_arn arn:aws:elasticloadbalancing:eu-west-1:myaccountnumber:targetgroup/myapp-blue-target-staging/id
"trace_id" "Root=1-63e6568c-7c78be0f1e967e59370fbb80"
"domain_name" "api.myapp.com"
"chosen_cert_arn" "arn:aws:acm:eu-west-1:myaccountnumber:certificate/certid"
matched_rule_priority 0
request_creation_time 2023-02-10T14:37:00.096000Z
"actions_executed" "forward"
"redirect_url" "-"
"error_reason" "-"
"target:port_list" "172.31.2.112:3000"
"target_status_code_list" "-"
"classification" "Ambiguous"
"classification_reason" "UndefinedContentLengthSemantics"

This is when I tried to call the endpoint.
The ports match everywhere (3000), the type is HTTPS everywhere, the certs are matching, I have no idea what's wrong, and ran out of ideas about how I could debug this problem.

A:
Now I created the same app with https, with certificate assigned, but the same app fails health checks.

If the targets of your loadbalancer fail the healthcheck, the loadbalancer will not send any traffic to them. You may have changed the protocol in the healthcheck to HTTPS, but the targets may need the previous protocol.
You need to fix the healthchecks to make it work, you could change the healthcheck back or make your targets respond to HTTPS.


text:
Q: Do Ruby objects have a size limit? I'm building some large strings which have a short lifetime within the application.  Will the String objects grow arbitrarily large up to the physical limits of the ruby instance?
What I'm wondering is if, without any intervention in limiting the string size, my application would get hosed by running out of memory, or whether it would degrade gracefully.
Thanks for any input!

A: There is a limit.  A String can be 2**31 - 1 (and accordingly 2**63 - 1 on 64 bit ruby). You can see the limit with:
>> s = String.new("1" * (2**32))
RangeError: bignum too big to convert into `long'
    from (irb):3:in `*'
    from (irb):3
>> s = String.new("1" * (2**31))
RangeError: bignum too big to convert into `long'
    from (irb):4:in `*'
    from (irb):4

Having said that, while you could try to allocate a string that big it will likely fail (at least on a 32 bit system as typically the maximum amount of memory a process can allocate is between 2.5 and 3GB and a 2**31 - 1 length string is nearly 2GB by itself.)  As seen:
>> "1" * (2**30)
NoMemoryError: failed to allocate memory
    from /usr/lib/ruby/1.8/irb.rb:310:in `inspect'
    from /usr/lib/ruby/1.8/irb.rb:310:in `output_value'
    from /usr/lib/ruby/1.8/irb.rb:159:in `eval_input'
    from /usr/lib/ruby/1.8/irb.rb:271:in `signal_status'
    from /usr/lib/ruby/1.8/irb.rb:155:in `eval_input'
    from /usr/lib/ruby/1.8/irb/ruby-lex.rb:244:in `each_top_level_statement'
    from /usr/lib/ruby/1.8/irb/ruby-lex.rb:230:in `loop'
    from /usr/lib/ruby/1.8/irb/ruby-lex.rb:230:in `each_top_level_statement'
    from /usr/lib/ruby/1.8/irb/ruby-lex.rb:229:in `catch'
    from /usr/lib/ruby/1.8/irb/ruby-lex.rb:229:in `each_top_level_statement'
    from /usr/lib/ruby/1.8/irb.rb:154:in `eval_input'
    from /usr/lib/ruby/1.8/irb.rb:71:in `start'
    from /usr/lib/ruby/1.8/irb.rb:70:in `catch'
    from /usr/lib/ruby/1.8/irb.rb:70:in `start'
    from /usr/bin/irb:13
Maybe IRB bug!!

I don't believe there is any way to catch the NoMemoryError.
Updated to reflect the comment from sepp2k


text:
Q: How can I make my app read my contact list? My MainActivity has a getContactList() method that does what it's suppose to. I also have recyclerViews and adapters and all that work when viewing activity_main.xml in an emulator, so the problem isn't there. The problem I'm having is making the app read the arrayList of contacts or just doing it automatically.
Here's my MainActivity code (what's more important is the onCreate method which loads everything it's suppose to and the getContactList()):
package com.app.wolfix;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    ArrayList<ContactModel> arrayList = new ArrayList<ContactModel>();
    MainAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);

        adapter = new MainAdapter(this, arrayList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        Button add_btn = findViewById(R.id.add_btn);

        add_btn.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, Add_Contact.class)));

        Button rem_btn = findViewById(R.id.rem_btn);

        rem_btn.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, Main_Remove_Contact.class)));

        checkPermission();
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 100);
        }else{
            getContactList();
        }
    }

    private void getContactList() {
        Uri uri = ContactsContract.Contacts.CONTENT_URI;

        String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC";

        Cursor cursor = getContentResolver().query(
                uri, null, null, null, sort);

        if (cursor.getCount() > 0){
            while (cursor.moveToNext()){
                String id = cursor.getString(cursor.getColumnIndexOrThrow(
                        ContactsContract.Contacts._ID
                ));
            }
        }
    }
}

checkPermission() is just a verification check that goes for getContactList() once it accepts it, BUT there could be an error there too that I just can't really dissect (it's code from a video tutorial I saw but I have been getting some help and there have been some code changes).
Would it be easier to just make a while() loop somewhere to read all the contacts and add them to arrayList or is there an already added feature that does that already, since I already had that working before. Here's a tutorial I saw a long time ago that used to work on my app too: https://www.youtube.com/watch?v=esDWSfBa-oc
Thanks in advance!

A: I'll recommend you you to look into the given link. I hope you'll find your solution.
Link: android get all contacts


text:
Q: #define confusion with {} and declaration I recently got a C++ program for my school test.
#include<iostream.h>
#define convert(p,q) p+2*q

void main()
{
int a,b,result;
cin>>a>>b;
result=convert(a,b);
cout<<result;
}

This works correctly.
When I put p+2*q in {}, it gives me the error :
"Expression syntax in function main()"
Now when I declare result just before output, like this:
int result=convert(a,b);
It works. Why and why not?

A: Avoid using macros if you have trouble understanding what the compiler complains about. This is what your code looks like when the macro is expanded, when you put the extra {}
result={a+2*b}

And this is what it looks like with the declaration on the same line
int result={a+2*b}

Before the C++11 standard, the former is a syntax error. Since C++11, it is copy-list-initialization of a temporary (see the syntax labeled (10) ).
The latter is aggregate initialization.


text:
Q: Getting Undefined function error message for a function that's defined I'm getting the following error message

Fatal error: Call to undefined
  function get_subject_by_id() in
  /hsphere/local/home/c263430/prupt.com/content.php
  on line 25

This is the function at line 25
 $sel_subject = get_subject_by_id($sel_subj);

This is the function it refers to. How can it be "undefined" as the error message says? Can anyone help?
function get_subject_by_id($subject_id) {
    global $connection;
    $query = "SELECT * ";
    $query .= "FROM subjects ";
    $query .= "WHERE id='" . mysql_real_escape_string($subject_id) ."' ";
                       // note the quotes and escaping wrapper
    $query .= "LIMIT 1";
    $result_set = mysql_query($query, $connection);
    confirm_query($result_set);
    // if no rows are returned, fetch array will return false
    if ($subject = mysql_fetch_array($result_set)) {
        return $subject;
    } else {
        return NULL;
    }
}

Below is the whole code of the page where the function is called
<?php

    //1.Create a database connection
    $connection = mysql_connect("98.130.0.87", "User", "Pass");
    if (!$connection) {
        die("Database connection failed: " . mysql_error());
    }
    $db_select = mysql_select_db("C263430_testorwallo" ,$connection);
    if (!$db_select) {
        die("Database selection failed: " . mysql_error());
    }

    ?>

    <?php
        if (isset($_GET['subj'])){

        $sel_subject = get_subject_by_id($_GET['subj']);
        $sel_pg = 0;
        $sel_page = NULL;
        } elseif (isset($_GET['page'])) {
        $sel_subject = NULL;
        $sel_page = get_page_by_id($_GET['page']);
        } else {
        $sel_subject = NULL;
        $sel_page = NULL;
        }

        ?>
    <?php require_once("includes/functions.php"); ?>
    <?php include("includes/header.php"); ?>

                    <?php

                    $subject_set = get_all_subjects();

                    while ($subject = mysql_fetch_array($subject_set)){
                    echo "

                    {$subject["menu_name"]}
";
                    $page_set = get_pages_for_subject($subject["id"]);

                    echo "
";
                    while($page = mysql_fetch_array($page_set)){
                        echo "
{$page["menu_name"]}
";

                        }
                        echo"
";
                        }

                    ?>

                        <?php if (!is_null($sel_subject)) {

<?php echo $sel_subject['menu_name']; ?>

                        <?php } else if (!is_null($sel_page)) {

<?php echo $sel_page['menu_name]; ?>

                        <?php } else {

 Select a subject or page to edit

                        <?php } ?>

    <?php include("includes/footer.php"); ?>

A: You are calling the function before is has been included.
You must use require_once before calling this function.
<?php
        require_once("includes/functions.php"); // include file here

        if (isset($_GET['subj'])){

        $sel_subject = get_subject_by_id($_GET['subj']);
        $sel_pg = 0;
        $sel_page = NULL;
        } elseif (isset($_GET['page'])) {
        $sel_subject = NULL;
        $sel_page = get_page_by_id($_GET['page']);
        } else {
        $sel_subject = NULL;
        $sel_page = NULL;
        }

        ?>

A: Obviously this has already been answered, but hopefully this will help someone else. I was experiencing this same issue, and it was because somehow x <?php was the first line of my file, instead of just <?php after I had updated my repository.


text:
Q: obtain "server side" variable for use in html/javascript function I'm trying to develop a language web application. It will scrape data from various websites and ask the participant numerous questions etc. I have created the file that scrapes the web page but I'm having difficulty getting the scraped variables from the node.js file. below are some extracts from the node js file:
var pword = function() {
    var request = require("request");
    var cheerio = require("cheerio");

    var aa = Math.floor(Math.random() * 588);

    var words = ['abash', 'aberrant', .....]

    var A = words[aa];
    var urlcollinsdictionary = "http://www.collinsdictionary.com/dictionary/english/";
    var Newurldictionary = urlcollinsdictionary + A;
    request({
        uri: Newurldictionary,
    }, function(error, response, body) {
        var $ = cheerio.load(body);

        $('div.homograph-entry').each(function() {
            var link = $(this);
            var text1 = link.text();
            console.log(A);

            console.log(text1);
        });
    });

}

My node js code works fine. my problem arises when I try to use its "text1" variable or others of its kind in my HTML/javascript coding. I've tried "getelementbyid", "variable exports/imports", even the "%%" method. but still no luck. as you've probably get guess I'm new to programming. please please please help me by making alterations/additions to the HTML code beneath to enable access to the text1 variable and others like it
<html>
    <head>
        language game
        <title>language game</title>
        <br>
        <input type = "button" onclick = "word()" value = "Professional Vocab">
    </head>
    <body>
        <script>
            function word(){
                 alert(text1);
            }
        </script>
    </body>
</html>

Thanks in advance...

A: You can add similar code in your node js file to respond to api calls
var express = require("express");
var app = express();
app.get("sendVar", function(request, response){
    response.send(text1);
}

you will need to do npm install express in your command line
In your front-end side you can use jquery and make an AJAX call inside function word()
function word(){
    $.get("url/sendVar", function(data){
        alert(data);
    });
}


text:
Q: AndEngine load TMX map on multiple devices I have a problem with my game. I have a map 1280x1280px . It is consisted of 40x40 tiles, so 1 tile is 32x32 pixels. The thing is that I can't scale this map to the actual screen size of my device. Is there any way to do that?
This is how I load the tmx file:
public Scene onLoadScene() {
                // TODO Auto-generated method stub
                this.mMainScene = new Scene(1);

                try
                {
                        final TMXLoader tmxLoader = new TMXLoader(this, this.mEngine.getTextureManager(),
                                                                                TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                        this.mTMXTiledMap = tmxLoader.loadFromAsset(this,"gfx/untitled.tmx");

                        //"gfx/0_fire_drill-lvl_01.tmx"
                }
                catch(final TMXLoadException tmxle)
                {
                        Debug.e(tmxle);
                }

                for(TMXLayer tmxLayer : this.mTMXTiledMap.getTMXLayers())
                {
                        this.mMainScene.getChild(0).attachChild(tmxLayer);
                }

                return this.mMainScene;
        }

This is how the map loocks like:
http://postimage.org/image/403w3dfnx/
The actions will happend only in the red area.
Do I need to edin the map?
Thank you in advance!

A: The issue is not with how you're generating the map, it's with your camera.  Create a camera using one of AndEngine's various camera classes.  (I'm a fan of the SmoothCamera.)  Like this:
SmoothCamera camera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 10, 10, 1.0f);

CAMERA_WIDTH and CAMERA_HEIGHT are ints for you to define.  If you set these to smaller values, you'll be more zoomed in.  You can also directly adjust the zoom on the camera.  Like this:
camera.setZoomFactor(5.0f);

And you're probably going to want to set the camera to chase your player entity.  Something like this:
camera.setChaseEntity(pChaseEntity)

Where pChaseEntity is whatever you'd like it to follow.  Hope this helps.


text:
Q: Function is ignored and only trigger at the end of map I'm having some problems with my function, the problem is all the Establishment.finById() is ignored until the end of the map, I need that findById for every item that enters on if. At the end of the map, finById fires, but only occurs on the last map object. I can work around the problem using another map, but I do not want to do this.
I think the problem is something related to async / wait, but I can not figure out what is.
try{
    Logger.log("Info", "Buscando estabelecimentos na API.");
    const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + latitude + ',' + longitude + '&radius=200&type=store&key=' + GOOGLE_PLAY_API;
    axios.get(url).then(response => {
        let resultados = response.data.results;
        if(resultados.length == 0) {
            Logger.log("Info", "Nenhum resultado encontrado pela API");
            return resposta.status(404).send("Nenhum resultado encontrado pela API");
        } else {
            resultados.map((item, i) => {
                let found = item.types.some(r => tipos_estabelecimentos.indexOf(r) >= 0);
                if(found){
                    var _estabelecimento = new Estabelecimento({
                        _id: item.place_id,
                        nome: item.name,
                        localizacao: { type: "Point", coordinates: [item.geometry.location.lng, item.geometry.location.lat]}
                    });
                    Estabelecimento.findById(_estabelecimento._id).then((result) => {
                        if(!result || result.length == 0){
                            _estabelecimento.save().then((success) => {
                                Logger.log("Info", "Cadastrando novo estabelecimento: " + success);
                                listaEstabelecimentos.push(success);
                            }).catch((error) => {
                                if(error){
                                    Logger.log("Erro", "Erro ao cadastrar estabelecimento " + error);
                                }
                            });
                        } else {
                            Logger.log("Info",  "Estabelecimento " + _estabelecimento.name + " já cadastrado. Pulando...");
                        }
                    });
                }
            });
        }
        return resposta.status(200).send(listaEstabelecimentos);
    }).catch(error => {
        return resposta.status(500).send(error);
    });
} catch(error) {
    console.log(error);
}

A: You are right in that it's an issue with findById being asynchronous. If you store all these asynchronous promises in an array and wait for them to finish with Promise.all before you send the listaEstabelecimentos, it will work as expected.
const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${latitude}&radius=200&type=store&key=${GOOGLE_PLAY_API}`;
const listaEstabelecimentos = [];

axios
  .get(url)
  .then(response => {
    let resultados = response.data.results;
    const promises = [];
    if (resultados.length == 0) {
      return resposta.status(404).send("Nenhum resultado encontrado pela API");
    } else {
      resultados.forEach((item, i) => {
        let found = item.types.some(
          r => tipos_estabelecimentos.indexOf(r) >= 0
        );
        if (found) {
          var _estabelecimento = new Estabelecimento({
            _id: item.place_id,
            nome: item.name,
            localizacao: {
              type: "Point",
              coordinates: [
                item.geometry.location.lng,
                item.geometry.location.lat
              ]
            }
          });
          promises.push(
            Estabelecimento.findById(_estabelecimento._id).then(result => {
              if (!result || result.length == 0) {
                _estabelecimento
                  .save()
                  .then(success => {
                    Logger.log(
                      "Info",
                      "Cadastrando novo estabelecimento: " + success
                    );
                    listaEstabelecimentos.push(success);
                  })
                  .catch(error => {
                    if (error) {
                      Logger.log(
                        "Erro",
                        "Erro ao cadastrar estabelecimento " + error
                      );
                    }
                  });
              } else {
                Logger.log(
                  "Info",
                  "Estabelecimento " +
                    _estabelecimento.name +
                    " já cadastrado. Pulando..."
                );
              }
            })
          );
        }
      });
    }
    return Promise.all(promises).then(() => {
      return resposta.status(200).send(listaEstabelecimentos);
    });
  })
  .catch(error => {
    return resposta.status(500).send(error);
  });


text:
Q: TypeError: POST data should be bytes This the background code for the below input code and when I try running it returns this error, can somebody help. I'm using Python 3.7.
File "C:\Users\Sai\anaconda3\lib\urllib\request.py", line 1250, in do_request_
    raise TypeError(msg)
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
if request.data is not None:  # POST
        data = request.data
        if isinstance(data, str):
            msg = "POST data should be bytes, an iterable of bytes, " \
                  "or a file object. It cannot be of type str."
            raise TypeError(msg)
        if not request.has_header('Content-type'):
            request.add_unredirected_header(
                'Content-type',
                'application/x-www-form-urlencoded')
        if (not request.has_header('Content-length')
                and not request.has_header('Transfer-encoding')):
            content_length = self._get_content_length(request)
            if content_length is not None:
                request.add_unredirected_header(
                        'Content-length', str(content_length))


text:
Q: Contact page php Problem - > on clicking send button opens 'send.php' code in the browser and no success message displaying
Html code-
    <form action="send.php" name="form1" method="post" id="third1" style="margin-left:15%; margin-top:5%;
    border:none">

    * Name :
        <input id="name" type="text"size="20" />

    * Email :
        <input id="email" name="email" type="text" size="20" />

    * Subject :
        <input id="subject" name="subject" type="text" size="20" />

    * Your message :

        <textarea id="message" name="message" type="text" class="validate['required']" rows="10"
                    cols="30"></textarea>

    <input type="submit" class="buttonSubmit" value="Send it!" />
</form>

PHP Code:
 <?php

 $name = $_POST['name'];
 $email = $_POST['email'];
 $subject = $_POST['subject'];
 $message = $_POST['message'];

 $to = "email@yahoo.com";
 mail ($to, $subject, $message, "From: " . $name);

 echo "Your message has been sent";
 ?>

Please help me finding out the solution.
Thanks.

A: @nevermind4 has spotted it right - you are missing name attribute on first input.
This does not have to be the real problem here though, can you please enable error reporting to see what is breaking your script?
Secondly mail returns true on success, false otherwise. Display of that message should be conditional, on false you should display a different one.

A: If you see PHP code in the browser then PHP interpreter surely did not processed your code. Even if the PHP is not working / buggy the interpreter will never let the code appear on the client side. So that sounds like, your web server configuration is incomplete, or you see the form page out of the server's scope. Make sure the form html (but at least) the PHP file is in the server's document root directory or subdirectory or a properly configured vhost's path. Plus check your PHP running correctly by some simpler code, like


text:
Q: Unable to set up bond interface from 2 vlans Can someone help me to set up a bond interface from 2 vlans using teamd daemon.
This is how i'm trying to do:
 # ip link add link eth1 name vlan50 type vlan id 50
 # ip link add link eth2 name vlan60 type vlan id 60

But, when i'm trying to add port on bond interface, i'm receiving an error:
# teamdctl team0 port add vlan50

vlan50: Adding port (found ifindex "15").
vlan50: Failed to add port (Invalid argument).

# teamd --version
teamd 1.27

Thank's.


text:
Q: Generic dispatcher for multiple classes I am trying to achieve the same effect in C++. In Python it is so simple to just pass a class method pointer to a dispatcher and to execute the function callback when the specific event occurs. The effect I am looking for is a true generic dispatch class method. Also, the classes should not be related in any way (like in the example below).
class Dispatcher:
    def __init__(self):
        self.map = {}

    def register(self, func, event):
        try:
            self.map[event].append(func)
        except KeyError:
            self.map[event] = [func]

    def dispatch(self, event):
        for func in self.map[event]:
            func(event)

class A:
    def __init__(self):
        pass

    def foo(self, event):
        print("A", event)

class B:
    def __init__(self):
        pass

    def bar(self, event):
        print("B", event)

if __name__ == '__main__':
    d = Dispatcher()
    a = A()
    b = B()
    d.register(a.foo, 6)
    d.register(b.bar, 6)
    d.register(a.foo, 7)

    d.dispatch(6)

Expected output:
A 6
B 6

A: #include <map>
#include <vector>
#include <functional>

using namespace std;

class dispatcher
{
public:
    using event_t = int;
    using callback_t = function<void(event_t)>;
    void register(callback_t c, event_t e)
    {
        m[e].emplace_back(move(c));
    }
    void dispatch(event_t e)
    {
        for(auto&&c: m[e])
            c(e);
    }
private:
    map<event_t, vector<callback_t>> m;
};

You can do something like this. I wrote this in one go on mobile so I have no idea if it works.
That said, this won't really work exactly the same way as you cannot pass functions that automatically capture the thisptr of an object. You'll use it as follows, with a functor:
A a;
d.register([&](int i){a.foo(i);}, 6);


text:
Q: How To Set Globalization Culture in ASP.Net Core? I've been having some trouble with decimal numbers in asp net core mvc. I got it to work in a regular asp net app by adding this to the web.config:
  <system.web>
    ...
    <globalization uiCulture="en" culture="en-US"/>
  </system.web>

But, as there isn't a web.config present in the core app, I'm not quite sure what to do. What would the closest approximation of this in core look like?

A: In Asp.Net Core ,localization is configured in the Startup.ConfigureServices method and can be used throughout the application:
services.AddLocalization(options => options.ResourcesPath = "Resources");

services.AddMvc()
  .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
  .AddDataAnnotationsLocalization();

The current culture on a request is set in the localization Middleware. The localization middleware is enabled in the Startup.Configure method. The localization middleware must be configured before any middleware which might check the request culture (for example, app.UseMvcWithDefaultRoute()).
var supportedCultures = new[]
{
 new CultureInfo("en-US"),
 new CultureInfo("fr"),
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
   DefaultRequestCulture = new RequestCulture("en-US"),
   // Formatting numbers, dates, etc.
   SupportedCultures = supportedCultures,
   // UI strings that we have localized.
   SupportedUICultures = supportedCultures
 });

 app.UseStaticFiles();
 // To configure external authentication,
 // see: http://go.microsoft.com/fwlink/?LinkID=532715
app.UseAuthentication();
app.UseMvcWithDefaultRoute();

For more details , you could refer to the official documentation .


text:
Q: java парсинг веб страницы Ранее с парсингом не сталкивался, а тут перед мной постала такая проблема, есть несколько определенных веб страниц одна из них - https://cybermap.kaspersky.com/
задача заключается в том, что необходимо достать информацию по конкретной стране, а именно виды кибератак ,их количество, каким образом вообще возможно это реализовать подскажите пожалуйста, возможно ли это сделать с помощью jsoup или используя стандартные парсеры и каким образом, заранее спасибо.

A: FLV страничку парсить jsoup api не умеет, так что вряд ли


text:
Q: validate some specific fields in asp.net mvc 5 (vb) I have a form and I want to validate some fields only.
I used to disable some field validation using data-val="false".
It works ok in client side. But serverside it doesn't.
Here is my code

         @Html.RadioButtonFor(Function(model) model.Sex, "M") Male

          @Html.RadioButtonFor(Function(model) model.Sex, "F") Female

      @Html.ValidationMessageFor(Function(model) model.Sex, "", New With {.class = "text-danger"})

    @Html.LabelFor(Function(model) model.DateOfJoin, htmlAttributes:=New With {.class = "col-lg-4 control-label"})

       @Html.EditorFor(Function(model) model.DateOfJoin, New With {.htmlAttributes = New With {.class = "form-control datefield", .data_val = False}})
       @*@Html.ValidationMessageFor(Function(model) model.DateOfJoin, "", New With {.class = "text-danger"})*@

My model is
<MetadataType(GetType(EmployeeMasterMetaData))> _
Partial Public Class EmployeeMaster
  Public Overridable Property DepartmentMaster As DepartmentMaster
  Public Overridable Property DesignationMaster As DesignationMaster
End Class
Public Class EmployeeMasterMetaData

 <Required(ErrorMessage:="Sex is required")>
 Public Property Sex As String

 <Display(Name:="Date Of Join")>
 Public Property DateOfJoin As Date
End Class

I don't want to validate DateOfJoin field and empty values for it, can be save.
How can be done this?

A: if you want the date field to be nullable set your date like the following.
public DateTime? DateOfJoin { get; set; }

The Question mark after the datetime type sets the data as nullable. If Database first method is used, then allow the corresponding field to accept null value.


text:
Q: Can't install cuDNN 5.1.5 with CUDA 8.0 and Tensorflow 0.12 on g2.2xlarge instance The steps I've taken are below.  During the ./configure step, unless I allow the system default for the cuDNN version (v5) instead of specifying v5.1.5 (as I want), I get an error saying that the environment version (v5) for cuDNN doesn't match the target version (5.1.5).  Since I have downloaded the cuDNN v5.1.5 file for CUDA 8.0 from Nvidia I'm baffled.
What's more, after digging through https://github.com/tensorflow/tensorflow/blob/master/third_party/gpus/cuda_configure.bzl around line 240, I'm seeing that the version the bazel configure script checks against seems to only take into account the Major numeral of the cuDNN version (my Major, Minor and Patch numerals within cudnn.h are 5, 1, 5 respectively).  So, I'm uncertain as to how it would ever allow version 5.1.5 to be installed.  Maybe I'm looking at it wrong?
In any case, does anyone have a method of installing cuDNN 5.1.5 with CUDA 8.0 and Tensorflow 0.12 on a g2.2xlarge instance?
Thanks!
Steps
(Note: these work, but it installs cuDNN 5.0, not 5.1.5 as desired)
Provisioning

*

*follow provisioning steps from: https://medium.com/@giltamari/tensorflow-getting-started-gpu-installation-on-ec2-9b9915d95d6f#.2hv67eeek
(i.e. up to but not including: sudo apt-get update && sudo apt-get -y upgrade)

Installing dependencies and tools

*

*familiarize self with:

*

*http://expressionflow.com/2016/10/09/installing-tensorflow-on-an-aws-ec2-p2-gpu-instance/

*http://ramhiser.com/2016/01/05/installing-tensorflow-on-an-aws-ec2-instance-with-gpu-support/

*https://alliseesolutions.wordpress.com/2016/09/08/install-gpu-tensorflow-from-sources-w-ubuntu-16-04-and-cuda-8-0-rc/

*sudo apt-get update

*sudo apt-get upgrade

*sudo apt-get install -y build-essential git python-pip libfreetype6-dev libxft-dev libncurses-dev libopenblas-dev gfortran python-matplotlib libblas-dev liblapack-dev libatlas-base-dev python-dev python-pydot linux-headers-generic linux-image-extra-virtual unzip python-numpy swig python-pandas python-sklearn unzip wget pkg-config zip g++ zlib1g-dev libcurl3-dev

*sudo pip install -U pip
Installing Cuda 8

*

*wget https://developer.nvidia.com/compute/cuda/8.0/prod/local_installers/cuda-repo-ubuntu1604-8-0-local_8.0.44-1_amd64-deb

*sudo dpkg -i cuda-repo-ubuntu1604-8-0-local_8.0.44-1_amd64-deb

*rm cuda-repo-ubuntu1604-8-0-local_8.0.44-1_amd64-deb

*sudo apt-get update

*sudo apt-get install -y cuda
Installing cuDNN

*

*We want to download and install latest version of cuDNN. Downloading cuDNN requires logging into NVIDIA developer site, so we can't use wget to fetch the files. Download the following files from NVIDIA and upload them to your AWS instance.

*download cuDNN 5.1 for CUDA 8.0 on linux

*scp -i ssh-key.pem path/to/downloaded/cudnn ubuntu@ec2{instance}.us-west-1.compute.amazonaws.com:~/

*sudo tar -xzvf cudnn-8.0-linux-x64-v5.1.tgz

*sudo cp cuda/include/cudnn.h /usr/local/cuda/include

*sudo cp cuda/lib64/libcudnn* /usr/local/cuda/lib64

*sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*
Configure the Environment

*

*put following at end of ~/.bashrc:
export CUDA_HOME=/usr/local/cuda
export CUDA_ROOT=/usr/local/cuda
export PATH=$PATH:$CUDA_ROOT/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CUDA_ROOT/lib64:$CUDA_ROOT/extras/CUPTI/lib64

*source ~/.bashrc

*sudo reboot
Installing Bazel

*

*sudo add-apt-repository -y ppa:webupd8team/java

*sudo apt-get update

*echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-  set-selections

*echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-    set-selections

*sudo apt-get install -y oracle-java8-installer

*sudo apt-get install pkg-config zip g++ zlib1g-dev

*scp https://github.com/bazelbuild/bazel/releases/download/0.3.2/bazel-0.3.2-installer-linux-x86_64.sh from local machine to ec2 instance

*chmod +x bazel-0.1.4-installer-linux-x86_64.sh

*./bazel-0.1.4-installer-linux-x86_64.sh --user

*rm bazel-0.1.4-installer-linux-x86_64.sh

*bazel version
Building and Installing Tensorflow

*

*git clone --recurse-submodules https://github.com/tensorflow/tensorflow

*cd tensorflow

*TF_UNOFFICIAL_SETTING=1 ./configure

*hit enter/default for all except:

*

*CUDA version = 8.0, CUDA dependency = 3.0 (k520 gpu)

*bazel build -c opt --config=cuda //tensorflow/cc:tutorials_example_trainer

*bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

*sudo pip install --upgrade /tmp/tensorflow_pkg/tensorflow-0.12.0rc1-cp27-cp27mu-linux_x86_64.whl