text:
Q: The process cannot access the file because it is being used by another process asp.net I have the following method which resizes a given image and caches it
[OutputCache(Duration = 3600, VaryByParam = "id")]

    public ActionResult UserFace(int id)
    {
        var cacheKey = String.Format("userPhotoURICacheKey_{0}", id);
        var defaultFileCacheKey = String.Format("userPhotoDefaultCacheKey");

        HttpContext.Cache[cacheKey] = HttpContext.Cache[cacheKey] ?? UserService.GetPhotoURI(id) ?? string.Empty;
        var userPhoto = (String)HttpContext.Cache[cacheKey];

        if (!string.IsNullOrEmpty(userPhoto))
        {
            var filename = id + ".jpg";

            //crop and resize
            var image = Image.FromFile(new Uri(userPhoto).LocalPath);

            const int resW = 200;
            const int resH = 200;

            var minEdge = Math.Min(image.Width, image.Height);
            var scaleFactor =(float) minEdge/Math.Min(resH, resW);

            var newImage = new Bitmap(resW, resH);
            var sufrace = Graphics.FromImage(newImage);
            sufrace.InterpolationMode = InterpolationMode.HighQualityBicubic;

            sufrace.DrawImage(image, 0, 0, image.Width / scaleFactor, image.Height / scaleFactor);

            var stream = new MemoryStream();
            newImage.Save(stream, ImageFormat.Jpeg);

            stream.Position = 0;
            var file = File(stream, "image/jpg", filename);

            return file;

        }
        HttpContext.Cache[defaultFileCacheKey] = HttpContext.Cache[defaultFileCacheKey] ?? File("~/Content/images/no_photo.jpg", "image/jpg", "nophoto.jpg");
        return (FileResult)HttpContext.Cache[defaultFileCacheKey];
    }

In another method I'm trying to update a cached image with a new one
public void UploadUserImage(byte[] arr, int userId)
    {
        Stream stream = new MemoryStream();
        stream.Write(arr, 0, arr.Length);
        using (var dataManager = factory.GetDataManager())
        {
            var userRepository = dataManager.GetRepository<IUserRepository>();
            var user = GetByID(userId);
            user.PhotoURI =
                        storageFactory.CreateFileStorageSender()
                            .Send(storageConfig.UsersPhotoPath, user.Id.ToString(), stream);
            user.PhotoSize = stream.Length;

            userRepository.Save(user);
            dataManager.Commit();
        }
    }

And I'm getting "The process cannot access the file because it is being used by another process" error.

A: Dispose image after you're done with resize to use it again.

A: You need to dispose the "file", "image" and "newImage" objects from your code. I think the handles to the file object is giving you this error.


text:
Q: "Facebook \ WebDriver \ Exception \ TimeoutException" when using waitFor() in symfony/panther & Laravel I have a laravel app that is using symfony/panther to scrape js loaded web pages.
Upon running, I always get a timeout exception Facebook \ WebDriver \ Exception \ TimeoutException at the waitFor() method.
I've tried increasing the max_execution_time in my php.ini file and also tried doing this in a queue, but I still get the same error
To test I'm using a livewire component
public function handle()

{

    $client = Client::createChromeClient(base_path("drivers/chromedriver"), null, ["port" => 9080]);    // create a chrome client

    $crawler = $client->request('GET', 'https://example.com');

    $client->waitFor('h1'); // Fails here ***********

    $crawler->filter('h1')->text();

}

Any ideas what could solve this timeout exception?
Thanks!

A: Turns out the website being visited was not loading the JS due to console errors. Therefore the waitFor() never sees its element. The errors were CORS Policy errors and 403 errors. Both due to the browser being automated. Incase you have stumbled on this, the solution that worked for me is to add these flags:
$client = Client::createChromeClient(base_path("drivers/chromedriver"), [
    '--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
    '--window-size=1200,1100',
    '--disable-web-security',
    '--disable-blink-features=AutomationControlled',
], ["port" => 9080,]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How an I access data in map to set properties? Using react-three-fiber, i'm trying to set a location of a object dynamically via state. I'm having a issue where if i'm sending in a state it doesn't actually reflect the data. It's very odd. Wondering if anyone knows what's up or how to change. I imagine I have to use some kind of hook or something?
<Canvas linear flat frameloop="demand" orthographic camera={{ position: [0, 0, 50], zoom: 20, up: [0, 0, 1], far: 10000 }}>
            <Suspense fallback={null}>
                {moduleData.floor1.pins.map(e=>
                    <Pin pinInfo={e}/>
                )}
                <Scene mapImage={riverwalkMap}/>
            </Suspense>
            <MapControls enableRotate={false}/>
        </Canvas>

and then the Pin function:
function Pin(pinInfo){
    const pinTexture = useLoader(TextureLoader, setPinColor(pinInfo.pin_color));
  console.log(pinInfo)
    return(
        <>
        <mesh position={[5,-8,0]}>
            <planeGeometry args={[5,5]}/>
            <meshBasicMaterial map={pinTexture} toneMapped={false} transparent={true}/>
        </mesh>
        </>
    )
}

the console log in there returns:
{
  "pinInfo": {
    "pin_color": "yellow",
    "pin_position": {
      "x_pos": 5,
      "y_pos": 10
    },
    "popup_color": "green",
    "popup_content": "
Test
",
    "popup_title": "Test"
  }
}

but if I try to access anything in there like:
pinInfo.pin_position.x_pos

I get undefined. Anyone got any ideas on how I can access that data every time the data changes in that map call?

A: So I feel dumb. The answer is I didn't destructure the prop, so all I had to do was use:
pinInfo.pinInfo.pin_position.x_pos

To get it to work :v


text:
Q: How to pause MySQL before taking an LVM/ZFS snapshot? How can I instruct MySQL to complete all "in-progress" transactions, but to delay starting new ones (without kicking clients off) until I have taken a ZFS or LVM snapshot (which takes less than a second).
e.g.

*

*pause MySQL, waiting for "in-progress" transactions to complete

*sync to disk

*take ZFS/LVM snapshot

*resume MySQL
The point of this is to get a consistent snapshot for backup purposes.  Step 2 takes a fraction of a second.

Step one should not cause client errors, just a very short pause until step 4 is reached.
Are there MySQL commands which can do 1 and 4?  What are they?

A: A hacky way would be, to wait for the transactions to finish:
mysql> FLUSH LOCAL TABLES;
Query OK, 0 rows affected (11.31 sec)
and then getting a read lock:
mysql> FLUSH TABLES WITH READ LOCK;
Query OK, 0 rows affected (22.55 sec)
Now all queries are blocked (ie. they wait for the lock to get released) until your session ends. Mind you - you still have to wait until all transactions are finished. Depending on your workload this can take a while (UPDATE-ing a few million rows...).
You can code this in your favourite script language.
But seriously - why not use Xtrabackup ? It does take care of a consistent snapshot of mysql for you and you can dump it on the filesystem,  and zfs/lvm snapshot it.

A: This is my solution how to create an ZFS snapshot while keeping the global lock, so that MyISAM and InnoDB data files are consistent.
mysql << EOF
    FLUSH TABLES WITH READ LOCK;
    system zfs snapshot data/db@snapname
    UNLOCK TABLES;
EOF


text:
Q: Does the number of involutions in an abelian group of order $2^n$ uniquely determine its isomorphism class? Saw an exam question quite a while ago on determining whether the statement:

Let $G$ be an abelian group of order $2^n$. Suppose that $G$ has $m$ involutions. Then the isomorphism class of $G$ is uniquely determined.

is true. I was never able to solve it - I said that an element of $G$ must have order $2^i$ for some $i \le n$ by Lagrange's and that if $g$ is of order $2^i$ then $g^{2^{i - 1}}$ is an involution, and so there are only $m$ possible values for $g^{2^{i - 1}}$. I blagged that this meant that the orders of the elements are fixed by knowing the number of involutions - but this does not seem to use the abelian property anywhere.
There doesn't seem to be any counterexamples for $n = 2, 3, 4$. Is the statement true? If not, is this argument along the right lines?

A: I think the fundamental theorem of finitely generated abelian groups should be useful here. We know that $G$ is a product of cyclic groups with even order. Then it comes down to does the number of involutions in $G$ determine invariant factors of $G$


text:
Q: PhpMyAdmin Error Trying to fix the problem causing this error message, "Your PHP MySQL library version 5.1.54 differs from your MySQL server version 5.5.7. This may cause unpredictable behavior." Any help would be appreciated.
Installed on the web server - PHP version 5.3.5, Apache 2.2.3, MySQL Client API 5.1.54, MySQLi 5.1.54
MySQL 5.5 installed on seperate DB server.
Do I need to upgrade the MySQL Client API on the web server?  Any ideas how?

A: Considering you have :

*

*MySQL Server v 5.5

*MySQL Client (the php-side library) v 5.1

You should update the client library (on the PHP side), to use a more recent version : you'll gain more by using a 5.5 server than by reverting to a 5.1, I'd say.

On the how to update the php-side component... The simplest solution is probably to update your version of PHP, I'd say -- or, if that's not enough (if PHP is compiled against the 5.1 client library) to recompile PHP yourself, against a 5.5 client library.

Anyway, as long as you don't do any strange stuff, using a 5.1 client with a 5.5 server should generally work -- that's why phpMyAdmin reports a warning, but still works ;-)

A: I Do not know what the hell everyone suggesting you the best method is
1.Go to https://dev.mysql.com/downloads/installer/
2.Install the mysql installer do not configure anything .It will update automatically.
3.Restart all services if you are using wamp.
4.now open phpmyadmin.
Please use wamp its easy yo use and configure.
Asif iqbal


text:
Q: JavaScript removeAttribute not working in IE for href and onclick values I'm making an online advent calendar where you can only open the door of the day. All the doors use JavaScript onclick to display offer eg, 'door10'...

They're all created with this onclick and then at the end of the HTML the following JavaScript function runs which removes the href and onclick attributes of the doors that aren't today, thus removing the ability to open them.
function disableDoor(num) {
var today = new Date();
var day = today.getDate();
var calendar_day = num;
if (calendar_day == day) {
} else {
    var string = "door-" + num + "-link";
    var d = document.getElementById(string);
    d.removeAttribute("href");
    d.removeAttribute("onclick");
}

This all works fine in everything but Internet Explorer where the doors are still clickable even though they shouldn't be. The cursor doesn't change to the hover cursor and if you inspect the element the href and onclick values have been correctly removed, yet you can still 'open the door' even though no href is stated. The HTML now looks like this with the attributes correctly removed...

In the IE inspector, if I 'Edit as HTML', don't change anything, click outside to finish editing and refresh the page it all works fine and I can't click the doors I'm not supposed to. The href element has been properly removed from the page.
It seems like the elements on the page need to refresh or something after the JavaScript has run. My guess is it's something to do with the DOM maybe but I'm pretty new to that area.
Any help would be brilliant as it's got me properly stumped.
Thanks in advance

A: This appears to be a regression in Internet Explorer 11; I checked both Internet Explorer 9 and 10, and neither of the two would repro the issue. I've filed a bug internally to have our team look at resolving the issue as soon as we are able. You can check http://remote.modern.ie moving forward if you like. I constructed a small fiddle that demonstrates issue.
With this particular project, I would actually encourage you to take an alternate route and stand up a single event listener rather than conditionally tearing down dozens of pre-existing listeners. As a quick example of what I mean, consider the following:
(function () {

    "use strict";

    var day = (new Date).getDate(),
        doors = document.querySelectorAll( "div" );

    doors.item( --day ).addEventListener( "click", function openDoor () {
        this.classList.toggle( "open" );
    });

}());

In the above, only today's door will be unlocked — all other doors will remain locked. You can view the actual demo online at http://jsfiddle.net/jonathansampson/n4ed6uw5/.
I hope this work-around helps; in the meantime, I will be working with my team to resolve the regression.

A: Try setting d.onclick = null to disable the onclick handler.

A: You could do this with jQuery. You can attach a click handler to the element and every click handler checks if it is allowed to open.
For the time I'm using a JSON time server because if you use the client time it can be easily modified and every door could be opened.
Please check the following code. If you prefer jsFiddle you can find the same code here. It's doing what you are planning to do. Just add a popover instead of the alert to show the offer and apply your styling.
I have used MetroUI CSS just to do the tile styling.
To add your offers you have to modify the following JSON
var offers = [
    {
        'day': 1,
        'offer': 'something for day'
    },
    {
        'day': 2,
        'offer': 'A 2GB USB Stick'
    },
    ...
];

and add all 24 days and remove the three lines after the comment 'deep copy of offer'. Then you can use the index of your offers JSON to attach the data to the DOM elements.
There is another point that needs to be improved. If the time servers takes too long you can click at another element and both will popup.
Blocking of other clicks and / or a loading progress bar would help.

var adventCalendar = (function () {
    var MONTH = 10; //10 = November / 11 = December --> set to November for testing
    var LAST_DAY = 30; // later 24 --> 30 just for testing

    function Calendar() {
        //console.log('constructor called');
        this.init();
    };
    var offers = [{
        'day': 1,
            'offer': 'something for day'
    }];
    // later you would have for each day a different offer.

    Calendar.prototype.init = function () {
        var offers24days;
        var $calendar = $('#adventCalendar');

        for (var i = 1; i <= LAST_DAY; i++) {
            // console.log(i);
            // deep copy of offer
            var newObject = jQuery.extend(true, {}, offers[0]);
            newObject.day = i;
            newObject.offer += ' ' + i;

            $door = $('
')
                .text(i)
                .data(newObject)
                .appendTo($calendar);

            var that = this; // store reference to this Calendar
            $door.on('click', function () {
                var today = new Date();
                var $this = $(this);
                that.getTime('GMT', function (date) {
                    // This is where you do whatever you want with the time:
                    //console.log(date.getDate());
                    var data = $this.data(); // today from time server

                    if ((data.day <= date.getDate()) && (date.getMonth() == MONTH)) {
                        // Attention! Date month starts at 0 --> 0 = Januar & 10 = November
                        // open allowed
                        alert(data.offer); // later you can use a popover instead of an alert. This is just for the demo.
                    } else {
                        //alert('not allowed'); // just for testing
                    }
                });
            });
        }
    }

    // get time from this SO question http://stackoverflow.com/questions/9486293/does-anyone-know-of-a-good-json-time-server
    // zone not used because time server doesn't support it
    Calendar.prototype.getTime = function (zone, success) {
        //var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
        var url = 'http://time.jsontest.com/?', // no zone support other link is broken
            ud = 'json' + (+new Date());
        window[ud] = function (o) {
            success && success(new Date(o.milliseconds_since_epoch)); //o.datetime));
        };
        document.getElementsByTagName('head')[0].appendChild((function () {
            var s = document.createElement('script');
            s.type = 'text/javascript';
            s.src = url + 'callback=' + ud;
            return s;
        })());
    }

    return {
        Calendar: Calendar
    };
})();

$(function () {
    var advent = new adventCalendar.Calendar();
});
.tile {
    font-family: sans-serif;
    font-size: 4em;
    color: #E2E1E6;
}

<link href="http://cdn.jsdelivr.net/metro-ui-css/2.0.23/min/metro-responsive.min.css" rel="stylesheet"/>
<link href="http://cdn.jsdelivr.net/metro-ui-css/2.0.23/min/metro-bootstrap.min.css" rel="stylesheet"/>


text:
Q: Tooltips issues in dojo stacked column chart Now i am playing with dojo column chart and stacked chart.It works fine when the Page loads. When I hover over different stacked fields and can't get the tool tip displayed.So please request to your how can show my tooltips on mouse hover with respected series name .Here is my js fiddle [link][ http://jsfiddle.net/kairi/S4tH2/ ] .
So kindly request to you how can i show my tooltips on mouse over with respective fields.
So here is my code is
  require(["dojox/charting/Chart",
 "dojox/charting/plot2d/Lines",
 "dojox/charting/axis2d/Default",
 "dojox/charting/plot2d/StackedColumns",
  "dojox/charting/action2d/Tooltip",
  "dojo/ready",
  "dojox/charting/widget/SelectableLegend"],
   function(Chart, Lines, Default, StackedColumns, Tooltip, ready, SelectableLegend) {
ready(function() {
    var chart1 = new Chart("chart1");
    chart1.title = "stacked chart";
    chart1.addPlot("stackedColumnsPlot", {
        type: StackedColumns,
        gap:6,
        lines: true,
        areas: true,
        markers: true,
        labels: true,
        labelStyle:"inside",
        //maxBarSize: 35,
        tension: "2"
    });
chart1.addAxis("x", {
                      dropLabels: false,
                      labelSizeChange: true,
                      rotation:-20,
                      majorTicks:true,
                      majorTickStep:1,
                      minorTicks:false,
                      font: "normal normal bold 12px Tahoma",
                      fontColor: "black",
                     labels: [{"value":1,"text":"A"},{"value":2,"text":"B"},{"value":3,"text":"C"},{"value":4,"text":"D"},{"value":5,"text":"E"},{"value":6,"text":"F"}]
});
    chart1.addAxis("y", {title:"Cost",
      fixLower: "major",
      fixUpper: "major",
       includeZero: true,
      majorTickStep:500,
     max: 7000,
     //from:1000,
     //to:6000,
        vertical: true
    });

    chart1.addSeries("AC",[3000,5000,5500,6000,1300,8280] ,

     {

        plot: "stackedColumnsPlot",
        stroke: {
            color: "#FFFFFF" ,

        },
        fill: "#FFAEAE "
    });
    chart1.addSeries("TV", [2844,7301,6699,620,820,9683] , {
        plot: "stackedColumnsPlot",
        stroke: {
            color: "#FFFFFF"
        },
        fill: "#FFEC94"
    });
    chart1.addSeries("ACCE", [5000,1000,1000,1000,2500,2500] , {
        plot: "stackedColumnsPlot",
        stroke: {
            color: "#FFFFFF"
        },
        fill: "#B4D8E7"
    });
    chart1.addSeries("OTHER", [1500,150,1500,700,7000,0,8000,1300,1300] , {
        plot: "stackedColumnsPlot",
        stroke: {
            color: "#FFFFFF"
        },
        fill: "#56BAEC"
    });

    new Tooltip(chart1, "stackedColumnsPlot", {
        text: function(chartItem) {
            console.debug(chartItem);
        //return "Rating: " + chartItem.run.data[chartItem.index] + "; Total Value: " +   chartItem.y;
          // return  "Comparision Rating: " + chartItem.y;
           return "Value: " + chartItem.run.data[chartItem.index] + "; Stacked Value: "   + chartItem.y;
        }
    });

    chart1.render();

    new SelectableLegend({
        chart: chart1,
        horizontal: true,
        align:top
    }, "chart1SelectableLegend");
   });
   });

Here i want different different tooltips for different different series.So how it is possible.

A: You're just missing the dojo css and the body class attribute.
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.9.3/dojo/resources/dojo.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.9.3/dijit/themes/claro/claro.css" type="text/css">


text:
Q: Problems loading images from bytes in Flutter/Dart I am building an application with Flutter. I am using using a mix of newer technologies that I am struggling to piece together.
My actual issue is that I cannot get images to load in the app when using the following methods:

*

*Insert test data into MongoDB using Mongoengine, images are inserted into GridFS using this method.

*Query GraphQL server for data and retrieve data and receive images from GridFS in form of bytes but in a string - e.g "b'/9j/4AAQSkZJRgABAQEASABIAAD/4V0X .... '"

*Use that bytes string to load images in app with something like Image.memory()
But the images fail to load with an error: type String is not a subtype of type Uint8List. So I tried to convert the string of bytes from a String to raw bytes by doing:
List<int> bytesList = imageData['image']['data'].codeUnits;
Uint8List thumbImageBytes = Uint8List.fromList(bytesList);

I get the following exception:
I/flutter ( 4303): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞══════
I/flutter ( 4303): The following _Exception was thrown while resolving an image:
I/flutter ( 4303): Exception: Could not instantiate image codec.

I have no idea what I can do to fix this, I cannot seem to find anything by googling etc. It would seem there is no information available for this exact scenario except for this S.O question which is what I have tried to do. I have also tried all the methods sugested in comments, followed the suggested links and tried all available combinations of answers, comments, everything.
My set up is as follows;
Main app: Flutter/Dart
API Server: Python/Flask/Mongoengine based GraphQL/Graphene API
Backend Database: MongoDB
The Python side;
A Mongoengine Document model:
class Product(Document):
    meta = {'collection': 'product'}
    name = StringField(unique=True)
    price = FloatField()
    sale_price = FloatField()
    description = StringField()
    image = FileField()
    thumb = FileField()
    created_at = DateTimeField(default=datetime.utcnow)
    edited_at = DateTimeField()
    # user = ReferenceField(User)

    def __repr__(self):
        return f'<Product Model::name: {self.name}>'

A Graphene schema for the model:
class ProductAttribute:
    name = graphene.String()
    price = graphene.Float()
    sale_price = graphene.Float()
    description = graphene.String()
    image = Upload()
    thumb = graphene.String()
    created_at = graphene.DateTime()
    edited_at = graphene.DateTime()

class Product(MongoengineObjectType):
    """Product node."""

    class Meta:
        model = ProductModel
        interfaces = (graphene.relay.Node,)

class CreateProductInput(graphene.InputObjectType, ProductAttribute):
    """Arguments to create a product."""
    pass

class CreateProduct(graphene.Mutation):
    """Create a product."""
    product = graphene.Field(lambda: Product, description="Product created by this mutation.")

    class Arguments:
        input = CreateProductInput()
        image = Upload(required=True)

    def mutate(self, info, image, input):
        data = utils.input_to_dictionary(input)
        data['created_at'] = datetime.utcnow()
        data['edited_at'] = datetime.utcnow()
        print(data)

        product = ProductModel(**data)
        product.save()

        return CreateProduct(product=product)

My base Graphene schema:
class Query(graphene.ObjectType):
    """Query objects for GraphQL API."""

    node = graphene.relay.Node.Field()
    single_product = graphene.relay.Node.Field(schema_product.Product)
    all_products = MongoengineConnectionField(schema_product.Product)

class Mutations(graphene.ObjectType):
    createProduct = schema_product.CreateProduct.Field()

schema = graphene.Schema(query=Query, types=[schema_product.Product], mutation=Mutations)

A: It's very suspicious that:

*

*Your binary data is stored in a String (this is usually wrong).

*Your String happens to be composed entirely of printable characters.

It's therefore likely that you're getting back binary data that's been encoded to a printable string.  A common encoding is base64, and sure enough, when I tried to base64-encode a few different types of images, I see that base64-encoding JPEG files generates a string that starts off with /9j/4AAQSk, just like the string you get.
You are definitely getting back base64-encoded data.  If you aren't doing the encoding yourself, then something is automatically doing the encoding for you, and likely there's a symmetric mechanism to decode it for you.  If not, you'll need to explicitly base64-decode your String to get back binary data. You can use dart:convert to decode it for you.


text:
Q: Is there a way to invert the colors of a SKSpriteNode I was wondering if it was possible to invert the colors (or adjust the hue) of a SKSpriteNode.

A: You can invert the colors by applying a CIFilter with an SKEffect node. Something like this should work:
SKEffectNode *effectNode = [[SKEffectNode alloc] init];
effectNode.filter = [CIFilter filterWithName:@"CIColorInvert"];

SKSpriteNode *node = yourNode; // Make sure this node doesn't already have a parent
[effectNode addChild:node];
[self addChild:effectNode];

Note that an SKScene is an effect node, so this makes inverting an entire scene very easy:
// self is a scene here
self.filter = [CIFilter filterWithName:@"CIColorInvert"];
self.shouldEnableEffects = YES;


text:
Q: std::for_each seems to be cleaning std::string I'm making a simple snake game in c++17 with STL, and I have a problem with parsing board (std::vector) to std::string. I'm using std::for_each with my custom functor. Here's parsing method:
std::string Board::parseBoardToString()
{
    boardToString.resetStringBoard();
    std::for_each(v_board.begin(), v_board.end(), boardToString);
    return boardToString.getStringBoard();
}

Functor prototype (some of these method are for testing, doesn't matter):
class BoardToString
{
    public:
        BoardToString(unsigned _width);
        void operator()(char _cell);
        void resetStringBoard();
        std::string getStringBoard();
        void printStringBoard();
    private:
        bool isItLastLine();
        void resetCharsToNewLine();
        std::string stringBoard;
        const unsigned U_WIDTH;
        unsigned charsToNewLine;
};

And the operator() implementation:
void BoardToString::operator()(char _cell)
{
    stringBoard.push_back(_cell);
    //std::cout << _cell;
    //std::cout << stringBoard.back();
    if (isItLastLine())
    {
        stringBoard.push_back('\n');
        //std::cout << stringBoard.back();
        //std::cout << '\n';
        resetCharsToNewLine();
    }
}

After some tests I'm pretty sure that stringBoard gets cleared when for_each ends his job. GDB shows properly string size when for_each is working, and 0 after that. Both commented couts are working properly. Anyway I don't know why it goes like that. I know I could easily fix it by making a little bit different implementation, but I want to do it right way.

A: So the problem is that your functor object is being copied and the modifications are happening to the copy. This is why it seems to reset when you've finished.
You could change your functor to hold references to the variables you need to modify.
You could use a lambda instead, again holding references to the variables that need to be modified.
But to me the whole approach is too elaborate. Just write a for loop. Nothing gets copied, everything is transparent and direct.

A: Change
std::for_each(v_board.begin(), v_board.end(), boardToString);

to
std::for_each(v_board.begin(), v_board.end(), std::ref(boardToString));

Function objects passed to std algorithms are copied; std ref wraps them up so they are not copied.


text:
Q: Nginx redirection for entire subfolder with screening for special characters I have trouble making this work:
I need all links from
.domain.com/category/1
redirect to
*.domain.com/#something-{"[1]":"[]"}

.domain.com/category/2
redirect to
*.domain.com/#something-{"[2]":"[]"}
So I'm stuck on both making a regular expression and making proper screening for special characters:
So far did that:
    server_name 1.domain.com 2.domain.com 3.domain.com;

    location /^category/1$ {
          return 301 /%23something-{"[1]":"[]"};
        }
    location /^category/2$ {
          return 301 /%23something-{"[2]":"[]"};
        }

And it doesn't work actually and takes some 10 lines, cause I have 10 categories.
And also I need to redirect /category/ itself to /

A: After endless tries I just installed a redirection plugin.


text:
Q: Error 504 when sending email with SmtpClient (.Net Core) I have a web app hosted on AWS cloud composed by a front end (SPA in React.js) and a back end (Web API in .Net Core 3.1).
When I try to send email into a Web API's end point using SmtpClient, the code crashes on the line where I call ConnectAsync method:
await client.ConnectAsync("email-smtp.eu-west-1.amazonaws.com", 465, true);
without returning any error (does not go into the catch).
After a minute the endpoint responds with code 504 Gateway Time-out.
Would anyone know how can I fix it, please?

A: I solved the problem by restarting the AWS virtual machine!
I have not posted the code as I thought it was not a code problem and therefore I thought it was not necessary.
However I hope my solution will be useful to anyone else who has had my same problem.


text:
Q: MongoDB query for time(%Y-%m-%d %H) less than the current time
*

*I need mongodb to get the current time

*I need to format the time (%Y-%m-%d %H)(String)

I am using the navicat for mongodb tool. But my sql can't get the result.
db.getCollection("test").find({
    hours:{
        $lte:{
            hourStr:{
                $dateToString: {
                    format: "%Y-%m-%d %H",
                    date: new ISODate()
                }
            }
        }
    }
})

null

A: The $dateToString is an expression. To evaluate any expression in find() clause, we have to use $expr.
The following query can get us the expected output:
db.test.find({
    $expr:{
        $lte:[
            "$hours",
            {
                $dateToString:{
                    "date":new ISODate(),
                    "format":"%Y-%m-%d %H"
                }
            }
        ]
    }
}).pretty()

Data set:
{ "_id" : ObjectId("5d67bf0e644d83f427bb4917"), "hours" : "2019-08-29 12" }
{ "_id" : ObjectId("5d67bfb1644d83f427bb4918"), "hours" : "2019-08-29 11" }
{ "_id" : ObjectId("5d67c0d1644d83f427bb4919"), "hours" : "2019-08-29 14" }

Current time: ISODate("2019-08-29T12:11:27.287Z")
Output:
{ "_id" : ObjectId("5d67bf0e644d83f427bb4917"), "hours" : "2019-08-29 12" }
{ "_id" : ObjectId("5d67bfb1644d83f427bb4918"), "hours" : "2019-08-29 11" }


text:
Q: Why Localization is not working in my asp.net project? I created 2 resource files, one for English (Resource.en.resx) and another for Persian (Resource.per.resx) in App_LocalResources folder.
I have attached them to my server control (Label1), this way:
<asp:Label ID="Label1" runat="server" Text="Label"
           meta:resourceKey="Label1">
</asp:Label>

and Page header like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Persian.aspx.cs"
    Inherits="Persian" Culture="auto:en-US" UICulture="auto" %>

After browsing in Google chrome I added 2 languages Us English and Persian and set Persian to top priority.
But it still displays in English not Persian, why? I am using VS 2013 and .net 4.5.

A: One wild guess: the language code for Persian is fa (Farsi), not per. Try renaming your resx file to Resource.fa.resx


text:
Q: Avoid looping over array multiple times to rearrange elements I have a situation where I have to rearrange an array of objects based on certain property values, but I'm struggling with how to avoid looping over the array multiple times.
      // first move the labels to the front
      entry.response.forEach( (resp, idx) => {
        if (resp.metadata.response_label && resp.metadata.response_label !== '') {
          rearrangeArray(entry.response, idx, 0);
        }
      });

      // second move the enums in front of the labels
      entry.response.forEach( (resp, idx) => {
        if (resp.metadata.response_type === "enum") {
          rearrangeArray(entry.response, idx, 0);
        }
      });

Firstly, if the response enum exists I need to move those to the front of the array. If a label exists, they need to be moved to the front of the array but after the enum types. The rearrangeArray function also ends up basically looping over the array as well, so this code is pretty inefficient.
Are there any patterns or lodash functions that could help optimize this process?
UPDATE: my rearrangeArray function takes the array, then the old index, then the new index (arr, old_index, new_index)

A: This will sort the array into two arrays then join them. I am not sure what you are doing with the rearrangeArray so you will have use this is an example not a final solution.
var labels = [];
var enums = [];
entry.response.forEach( (resp, idx) => {
  if (resp.metadata.response_label && resp.metadata.response_label !== '') {
    labels.push(resp)
    //rearrangeArray(entry.response, idx, 0);
  } else if (resp.metadata.response_type === "enum") {
    enums.push(resp)
    //rearrangeArray(entry.response, idx, 0);
  }
});
var results = labels.concat(enums)

A: You could use Array.prototype.sort with a custom comparison. Note that sort is not necessarily stable, so this solution can change the order of 'enum's.

function compareValues(a, b) {
  return (a > b) ? 1 : (a < b ? -1 : 0);
}

function weighItem(x) {
  var meta = x.metadata;
  if (meta.response_type === "enum") return 0;
  if (meta.response_label) return 1;
  return 2;
}

function compareResponses(a, b) {
  return compareValues(weighItem(a), weighItem(b));
}

var arr = [
  { metadata: {
    response_type: "enum",
    response_label: ""
  } },
  { metadata: {
    response_type: "not_enum",
    response_label: ""
  } },
  { metadata: {
    response_type: "enum",
    response_label: "asd"
  } },
  { metadata: {
    response_type: "not_enum",
    response_label: "fgh"
  } }
];

arr.sort(compareResponses);

// Log the output
$('pre').text(JSON.stringify(arr, null, 2));


text:
Q: How do I modify a CSS value after the DOM is created? I'm working on a website and the layout is a bit lazy. I found now that because of clearfix, there is a div that its height may be resized if the user triggers it.
My question is, is there a simple way to say that one value of the CSS can't change whenever anything happens, something like:
color:black !IMPOSSIBLETOCHANGE

A: Yes, and you were close enough that you probably knew about this already:
color: black !important;
The only way to override an !important style is to make another !important style of higher priority (like putting it inline on the style= attribute).

A: Use $(document).ready() and change color which will not effect your layout otherwise use color with transparent.
Like
$("#div").css('color','transparent');


text:
Q: XSLT how to sort by variable derived from original field? I'm very new to xslt, and wondering how to do a sort based on a derived variable such as the following (using xslt 1.0):
xml:
<channel>
  <item>
     <title>#2: Second Guy</title>
  </item>
  <item>
     <title>#3: Third Guy</title>
  </item>
  <item>
     <title>#1: First Guy</title>
  </item>
</channel>

xslt attempt:
<xsl:for-each select="channel/item" >

        <xsl:sort select="$rank" data-type="number" order="ascending" />

        <xsl:variable name="rankStartPosn" select="string-length(substring-before(title, '#'))+1"/>
        <xsl:variable name="rankEndPosn" select="string-length(substring-before(title, ':'))+1"/>
        <xsl:variable name="rank" select="substring(title,number($rankStartPosn), number($rankEndPosn)-number($rankStartPosn))"/>

                <p class="Normal">
                    <xsl:value-of select="title" />
                </p>
            </xsl:if>
        </xsl:if>
    </xsl:for-each>

Desired output:
#1: First Guy
#2: Second Guy
#3: Third Guy

Thanks in advance for any help!
Chad

A: Ah...epiphany!
just don't use variables and put the entire expression in the sort's select...like:
<xsl:sort data-type="number" order="ascending"
             select="substring(title,number(string-length(substring-before(title, '#'))+2), number(string-length(substring-before(title, ':'))+1)-number(string-length(substring-before(title, '#'))+2))"/>

A: Simpler:
<xsl:sort select="substring(substring-before(title, ':'), 2)"
          data-type="number" order="ascending" />


text:
Q: Fatal Error: Uncaught --> Smarty: Unable To Load Template File my back-office (dashboard/administrator) wouldn't show anything but a blank white page. After i switched on debug mode I got the following explanation:
Fatal error: Uncaught --> Smarty: Unable to load template file 'helpers/form/form.tpl' <-- thrown in E:\HostingSpaces\User\mywebsite.com\wwwroot\tools\smarty\sysplugins\smarty_internal_templatebase.php on line 129
I've tried to upload newer "fresh" versions of prestashop and to delete the database and bring it back with backups nothing worked. I changed the rights for the whole tools folder, and I have deleted al content of directories /cache/smarty/cache/ except the file index.php and cache/smarty/compile/ also except file index.php.
But nothing helped this morning everything was working until I tried to switch the sub-domain to the main domain for updates.
I'm currently working with Prestashop version: 1.6.1.4
Strangely enough both of the websites have the front-desk working without any problem.
*Obviously i've changed the details in the error message to general info for privacy reasons.
Can anyone please help me with this!!!!!!
PS: I by now have changed the right to each and every folder plus files to 777. And that didn't change a thing.
Although I must add that my ftp program (filezilla) gave me this answer several times:  504 Command not implemented for that parameter

A: This file is missing from your system:
E:\HostingSpaces\User\mywebsite.com\wwwroot\admin\themes\default\template\helpers\form\form.tpl


text:
Q: CSS Style sheet not loading in asp.net mvc using Razor I have used these lines inside head tag
 <link href="~/Content/site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />

Bootstrap seems to work, but site.css is not loading..I even tried
<link href='@Url.Content("~/Content/site.css")' rel="stylesheet" type="text/css" />

I couldn't find any solution. Where am I going wrong?


text:
Q: How to catch an error in a controller when thrown from an Attribute? I've got an ActionFilterAttribute that throws an error if the request is invalid.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AjaxOnlyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if((!filterContext.HttpContext.Request.IsAjaxRequest() ||
            !filterContext.HttpContext.Request.IsXMLHttpRequest()) &&
           (!filterContext.HttpContext.Request.IsLocal))
        {
            throw new InvalidOperationException("This operation can only be accessed via Ajax requests.");
        }
    }
}

Now in my controller, I'd like to catch the error and pass it on to the view
[AjaxOnly]
public JsonpResult List()
{
    try
    {
    var vimeoService = new VimeoService();
    var videos = vimeoService.GetVideosFromChannel(this._vimeoChannelId);

    return this.Jsonp(videos);
    }
    catch (Exception ex)
    {
        var err = new ErrorsModel() { ErrorMessage = ex.Message };
        return this.Jsonp(err, false);
    }
}

Now because the attribute runs before the controller action fires, I can never "catch" the error in the controller, and thereby I cannot relay the error to the view.
How can I achieve this?

A: Alright, so the short answer (tl;dr) is that you need to handle all exceptions in a clean and organized manner. And that is NOT to do it individually in each controller action as I (as a dummy) was originally planning.
Instead, I've wired up my Global Application_Error method to handle all errors, and punch them over to an Error controller with a single index action.
    private void Application_Error()
    {
        // setup the route to Send the error to
        var routeData = new RouteData();
        routeData.Values.Add("action", "Index");

        // Execute the ErrorController instead of the intended controller
        IController errorController = new Controllers.ErrorController();
        errorController.Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData));

        // After the controller executes, clear the error.
        this.Server.ClearError();
    }

My error controller is pretty basic. Basically it takes the last error thrown and pushes the relevant data to the client (In my case, serializes it as JsonP).
public class ErrorController : Controller
{
    public JsonpResult Index()
    {
        var lastError = Server.GetLastError();
        var message = lastError.Message;
        int statusCode;

        // If the lastError is a System.Exception, then we
        // need to manually set the Http StatusCode.
        if (lastError.GetType() == typeof(System.Exception))
        {
            statusCode = 500;
        }
        else
        {
            var httpException = (HttpException)this.Server.GetLastError();
            statusCode = httpException.GetHttpCode();
        }

        // Set the status code header.
        this.Response.StatusCode = statusCode;

        // create a new ErrorsModel that can be past to the client
        var err = new ErrorsModel()
            {
                ErrorMessage = message,
                StatusCode = statusCode
            };
        return this.Jsonp(err, false);
    }
}

Now to add a little robustness to my app, I've created custom Exceptions that correspond to Http StatusCodes.
public sealed class UnauthorizedException : HttpException
{
    /// <summary>
    /// Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided
    /// </summary>
    public UnauthorizedException(string message) : base((int)StatusCode.Unauthorized, message) { }
}

Now I can throw exceptions throughout my app wherever applicable, and they will all get picked up and sent to the client in an easily managable way.
Here's an example of throwing one of said errors.
if (!User.Identity.IsAuthenticated)
    throw new UnauthorizedException("You are not authorized");


text:
Q: Flask/mongodb webapp inconsistent test I have a Flask integration test backed by a 1-node mongodb that randomly fails:
pytest/test_webapi.py:59: in test_register_test
>           assert res.status_code == 302
E           assert <Response streamed [404 NOT FOUND]>.status_code == 302

Fail rate is roughly 50%.
Test in test_webapi.py looking thus:
def test_register_user(self):
    res = self.client.get("/logout")

    class MySMTPServer(smtpd.SMTPServer):
        mails = []
        def process_message(self, peer, mailfrom, rcpttos, data):
            self.mails.append((rcpttos[0], data))

    server = MySMTPServer(('localhost', 12345), None)

    t = threading.Thread(target=asyncore.loop, args=(1,))
    t.start()
    time.sleep(.1)

    try:
        res = self.client.post("/register", data=self.registration)
        assert res.status_code == 200

        mail, hash = server.mails[0]

        self.conn.fsync()
        time.sleep(.1)

        res = self.client.get('/activate/' + hash)
        assert res.status_code == 302
    finally:
        server.close()

The relevant Flask methods from webapi.py:
@app.route("/register", methods=["POST"])
def register_user():
    mail = flask.request.form['mail']
    user = flask.request.form["user"]
    pw = flask.request.form["pass"]

    hash = users.register(user, pw, mail=mail)
    return flask.jsonify({'_id': None}) # XXX

@app.route('/activate/<hash>', methods=['GET'])
def activate_user(hash):
    key = users.activate(hash=hash)
    if not key:
        flask.abort(404)
    return flask.redirect("/")

... are backed by action methods:
make_key = lambda : base64.encodestring(os.urandom(32)).strip()

def register(self, user, pw, **kw):
    hash = self.make_key()
    user = self.new(user, pw, activation=hash, **kw)
    self._send_mail(**user)
    return hash

def activate(self, hash):
    user = self.users.find_one({'activation': hash})
    if not user:
        return None
    key = self.make_key()
    activation = {
        '$unset': {'activation': 1},
        '$set': {'status': 'active', 'key': key} }
    self.users.update({'_id': user['_id']}, activation)
    return user

... where self.users is a mongodb collection.
self.new() persists the entity using safe=True.
Interestingly, several other tests doing similar things never seem to encounter this problem.
I had thought that this would be enough to make sure that the persisted object would be visible to other threads in the pymongo connection pool. What part of the mongodb/pymongo documentation should I have read more carefully? Or is there some weird interaction with asyncore?

A: (ported from comments thread)
In the context of the tests, is the data value just the base64-encoded string of the activation key? base64 contains letters and digits, but also "+" and "/", both of which will be misinterpreted by URL parsers (particularly "/").


text:
Q: Simple Axios GET does nothing in Azure Function I'm unable to get either a success or failure from a simple axios call inside an Azure Function. Actually I can't get APIs to work in Azure full stop, but these are the simplest repo steps.
Code as follows:

const axios = require('axios');

module.exports = function (context, req) {

    context.res = {
        status: 200,
        body: callAPI(),
        headers: {
            "Content-Type": "application/json"
        }
    };
    context.done();

    // Controlled logging
    function Logger(msg) {
        context.log(msg);
    }

    function callAPI() {

        let res = { "state": "init" };

        const config = {
            method: 'get',
            url: 'https://catfact.ninja/fact',
            headers: {
                'Cookie': 'XSRF-TOKEN=eyJpdiI6IjBwRFJSemp0ZTE3dEpRVWEzQm1jRnc9PSIsInZhbHVlIjoic1lMSDZ3cjlUdnRlQnJDQkQ4d2RhcWlPWFUvTjJjekdXSzVNSVBZUUlIQ3N5dVFLaE0ydHpESXhIeUNENlBSWFo1UTFJc1VML2dZakhvaTV0Q3B1V21iUmhYdndtck5uSFhZTVBJUEtuUnBocENmWkJCa2JQOWVYQjFBb1lCbnAiLCJtYWMiOiI5NThlMWE1ZWYyYjA4MmY2YTM0YjE1Njk1ZTgyMDA0YTQxNmIxMDkwN2I5Y2NlOGUzODljZDFlYTE3NzlkZTUwIiwidGFnIjoiIn0%3D; cat_facts_session=eyJpdiI6IktLMDZVVEdSMnN3UDJheDVwUERFc0E9PSIsInZhbHVlIjoib01nZUhMY21XQysyelQza3dxZVRLQ1cybW0zaXgzV0kweGg0eU5Wanpwdkt1QlY3bGZmTDhlU2JlMmJhNVB6VkttelhuLzQ4Q0lHR3BBOVRZTExNVXRDcys2QVliZVFYcUx2U01FSmRHc2tTaDA1NTdMa2V6dVNqcS9JeXN5cVAiLCJtYWMiOiIyYTVjYjM2ZDljZDdhZTgxM2Q3NDYzNWZkZjE3MDljNGNlNDJkOWRmMTlkYjMzMzc4OWFhNzk2ZDg1ODg4Y2QyIiwidGFnIjoiIn0%3D'
            }
        };

        axios(config)
            .then(function (response) {
                res = response.data;
                res.state = "OK"
                Logger(`API called ok, res = ${res}`);
            })
            .catch(function (error) {
                res.state = "FAL"
                Logger(`API failed, err = ${error}`);
            });

        return res;

    }

};

Response suggests the call never happened:
{
  "state": "init"
}


text:
Q: SQL injection with malicious payload disguise in hexadecimal value I am investigating in SQL injection and having a difficulty at hiding payload in hex, hope someone can advise.
For example, the injection:
select name from user where id= ? --> this where I want to inject
I want to make the query like:( just for example only)
select name from user where id= 1 union select 1,2,3
In order to hide my payload, I would like to convert "1 union select 1,2,3" into hexadecimal as below:
select name from products where id=X'3120756E696F6E2073656C65637420313233';
select name from products where id=0x3120756E696F6E2073656C65637420313233;
However, somehow mysql does not interpret my hex into the original string, but consider it as a number which is not logic in my point of view. Anyone can help me with this?
Thanks.

A: It's perfectly logical for MySQL to interpret both 0x3120... and X'3120...' as hexadecimal literal expressions in both cases, and to interpret as a number, string, or blob, as context dictates.
The parser would not under any circumstance interpret such expressions ambiguously, any more than it would misinterpret something like this:
WHERE id = '1 UNION ALL SELECT ...'

It's unambiguously a literal string expression, the same as the two examples provided.
https://dev.mysql.com/doc/refman/5.6/en/hexadecimal-literals.html
I am not inclined to assist anyone with advice on how to exploit a SQL injection vulnerability.  Using urlencoding would allow you to pass something like %31%20%75%6E... which is really no clever exploit at all, only a different way of encoding a URL for presentation at an already-vulnerable interface and would serve no advanced purpose.  Either it's properly written, or it's already vulnerable without such a tactic, and such an encoding wouldn't change that except maybe in rare cases.


text:
Q: How can I determine whether the current window in Vim was opened in a new tab? In Vim, I use the Startify plugin. There's a few ways to open new Vim tabs with this plugin; and I would like to configure my Vim to ensure that :tcd %:h is executed automatically for the first buffer opened into a new Tab after executing Startify.
For purposes like this, Startify provides the StartifyBufferOpened autocmd. Unfortunately, this is executed for every buffer that you open with Startify. Similarly, I'm aware of Vim's built-in TabNew; but this fires any time a new tabpage is created; I only want to :tcd in the tabpages created by Startify.
Is there a VimScript function I could construct that would, when evaluated in several new buffers (i.e. by StartifyBufferOpened), only actually run a particular command if a new tabpage was just created for that buffer?


text:
Q: Slidesshow in javascript I am doing a slidesshow image in javascript:
function ImageLoop( images, speed, width, height ,inc){
  this.img = images;
  this.speed = speed;
  this.width = width;
  this.height = height;
  this.interval = false;
  this.play = false;
  if (inc > this.img.length-1){
      this.index = this.img.length-1;
  } else {
     this.index = inc;
  }
  this.returned = false;

  function preloadImages(){
     for (i in this.img){
         var _i = new Image();
         i.src = this.img[i];
     }
  }

  preloadImages();

  thisObj = this;
  function onInterval( ){
     thisObj.next();
  }

  function set(index) {
     var im = document.getElementById("imageloop");
     if (index > this.img.length-1){
        var idx = this.img.length-1;
     } else {
        var idx = index;
     }
     im.src = this.img[idx];
  }

  function next( ){
     if (this.play){
        if (next == this.img.length-1){
            this.returned = false;
        }
        if ((this.index == this.img.length-1) && !this.returned){
           this.returned = true;
           return;
        }
        var next = (this.index < this.img.length-1) ? ++this.index : 0;
        this.set(next);
     }
  }

  function start( ){
     this.play = true;
     if (!this.interval){
        this.interval = setInterval(onInterval, this.speed);
     }
  }

  function stop( ){
     this.play = false;
     if (this.interval){
        clearInterval(this.interval);
        this.interval = false;
     }
  }

  function changeSpeed( adjust ){
     this.speed += adjust;
     clearInterval(this.interval);
     this.interval = setInterval(onInterval, this.speed);
  }

  function serendre( place ) {
     switch (place){
        case "beginning":
                         this.stop();
                         this.set(0);
                         break;
        case "left":
                    this.stop();
                    var next = (this.index > 0) ? --this.index : this.img.length-1;
                    this.set(next);
                    break;
        case "right":
                     this.stop();
                     var next = (this.index < this.img.length-1) ? ++this.index : 0;
                     this.set(next);
                     break;
        case "end":
                   this.stop();
                   this.set(this.img.length-1);
                   break;
     }
  }

  // Setup
  var d = document.getElementById("il");
  var image = "<img src='" + this.img[this.index] + "' id='imageloop' width='" + this.width + "' height='" + this.height + "' />";
  d.innerHTML = image;

  // Add Functions
  this.preloadImages = preloadImages;
  this.set = set;
  this.next = next;
  this.start = start;
  this.stop = stop;
  this.changeSpeed = changeSpeed;
  this.serendre = serendre;

}
In IE is working fine but on other I have problem. Like when I set the index to a other number and start it in Ie working but on other it start from index 0. I don't know what is the problem of it. Can someone help me with that ?

A: I do not know your goal in what you are doing. But if you just need that functionality (image slideshow), consider using existing javascript library and solution.
For jQuery it can be:

*

*http://sorgalla.com/projects/jcarousel/

*http://gmarwaha.com/jquery/jcarousellite/

*http://thomlx.free.fr/jquery/jquery_carousel.htm

A: I really like Lytebox.  It has the slideshow feature you want (as well as others) and is very easy to use.  It also works in IE6, etc.

A: The best approach to creating JS code that is compatible with all somewhat modern browsers (starting with IE6 and Firefox2) is to use a javascript library that takes care of those things for you. jQuery is an excellent library that has many plugins, including slideshows etc... You can find more information at link text and a bunch of great examples of UI features such as slideshows at link text
all the best,
yuval


text:
Q: 100% width w/o parent element I'm a bit confused. I'm building an To-Do List app and I'm trying to set the header as 100% of the screen width. I have the correct meta tags, I believe, but setting the header at 100% width is stretching the element past the right side of the screen. Is there something I'm doing wrong?
<!DOCTYPE html>
<html>
 <head>

 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Todo List App</title>

 <link rel="stylesheet" text="text/css" href="style.css">

 </head>
 <body>
     <header>

         <input type="text" placeholder="Enter an activity...">

         <button></button>

     </header>
 </body>
</html>

@charset "UTF-8";

header {
width: 100%;
height: 80px;
position: fixed;
padding: 15px;
top: 0px;
left: 0px;
z-index: 5;
background: #25b99a;
box-shadow:0px 2px 4px rgba(44, 62, 80, 0.15);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
}

header input {
width: 100%;
height: 50px;
float: left;
background: rgba(255,255,255,0.2);
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
border-top-right-radius: 25px;
border-bottom-right-radius: 25px;
border-radius: 5px;
border: 0px;
box-shadow: none;
outline: none;
}

A: You need to include the box-sizing property.
Info from MDN

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
}

header {
  width: 100%;
  height: 80px;
  position: fixed;
  padding: 15px;
  top: 0px;
  left: 0px;
  z-index: 5;
  background: #25b99a;
  box-shadow: 0px 2px 4px rgba(44, 62, 80, 0.15);
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}

header input {
  width: 100%;
  height: 50px;
  float: left;
  background: rgba(255, 255, 255, 0.2);
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
  border-radius: 5px;
  border: 0px;
  box-shadow: none;
  outline: none;
}
<header>
  <input type="text" placeholder="Enter an activity...">
  <button></button>
</header>


text:
Q: Selecting two highest values from a list, whilst keeping a record of their index positions? I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.
For example:
a = [1,2,7,9,3,4]

Desired output:
maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

A: Use sorted and list.index:
MaxVal, secondMax = sorted(a)[-2:]
index_max = a.index(MaxVal)
index_secondMax = a.index(secondMax)

A: import numpy as np
a = [1,2,7,9,3,4]
max_value = np.sort(a)[-1]
max_value2 = np.sort(a)[-2]
int(np.squeeze(np.where(a == max_value))),int(np.squeeze(np.where(a == max_value2)))

A: You can use enumerate to pair the values with their indices, sort using the second value (the value, not it's index) and keep the last ones
from operator import itemgetter
a = [1,2,7,9,3,4]
res = list(sorted(enumerate(a), key=itemgetter(1)))[-2:]

print(res) # [(2, 7), (3, 9)]
print("1st Max", res[-1][1], "at", res[-1][0])  # 1st Max 9 at 3
print("2nd Max", res[-2][1], "at", res[-2][0])  # 2nd Max 7 at 2

A: The solution using sorted is cleanest, but for long lists this might be faster (linear complexity):
a = [1,2,7,9,3,4]
index_max, maxVal = max(enumerate(a), key=lambda x:x[1])
index_secondMax, secondMax =  max([t for t in enumerate(a) if t[0] != index_max],  key=lambda x:x[1])

A: Numpy is quite god for things like this
import numpy as np

a = [1,2,7,9,3,4]

b = np.sort([(v, i) for i, v in enumerate(a)])

maxVal = b[-1, 0]
index_max = b[-1, 1]

secondMax = b[-2, 0]
index_sec_max = b[-2, 1]

print(maxVal)
print(secondMax)

print(index_max)
print(index_sec_max)

A: secondMax, Max  = sorted(a)[-2:]
index_max = a.index(Max)
index_secondMax = a.index(secondMax)


text:
Q: Error: Unable to find Mono. Ensure that Mono's '/bin' folder is added to your environment's PATH variable (on MacOS) I set (Omnisharp: Use Global Mono) to "always."
and I typed the latest in ("omnisharp.path":) "latest" but I'm facing this error
[ERROR] Error: Unable to find Mono. Ensure that Mono's '/bin' folder is added to your environment's PATH variable.

A: Open a terminal and check if path is added with
echo $PATH

if the path to Mono bin Folder is missing add it with (replace [PATH to the mono bin Folder] with your path), normally the path is /Library/Frameworks/Mono.framework/Versions/Current/bin:
export PATH=$PATH:[PATH to the mono bin Folder]


text:
Q: G Suite add-on Trigger for Calender eventUpdate should get called when changing event with 3rd party calender app I am struggling a bit with the understanding of the trigger capability of Google Apps Script and I am trying to find out what the capabilities and constraints are.
The idea is to have a G Suite add-on with Calender eventOpen and eventUpdate triggers.
My understanding is that those triggers are hit when the user has the extension installed and opens/updated the event. However this would mean if a user changes the event with a calender mobile app, those triggers will not get called.
Is there a way to call them using the Apps Script triggers? I would like to avoid to use the Push Notification since this seems very laborious. Maybe there is an easy way around it?

A: I understand that you want an Apps Script trigger that fires every time that a Calendar event is modified. If that is your goal, then you could use the TriggerBuilder.forUserCalendar() class to build the installable trigger. On those docs you will find example codes to guide you, but feel free to ask me if you have any doubt.


text:
Q: ssms upgrade without losing DB credentials I have to upgrade SSMS for an end-user. The problem is that she saves a lot of users and passwords saved with the option of "remember password". I scanned over the internet and couldn't find a solution. Another thing I wish to know is - When the wizard installs the new SSMS - Does it override the old one?
Can 2 versions of SSMS live separately on the same server and can be used by need?


text:
Q: Free Body Diagram of Perpendicular Forces of Inclined Plane I've been puzzling over this for a couple days now and I can't find an answer on the internet.

I have two wedges (inclined planes) facing each other (in the image above) and one of them (the black triangle) is fixed in place and the other can move.  I apply a force F to the moving wedge.  I want to know two things: (1) if my calculation for the force C is correct and (2) how to create a free body diagram of this system that represents what is going on.
Because the wedges act like a simple inclined plane, he force C should be equal to the "rise" of the wedges over the "run" (the slope).  In this case, that slope can be found with 1/tan(θ).  This means that C = F / tan(θ).  For example if F = 100 Newtons and θ = 30 Degrees then C = 173 Newtons.  Is this correct?
Second, if this is correct, how would I draw a diagram of this where the force vectors work out correctly?  Most of the typical examples with this type of problem are configured in a different way and never show how force C would be derived.


text:
Q: Dynamic grid on resize mainwindow I'll start by explaining what I'm trying to accomplish. So I have a list with images and those images have a name. I'm trying to place these images (and their names beneath them) in a grid next to each other and I would like the grid to have extra columns/rows depending on the size of my main window.
example
What I have done so far is, I've added the following in my custom grid class to track the resizing of my mainwindow.
mainWindow = (MainWindow)Application.Current.MainWindow;
mainWindow.MainWindowResize += mainWindow_MainWindowResize;

In "mainWindow_MainWindowResize" I made the 'calculations' to add/remove extra columns or rows & this works fine, BUT I was wondering if there is a better way to do this (for example by just using xaml).

A: Here is a sample using UniformGrid in pure XAML
<UniformGrid Columns="5"
             Rows="3">
    <UniformGrid.Resources>
        <DataTemplate x:Key="MyImageTemplate">
            <DockPanel LastChildFill="True">
                <TextBlock Text="Image Title"
                           DockPanel.Dock="Bottom"
                           HorizontalAlignment="Center" />
                <Image Source="pr.png" />
            </DockPanel>
        </DataTemplate>
    </UniformGrid.Resources>
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
    <ContentControl ContentTemplate="{StaticResource MyImageTemplate}" />
</UniformGrid>

result

The above is just an example, you may adjust as needed


text:
Q: how to pass parameters to batch file using java textbox I am running a batch file, where I want to pass parameters from Textbox
Batch: test.bat
@echo off
set par1=%1
echo Parameter 1 is %par1%
mkdir %par1%

Java:
 Process p = Runtime.getRuntime().exec("c:\\test.bat");

How to pass parameter to Test.bat file?

A: You can just add the parameter to the command line:
Process p = Runtime.getRuntime().exec("c:\\test.bat xyz");

This will pass xyz to the batch file.
But Runtime.getRuntime().exec(..) is not a good way to execute an external program. You should use ProcessBuilder instead.

A: Pass them in an array:
 Runtime.getRuntime().exec(new String[] {"c:\\test.bat", "-p", "firstParam", "--secondparam"} )


text:
Q: Dynamic Property Access Trying to figure out a topic and I can't seam to get it to work. Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Experiments</title>
</head>
<body>
<script>
    var AGE = (function(){
        var saying1 = "this is saying 1 ";
        var saying2 = "this is saying 2 ";
        var saying3 = "this is saying 3 ";

        return {
            say: function(numbers){
                return this["saying" + numbers];
            },
            sayFunction: function(){
                return "Hello World ";
            }

        };
    })();
    document.write(AGE.sayFunction());
    document.write(AGE.say(1));
    document.write(AGE.say(2));
    document.write(AGE.say(3));

</script>
</body>
</html>

This doesn't seam to be working, tried replacing "return this["saying" + numbers];" with "return AGE["saying" + numbers];" and "return ["saying" + numbers];" Anyone know what I am missing or messing up on?
var AGE = (function() {
   return {
     saying1: "this is saying 1",
     saying2: "this is saying 2 ",
     saying3: "this is saying 3 ",

     say: function(numbers) {
       return this["saying" + numbers];
     },

     sayFunction: function() {
       return "Hello World ";
     }
   };
 })();

 console.log(AGE.sayFunction());
 console.log(AGE.say(1));
 console.log(AGE.say(2));
 console.log(AGE.say(3));

Thanks Paul for the answer only issue now is saying1, saying2 and saying3 are public now.
var AGE = (function(){
    var say1 = "this is saying 1 ";
    var say2 = "this is saying 2 ";
    var say3 = "this is saying 3 ";

    return {
        say: function(){
            return say1;
        }
    };
})();
document.write(AGE.say());

This is the effect that I am trying to achieve but with bracket notation I don't know now if "Dynamic Property Access" can work with private access through a public function?

A: the sayings are not in this, they are local variables of the scope, I suggest creating a map instead:
var AGE = (function(){
    var sayings = {
        1: "this is saying 1 ",
        2: "this is saying 2 ",
        3: "this is saying 3 "
    };

    return {
        say: function(numbers){
            return sayings[numbers];
        },
        sayFunction: function(){
            return "Hello World ";
        }
    };
})();

A: Those aren't properties (of anything, but certainly not of the anonymous object you're returning).
Make them actual properties, and it works:

 var AGE = (function() {
   return {
     saying1: "this is saying 1",
     saying2: "this is saying 2 ",
     saying3: "this is saying 3 ",

     say: function(numbers) {
       return this["saying" + numbers];
     },

     sayFunction: function() {
       return "Hello World ";
     }
   };
 })();

 console.log(AGE.sayFunction());
 console.log(AGE.say(1));
 console.log(AGE.say(2));
 console.log(AGE.say(3));


text:
Q: Android make button disabled after setting alpha 0 probably another rhetorical question.
In iOS when we set a view's (any any UIView subclass such as UIButton) alpha to 0, iOS by default disables all user interaction on that view.
I got an Android app where I animate fade out the view by:
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(buttonSelectionContainer, "alpha", 1, 0);
fadeOut.setDuration(500);
fadeOut.start();

However, I am noticing that when I tap the screen, the animation starts again, leading me to believe, in Android, even when a button alpha is set to 0, it is still tappable, is this true?
Is there a way to globally tell Android to disable user interaction for a view (and all its subviews) when its alpha is set to 0, either explicitly through using:
view.setAlpha(0.0f);

or through the ObjectAnimator like the above code block I used ?
A temporary work around for my problem would probably be to schedule this code to run after 500 ms:
// psuedocode: after 500ms
dispatch_doSomethingAfter(500)
{
    myButton.setEnabled(false);
}

Not the ideal solution but might be my only solution, unless some bright Android developers out there has a better solution ?

A: Use addListener on your ObjectAnimator to control what happens after the animation has finished.
fadeOut.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                 button.setEnabled(false);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
});

A: You can create an Animator.AnimatorListener that automatically disables the target View when the animation ends.
Declare your custom DisableViewOnEndAnimatorListener class:
public class DisableViewOnEndAnimatorListener extends AnimatorListenerAdapter {
    @Override
    public void onAnimationEnd(Animator animation) {
        if (animation instanceof ObjectAnimator) {
            final Object target = ((ObjectAnimator) animation).getTarget();
            if (target instanceof View) {
                ((View) target).setEnabled(false);
            }
        }
    }
}

Then, in your code:
DisableViewOnEndAnimatorListener endAnimatorListener = new DisableViewOnEndAnimatorListener();

ObjectAnimator button1FadeOut = ObjectAnimator.ofFloat(button1, "alpha", 1, 0);
button1FadeOut.setDuration(500);
button1FadeOut.addListener(endAnimatorListener);
button1FadeOut.start();

ObjectAnimator button2FadeOut = ObjectAnimator.ofFloat(button2, "alpha", 1, 0);
button2FadeOut.setDuration(500);
button2FadeOut.addListener(endAnimatorListener);
button2FadeOut.start();


text:
Q: How to calculate the decimal point offset from 0 I'm having a bit of a go slow in the brain department today and thought maybe somone had done this before.
Given the numbers below, what simple means could I use in Javascript to work out the decimal point as a number, eg:

*

*1 = Decimal point: 0

*10 = Decimal point: 1

*1678 = Decimal point: 3

*-0.56 = Decimal point: -1

*-0.0045 = Decimal point: -3

A: log(x)/log(10) // log base 10 of x
Need absolute value if you want to pass negative numbers for x.
Need floor if you want integer result.
Example:
Math.floor(Math.log(Math.abs(-0.56))/Math.log(10));

A: It's not entirely clear what your algorithm is. What makes -0.56 decimal point -1 and not -2? Similarly, does the sign of the original number matter to the sign of the decimal point?
You can take the log base 10 of the absolute value of the numbers, then truncate to the integer to get the "decimal point" and get all of the results shown above. But, there are a number of algorithms that will do so within the provided set while diverging on other numbers.


text:
Q: How to change one index of character pointer in c? I am trying to take change a single character in the pointer array I have declared, but I get a seg fault every time.  This is what I am trying to do:
void manip(char * bits)
{
  bits[3] = 'a';
}

int main() {
  char * bits;
  bits = "testtesttest";
  manip(bits);
  printf("%s", bits);
  return 0;
}

What am I doing wrong?


text:
Q: Marker not showing @react-google-maps/api on localhost next.js I'm aware there are similar questions to this... but nothing has answered my question
I'm trying to add a marker to my google map but it is not showing up when I'm running the project locally (It works fine when on my live site)
Heres my component
import { React, useMemo } from "react";

import { GoogleMap, Marker, useJsApiLoader } from "@react-google-maps/api";

import MapContainerStyles from "./styles/MapContainerStyles";

const Map = () => {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: API_KEY,
  });

  const center = useMemo(() => ({ lat: -30.292038, lng: 153.118896 }), []);

  const onLoad = (marker) => {
    console.log("marker: ", marker);
  };

  const options = {
    mapTypeControl: false,
    streetViewControl: false,
    fullscreenControl: false,
  };

  if (!isLoaded) return
Loading...
;

  return (
      <GoogleMap zoom={15} options={options} center={center} mapContainerClassName="map-container">
        <Marker onLoad={onLoad} position={center} />
      </GoogleMap>
  );
};

export default Map;

The console logs for the markers onLoad return the following

There are no errors in the console
I've looked at multiple resources and it appears as if I am doing everything correctly.. but the marker is just not showing
any help would be appreciated

A: The problem that you're having is something introduced by React 18 related to Strict Mode. If you remove Strict Mode from your app, the markers should appear. That also explains why Smokey Dawson's app worked in production — I'm guessing they removed Strict Mode.
Here's a little documentation about it in a closed issue from the repo: https://github.com/JustFly1984/react-google-maps-api/issues/2978
Hopefully you already resolved this, but if not, I figured I'd answer it since I ran into the same problem this week.

A: for react 18+ you have to import MarkerF instead of Marker and use in it as a tag(of course)
import {MarkerF} from '@react-google-maps/api'

Source

A: I had the same issue when using @react-google-maps/api@2.10.2
To solve the problem I downgraded to @react-google-maps/api@2.7.0

A: You have to change your Marker html Element to MarkerF, and change your import to MarkerF as well. After that it should work. I had this same issue, and oddly enough I had it working for about a day with just Marker and out of the blue nextJS decided it didn't like that anymore and I banged my head against the wall until I found this out. Also I can't comment on Strict mode having any effect on it, I didn't test out removing strict mode. It's worth a shot though.

A: Additionally to importing MarkerF, you will want to remove reactStrictMode: true from your next.config.js file.

A: This is how I implemented it:

It might be because you did not specify the position prop, which most times takes the same coordinates as the center coordinates.
  const markerCoors = {
    lat: x,
    lng: y,
  };


text:
Q: Homemade dual USB hub Can I make a dual port USB HUB without a controller (parallel connection) it is only going to be used for a mouse and a keyboard. In other words will the Pc recognize them as 2 devices. Thanks

A: USB interface circuits are designed as point to point with transceivers on each end. If you try to join or "direct wire" together two of them on one end of an interface the local transceivers will conflict with each other when trying to drive back to the computer. This problem is solved by using a USB hub which provides internal routing circuitry to allow the computer end of the interface to be fanned out to multiple devices.

A: If you mean simply soldering together two USB ports to make a "pigtail" then the answer is No, this will not work.  You must have active electronics to act as a hub allowing multiple devices to be enumerated.


text:
Q: SkobblerMaps Android: How to create navigation log file I want to simulate a drive using the SKNavigationSettings.SKNavigationType.FILE. Is there an easy way to generate one of these files? I see the Seattle.log in the demo project, and I could just edit some coordinates and make my own however it would be great to simulate a real drive. Also I am not sure what all of the entries are:
"47.655942 -122.137419, 11.000000, 19.000000, 0.000000, 1380803959889470, 03.10.2013 15:39:19" (what are 11.000000, 19.000000, 0.000000?)
Update: I still do not have a way of doing this and I do not understand some of the values (listed above). The file is Seattle.log and it just consists of a bunch of lines like the one above separated by newlines.

A: You can find the full SDK documentation here.
https://www.developer.skobbler.com/docs/android/3.0.2/index.html
Yes, you can obtain a logging file with data collected from a real drive. You can use the startLoggingPositions(String filePath, SPositionLoggingType positionLoggingType) and public boolean stopLoggingPositions() from the SKPositionLoggingManager class (com.skobbler.ngx.positioner.logging package) to accomplish that. You will obtain a log file (if the positionLoggingType is set to SK_POSITION_LOGGING_TYPE_LOG) similar to Seattle.log at the specified path.
The values stored in the file are (in this order): Latitude, Longitude, Course, Speed, Accuracy, Timestamp.


text:
Q: Verificar si Activity ha recibido información extra desde un Intent Tengo muchas Activity en mi aplicación las cuales pueden ser abiertas desde varios lugares.
Siempre son invocadas desde Intents, sólo que a veces me interesa pasarles información extra, y otras veces no.
¿Hay alguna manera de saber cuándo el Intent que llama a una Activity le ha pasado información extra y cuándo no?
Muestro algunos fragmentos del código.
Intent que no pasa extras
    final Button btnOficio = (Button) findViewById(R.id.btn_oficio);
    btnOficio.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            utilClass.setFabric("btnOficio", TAG, strFechaHoy);
            Intent i = new Intent(BreviarioActivity.this, OficioActivity.class);
            startActivity(i);
        }
    });

    final Button btnLaudes = (Button) findViewById(R.id.btn_laudes);
    btnLaudes.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            utilClass.setFabric("btnLaudes", TAG, strFechaHoy);
            Intent i = new Intent(BreviarioActivity.this, LaudesActivity.class);
            startActivity(i);

        }
    });

    //...etc

Intent que sí pasa extras
  public boolean onContextItemSelected(MenuItem item) {
        Intent i=null;
        switch (item.getItemId()) {
            case R.id.nav_oficio:
                utilClass.setFabric("ctxOficio", TAG, strFecha);
                i = new Intent(this, OficioActivity.class);
                i.putExtra("FECHA", strFecha);
                startActivity(i);
                return true;

            case R.id.nav_laudes:
                utilClass.setFabric("ctxLaudes", TAG, strFecha);
                i = new Intent(this, LaudesActivity.class);
                i.putExtra("FECHA", strFecha);
                startActivity(i);
                return true;

           //más case...

            default:
                return super.onContextItemSelected(item);
        }
    }

A: Comprobando retorno de getStringExtra()
Para saber si has facilitado un extra debes hacer uso de Intent.getStringExtra() y comprobar si el resultado es null:

Returns String: the value of an item that previously added with putExtra() or null if no String value was found.

En castellano:

Devuelve String: el valor de un elemento que ha sido agregado previamente con putExtra() o null si no se encontró el valor String.

Ejemplo:
/* final Intent intent = getActivity().getIntent(); */
String strFecha = intent.getStringExtra("FECHA");
if (strFecha == null) {
    /* Hacer lo necesario en caso de NO recibir la fecha */
} else {
    /* Hacer lo necesario en caso de haber recibido la fecha */
}

Comprobando existencia del valor con hasExtra()
También podrías hacer uso de Intent.hasExtra():
/* final Intent intent = getActivity().getIntent(); */
if (intent.hasExtra("FECHA")) {
    /* Hacer lo necesario en caso de NO recibir la fecha */
} else {
    /* Hacer lo necesario en caso de haber recibido la fecha */
}

Comprobando si hay datos extras con getExtras()
Una llamada a Intent.getExtras() obtiene una instancia de Bundle con los valores o bien null en caso de no haber ninguno:

Returns Bundle: the map of all extras previously added with putExtra() or null if none have been added.

En castellano:

Devuelve Bundle: un mapa con todos los extras agregados previamente putExtra() o null si no fue agregado ninguno.

Ejemplo:
/* final Intent intent = getActivity().getIntent(); */
if (intent.getExtras() == null) {
    /* Hacer lo necesario en caso de no recibir NINGÚN extra */
} else {
    /* Hacer lo necesario en caso de no recibir algún extra */
}

Proyecto de ejemplo de uso
Proyecto de ejemplo EjemploIntent que he creado en github:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_intent);
    tvName = (TextView)findViewById(R.id.text_name);
    String strDate = getIntent().getStringExtra(EXTRA_NAME_STRING);
    if (strDate == null) {
        tvName.setText(getText(R.string.cancelled));
    } else {
        tvName.setText(strDate);
    }
}

A: Claro, en el codigo del Activity que se abra , puedes meter el:
if(getIntent().hasExtra("FECHA"){
//Hacer algo si tiene extras
}


text:
Q: Check if a file exists in the android resources - Android I am trying to get a video from "android.resource://" + getPackageName() + "/raw/video", and it reads it perfectly. How can I check if that file exists or is missing?

A: You can check like this .
int checkExistence = mContext.getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION", "raw", mContext.getPackageName());

if ( checkExistence != 0 ) {  // the resouce exists...
result = true;
}
else {  // checkExistence == 0  // the resouce does NOT exist!!
result = false;
}


text:
Q: Querying access to a UNC path on a remote machine via WMI I want to find out if the remote host has r/w access to a network share. To start out I wanted to see if I could query the target host's ability to query the UNC path for info, ala
var query = string.Format("select * from CIM_Directory where name = '{0}'", path);

This works fine for local files, e.g.
var path = @"c:\\Windows";

However, I can't figure out an appropriate way of querying a UNC path (e.g. \\foo\bar). The query always returns a blank set. I saw a related question about executing remote files and the solution for that one ended up being PsExec. I was hoping to ideally solve this problem entirely using WMI without having to rely on 3rd party execs, or uploading my own tool to the remote host.
Cheers
Here's a little usage sample of what I am trying to do right now (var values taken out):
using System;
using System.Linq;
using System.Management;

namespace netie
{
    class Program
    {
        static void Main()
        {
            var connection = new ConnectionOptions
            {
                Username = "user",
                Password = "pass",
                Authority = "domain",
                Impersonation = ImpersonationLevel.Impersonate,
                EnablePrivileges = true
            };

            var scope = new ManagementScope("\\\\remote\\root\\CIMV2", connection);
            scope.Connect();

            var path = @"\\\\foo\\bar\\";
            var queryString = string.Format("select * from CIM_Directory where name = '{0}'", path);
            try
            {
                var query = new ObjectQuery(queryString);
                var searcher = new ManagementObjectSearcher(scope, query);

                foreach (var queryObj in searcher.Get().Cast<ManagementObject>())
                {
                    Console.WriteLine("Number of properties: {0}", queryObj.Properties.Count);
                    foreach (var prop in queryObj.Properties)
                    {
                        Console.WriteLine("{0}: {1}", prop.Name, prop.Value);
                    }
                    Console.WriteLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            Console.ReadLine();
        }
    }
}

A: So it looks like this is basically impossible as WMI locks you out of network access for security reasons. Looks like your best bet is WinRM or PsExec for one-offs. You can potentially enable WinRM through WMI if that's your only path of access, but I imagine that ability can be blocked by group policies. The third option is to write your own Windows Service that will respond to requests and installing that through WMI if you have the access.
In short: the answer to my question is a No. Use WinRm, PsExec, or a custom win-service solution.

A: I know this is an old question, but for anyone looking to do this, the following code works. (I know that it's not WMI. Given the OP's answer I didn't even try it with WMI, but I shudder to think that people may write a service for something like this.)
if (System.IO.Directory.Exists(@"[SOME UNC PATH]"))
{
    System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(@"[SOME UNC PATH]");
    var securityInfo = info.GetAccessControl();
    var rules = securityInfo.GetAccessRules(
                   true,
                   true,
                   typeof(System.Security.Principal.SecurityIdentifier));

    foreach (var rule in rules)
    {
        var fileSystemRule = rule as System.Security.AccessControl.FileSystemAccessRule;
        if (ruleastype != null)
        {
            string user = fileSystemRule.IdentityReference.Translate(
                    typeof(System.Security.Principal.NTAccount)).Value;

            System.Diagnostics.Debug.Print("{0} User: {1} Permissions: {2}",
                fileSystemRule.AccessControlType.ToString(),
                user,
                fileSystemRule.FileSystemRights.ToString());
        }
    }
}

When run it produces the following output:
Allow User: Everyone Permissions: ReadAndExecute, Synchronize
Allow User: CREATOR OWNER Permissions: FullControl
Allow User: NT AUTHORITY\SYSTEM Permissions: FullControl
Allow User: BUILTIN\Administrators Permissions: FullControl
Allow User: BUILTIN\Users Permissions: ReadAndExecute, Synchronize


text:
Q: About signed saml request and response attached key I am wondering why the saml signed request and response XML attached key.
I saw the signature comes with a certificate?
Shouldn't the certificate already be negotiated ahead of time between SP and IDP?
I am just wondering if the attacker can sign the invaded message with their own private key and give the SP their public key to verify.
Or the certificate on response will be validated to match the already negotiated one? Then why it is necessary/bother to attach the the certificate on each request/response?

A: Your reasoning is correct: the certificate, or some unique reference to it like a thumbprint, should already have been negotiated out of band.
There are 2 situations in which it is useful to send the certificate anyhow with the requests:

*

*you've negotiated only the thumbprint or subject/issuer instead of the actual certificate

*you are capable of rolling over certificates and both the old and new certificate have been exchanged; then the certificate that is included in the request will prevent the receiver from having to try each key in turn until it finds the current signing key

But I would also argue that a lot of times the certificate is just included because it is the default setting for the SAML software stack used by the sender...


text:
Q: Steam Isnt working tyler@Tyler:~$ steam
Running Steam on ubuntu 16.04 64-bit
STEAM_RUNTIME is enabled automatically
Pins up-to-date!
Installing breakpad exception handler for appid(steam)/version(1528497815)
libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast
Installing breakpad exception handler for appid(steam)/version(1528497815)
Installing breakpad exception handler for appid(steam)/version(1528497815)
Gtk-Message: Failed to load module "gail"
Gtk-Message: Failed to load module "atk-bridge"
Gtk-Message: Failed to load module "unity-gtk-module"
libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast
assert_20180705192828_1.dmp[5672]: Uploading dump (out-of-process)
/tmp/dumps/assert_20180705192828_1.dmp
/home/tyler/.local/share/Steam/steam.sh: line 876:  5656 Segmentation fault      (core dumped) $STEAM_DEBUGGER "$STEAMROOT/$STEAMEXEPATH" "$@"
assert_20180705192828_1.dmp[5672]: Finished uploading minidump (out-of-process): success = yes
assert_20180705192828_1.dmp[5672]: response: CrashID=bp-7655b994-a255-4453-9e26-828ee2180705
assert_20180705192828_1.dmp[5672]: file ''/tmp/dumps/assert_20180705192828_1.dmp'', upload yes: ''CrashID=bp-7655b994-a255-4453-9e26-828ee2180705''

GPU  INFO 940M using 384.130 Nvidia Binary Drivers

A: try these links they might help you solve your problem
You seem to be missing the swarst driver so here's a link to some help with it
https://www.linuxquestions.org/questions/slackware-14/failed-to-load-driver-swrast-4175497461/
And try installing the 32bit version of gail and atk-bridge it worked fine for me
How to install gail and atk-bridge?


text:
Q: Javascript won't split using regex Since I started writing this question, I think I figured out the answers to every question I had, but I thought I'd post anyway, as it might be useful to others and more clarification might be helpful.
I was trying to use a regular expression with lookahead with the javascript function split.  For some reason it was not splitting the string even though it finds a match when I call match.  I originally thought the problem was from using lookahead in my regular expression. Here is a simplified example:
Doesn't work:
"aaaaBaaaa".split("(?=B).");

Works:
"aaaaBaaaa".match("(?=B).");

It appears the problem was that in the split example, the passed string wasn't being interpreted as a regular expression.  Using forward slashes instead of quotes seems to fix the problem.
"aaaaBaaaa".split(/(?=B)./);

I confirmed my theory with the following silly looking example:
"aaaaaaaa(?=B).aaaaaaa".split("(?=B).");

Does anyone else think it's strange that the match function assumes you have a regular expression while the split function does not?

A: String.split accepts either a string or regular expression as its first parameter. The String.match method only accepts a regular expression.
I'd imagine that String.match will try and work with whatever is passed; so if you pass a string it will interpret it as a regular expression. The String.split method doesn't have the luxury of doing this because it can accept regular expressions AND strings; in this case it would be foolish to second-guess.

Edit: (From: "JavaScript: The Definitive Guide")
String.match requires a regular expression to work with. The passed argument needs to be a RegExp object that specifies the pattern to be matched. If this argument is not a RegExp, it is first converted to one by passing it to the RegExp() constructor.

A: If I recall correctly (and I could be very wrong here), the split method was implemented in javascript before the regex engine was in wide use, so it's presumably for backward compatibility.


text:
Q: Vacation time auto calculate using excel I am creating a spreadsheet for Managed Time Off.  Here is the accrue amount based on years in service:
Accrual Periods 40 Hours per Week
0-1.99 years earn 136 hours (5.23 hrs per pay period)
2 – 5 years ear 176 hours (6.77 hrs per pay period)
6 – 10 years ear 208 hours (8 hrs per pay period)
11-15 years earn 248 hours(9.54 hrs per pay period)
16-20 years earn 288 hours (11.08 hrs per pay period)
21 or more years earn 312 hours (12 hrs per pay period)

Our pay periods are every 2 weeks.  Our last pay period was 9/3/16 - 9/16/16
Employees are allowed to carryover 1 year of MTO.  Often times they ask how much MTO they need to use by their Anniversary date so they are not above the carryout limit.  I started a spreadsheet but cannot seem to get it to populate correctly.  Does anyone have any suggestions?
This is manual calculation I use.
D. Ernzen
Hire Date: 10/28/1991
MTO/yr = 312 hrs per year
MTO/pay period = 12.0
Carryover allowed on aniv date = 312
Current MTO (as of 9/17/16)      389.5
MTO used 9/17-present day        (20.0)
MTO accruing (9/17-10/28)       + 34.8
MTO balance on Anniversary      = 404.3
Carryover                      - 312.0
Needs to be used by 10/28       =92.3

I would like to keep data entry to a minimum.  The biggest issue I'm having is pay periods til anniv count.  Any suggestions or help is greatly appreciated!  Thank you :)

A: Assuming cell A2 contains the hire date then:
Years since hire can be calculated using:
=INT((TODAY()-A2)/365.25)

Pay periods to anniversary can be calculated using:
=INT(26 - MOD((TODAY()-A2),365.25)/14) + 1

Accrual rate, max carryover etc. can all easily be found using a VLookup based on the years since hire.


text:
Q: Finitely generated ring of polynomials Can we say that, "by definition", a ring $R[x]$ is finitely generated as an $R$-module for some commutative ring $R$ iff $x^n=q(x)$ for some polynomial $q(x)$ of degree $n-1$ for some $n$?

A: It's not quite true; $q(x)$ could have degree lower than $n-1$, eg. $\mathbb{Q}[x]/(x^2 - 2)$. I don't think it's quite "by definition"; you should probably prove it eg. if this is homework.


text:
Q: Reference checklist for starting a new Rails application? It's easy to create a new Rails application using "rails new myapp" (or start with a template from Rails Wizard or the RailsApps project).
But after that, what do you do? What gems do you always add? What decisions do you make before beginning development? What important items are often overlooked before deploying an app?
I'd like to put together a reference checklist to share. Any suggestions?
For example:

*

*Create a new RVM gemset

*Modify the .gitignore file

*Switch from TestUnit to RSpec

*Set up Guard to run tests in the background during development

*Add the viewport metatag to the default application layout

*Don't forget to create a sitemap.xml file

*Add a Google Analytics snippet

What else?

A: Starting with a Rails template.
You should look theses resources :

*

*http://railswizard.org/

*https://github.com/RailsApps/rails3-application-templates

*http://railsapps.github.com/rails-application-templates.html

*https://github.com/quickleft/prologue

A: For me usual process involves:

*

*Add CSS framework (grids, text, forms)

*Add Cells

*Add Slim (www.slim-lang.com)

*Remove Test::Unit for RSpec

*Add application config settings (config.yml)

*Add Cucumber

*Add FactoryGirl

*Add Spork

*Add Guard (guard-rspec, guard-cucumber, guard-sass, guard-livereload, guard-spork)

*Add Git, Github space, + amend .gitignore

*Add Heroku (stage + production) spaces

I'll usually copy over my google_analytics helpers and sitemap_controller from other projects during the development process instead of being organised enough to do it from the start. I like to the the testing and deployment options setup from the get go so I can start developing and releasing early and often.
Dave

A: create rvm gemset, create .rvmrc, modify .gitignore
Then add gems

*

*gem 'pg'

*gem 'thin'

*gem 'ruby-debug19', :require => 'ruby-debug'

*gem 'rspec-rails'

*gem 'factory_girl_rails'

*gem 'capybara'

then depending on the project, I often use aws3, paperclip, resque, will_paginate and haml (although I try not to use it on new projects anymore)

A: Most of the time:

*

*Configuration

*

*add .rvmrc

*amberbit-config gem (avaible at GH)

*modify .gitignore

*Views

*

*haml to sass/coffee stack

*rdiscount

*Tests

*

*rspec instead of unit tests

*capybara, factory_gril, spork, timecop

*Development

*

*guard-livereload, with guard, libnotify etc.

*active_reload for faster development with assets pipeline

*annotate if relational db

*pry

I almost forgot to mention: mix of html5 boilerplate for rails with twitter bootstrap it's good combo.

A: The first think that I do is head to http://railswizard.org/ and create a template, before "rails new app".

A: *

*I always want to set up Factory Girl under /fixtures, and setup
Cucumber along Rspec. Sometimes I use shoulda too.

*Initialize the project as a git repository and link it to
github. Set up the app to use PostgreSQL instead of SQLite.

*And last I can think of is that I often make an entry, from the
beginning, to load .rb files form /lib automatically.

A: I don't add anything. Things get added if project requires them.

*

*I don't load up CSS framework just because there's a need for two columns and a rounded button somewhere.

*I don't load FactoryGirl because rails test fixtures actually do a fine job as long as you know how to use them. (Hint: you don't need 100 instances of User in your fixtures)

*I don't load RSpec/Cucumber/etc because UnitTest is just as good and I prefer keeping things simple.

There's absolutely no reason to bloat project with things just because you "might need it"

A: I got tired of having to remember and repeat the mundane tasks required for every new app.
If you're looking for guidance on getting started, we've recently (yesterday!) released a tool to speed up the process, with all sorts of tried and tested libraries for the various aspects of a Rails web app, as well as cleanup scripts to get the fresh app just the way it should be.
Check out http://drone.bz to build an app the same way we do. Under the hood, it uses the app_drone gem to resolve dependencies and build the actual template, but the UI is probably all you need to get started.
There are several similar tools out there, but I decided to be highly opinionated in my recipe choices, and the end result is a solid foundation on which to start developing :)
P.S. Even if you don't use the drones, you can take a look at the steps that are common enough in Rails dev to be automated.