text:
Q: Does python have its own cookies when download the files When I use python download web files. It get

--------------------------- The server replies that you don't have permissions to download this file.
Details: HTTP/1.1 403 FORBIDDEN

But when I use chrome website to click the links, it can be download without problem. Why?
If it is, can I clean it. My code is:
#!/usr/bin/python
#-*-coding:utf-8-*-
import urllib2
import os
from subprocess import check_output
def data(url):

    up=urllib2.urlopen(url)

    cont=up.read()

    key1="http://videolectures.net/site/secure_dl/"
    key2=".mp4"

    pa=cont.find(key1)
    pt=cont.find(key2,pa)

    urlx=cont[pa:pt+4]

    return urlx

if __name__ == "__main__":
    url_main=["http://videolectures.net/mit600f08_grimson_lec01/",
        "http://videolectures.net/mit600f08_grimson_lec02/",
        "http://videolectures.net/mit600f08_grimson_lec03/",
        "http://videolectures.net/mit600f08_grimson_lec04/",
        "http://videolectures.net/mit600f08_grimson_lec07/",
        "http://videolectures.net/mit600f08_grimson_lec08/",
        "http://videolectures.net/mit600f08_grimson_lec09/",
        "http://videolectures.net/mit600f08_grimson_lec10/",
        "http://videolectures.net/mit600f08_grimson_lec15/",
        "http://videolectures.net/mit600f08_grimson_lec16/",
        "http://videolectures.net/mit600f08_guttag_lec05/",
        "http://videolectures.net/mit600f08_guttag_lec06/",
        "http://videolectures.net/mit600f08_guttag_lec11/",
        "http://videolectures.net/mit600f08_guttag_lec12/",
        "http://videolectures.net/mit600f08_guttag_lec13/",
        "http://videolectures.net/mit600f08_guttag_lec14/",
        "http://videolectures.net/mit600f08_guttag_lec17/",
        "http://videolectures.net/mit600f08_guttag_lec18/",
        "http://videolectures.net/mit600f08_guttag_lec19/",
        "http://videolectures.net/mit600f08_guttag_lec20/",
        "http://videolectures.net/mit600f08_guttag_lec21/",
        "http://videolectures.net/mit600f08_guttag_lec22/",
        "http://videolectures.net/mit600f08_guttag_lec23/",
        "http://videolectures.net/mit600f08_guttag_lec24/"]
    file = open('file.txt', 'w')
    file.close()
    for url in url_main:

        print url
        url_video=data(url)
        file = open('file.txt', 'a')
        file.write(url_video+'\n')
        file.close()
        check_output("cmd.exe /k "+"\"C:\Program Files (x86)\Internet Download Manager\IDMan.exe\"  /d "+url_video, shell=True)

A: You are right, python has its own cookie and you have to use the library, see the link below:
https://docs.python.org/2/library/cookie.html


text:
Q: How to change default category id when adding a new product $categories = $this->getCategories($sub_cats);
$product->addToCategories($categories);

foreach ($categories as $category) {
    $product->category[] = $category;
}

This code works good when i want to add product categories but i cannot change id_category_default
How can i change the default category info ?

A: Did you call the save() method when you tried to save the default category?
$product->id_category_default = (int)$id_category;
$product->addToCategories($categories);
$product->save();

redpajama_set_name: RedPajamaStackExchange


text:
Q: ntoskrnl.exe !SeAccessCheckWith Hint+0x1c620 drive still in use error After not safely removing a flash drive a few years ago, I lost all of my data on a drive. Luckily I was able to find a data recovery program to restore the data, but it was a time consuming process. Since then I have always practiced safely removing drives, but occasionally get the error that the drive is still in use by a program. The problem has been happening much more frequently on my Win 10 PC the last few months.
The message that the drive is still in use comes up despite not having any applications open, so I started reading up on how to find out what background process is causing the problem. I read a little about the Systeminternals suite and downloaded it, found the logs for the error messages, and the process, which turned out to be the system. I then looked at the thread, and found what I think is the process associated with the problem.
As it turns out, it's the same thing every time I have the problem, regardless of which flash drive the problem occurs with:
"ntoskrnl.exe!SeAccessCheckWithHint+0x1c620"
I know ntoskrnl.exe is the kernel, but I'm trying to find out what the "!SeAccessCheckWithHint+0x1c620" means?
How can I go about finding more information as to what it is doing with my drives to prevent them from being safely ejected? (if the answer is a memory dump, which type, and how would I research the results of it)
How can fix the problem, aside from updates (I've done all of my Windows updates, and driver updates), and aside from restarting the computer each time this happens?
If the problem potentially related to the drive being indexed by the system, will I have to turn indexing off each time I plug the drive in or is there a way to make the system stop indexing all removable drives?
Thank you,

A: Task Scheduler:
\Microsoft\Windows\MemoryDiagnostic\RunFullMemoryDiagnostic
and
\Microsoft\Windows\Defrag
run from background tasks
Security and Maintenance - Automatic Maintenance
causes ntoskrnl.exe!SeAccessCheckWithHint+0x1c620
Try to disable defrag on this flash drive.
In my laptop i turned off the RunFullMemoryDiagnostic task because they were using 20% cpu when idle.

A: From late 2020 I had also been having the "ntoskrnl.exe !SeAccessCheckWith Hint+0x1c620" issue with multiple threads causing the System process to consume 5%-20% of the CPUs all day every day.
After the recent upgrade to Windows 10 21H2 the problem went away. But it came back as "ntoskrnl.exe !SeAccessCheckWith Hint+0x1c790" about 30 minutes later. Same bazillion threads constantly spawning and gobbling up CPU. Grrrrr!
I went back and tried all other suggestions I had tried before: disabling Windows Search service, disabling the Automatic Maintenance Tasks mentioned above, Dism /Online /Cleanup-Image /RestoreHealth etc. etc. Nothing changed.
Several days back I stumbled on a fix that works for me. The System process now hovers between 0%-3% CPU like it used to. All I did was put a CD into the DVD drive. Bizarre.
There was no methodical troubleshooting involved here, I was just tidying my desk and found an unlabelled CD and wondered what was on it. After inserting the CD I saw my Rainmeter CPU graph quickly drop to 1%.
I have had the LG DVD-RAM SATA multi-drive for a long time (since Vista days) and it works just fine although it isn't used very often these days. I have never set the DVD Region because I don't use the drive to play DVDs. My guess is that something changed in how autorun works in Windows 10 20H2, or, the drive has developed a problem sensing when no media is present.
I have been able to reproduce the error by ejecting the CD, opening File Explorer, a few minutes later the System process goes nuts. Put a CD in the drive and a few minutes later the System process idles as normal.
A data CD or audio CD works.

A: In my case, it turned out to be... corrupt system restore. Turned off and deleted all restore points before turning back on.
I discovered this by watching task manager launch windows system protection just before the SYSTEM CPU usage jump.
ntoskrnl.exe seaccesscheckwithhint+0x1c790
High System after 10 minutes
Next step would have been to delete the systemvolumeinformation folder from winpe.


text:
Q: osmdroid - offline map, not showing map after scrolling zoomed map I have some problems with showing map in the offline map. I'm using osmdroid + tile downloaded via MOBAC and putted on the phone.
I download the tiles from particular area, I can see unzoomed map, everything seems ok for me. Then I zoom the map and looks ok but if I scroll then I see unloaded fragments of map.
This screen should show what I meant.
Unzoomed:

Zoomed:

Zoomed after scroll:

and here is my code:
public class OSMDroidMapActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    MapView mapView = new MapView(this,256);

    //mapView.setClickable(true);

    mapView.setBuiltInZoomControls(true);

    setContentView(mapView);

    // set initial zoom-level
    mapView.getController().setZoom(15);
    mapView.setMultiTouchControls(true);
    mapView.setClickable(true);

    mapView.getController().setCenter(new GeoPoint(54.178181,15.579021));
    //keeps the mapView from loading online tiles using network connection.
    mapView.setUseDataConnection(false);
    mapView.setTileSource(TileSourceFactory.MAPQUESTOSM);

}

}
Is there any option to force view to render one more time or smth like that. This is not problem of not having the tiles in the memory of phone, cause when I unzoom map and then zoom this fragment which u can see at "Zoomed after scroll:" screen, the map is showed properly. In my opinion this is caused by rendering small fragment of map when I zoom it.
I searched for answer, most of question are about situation when map isn't showed at all(problem with tiles). I found this question, but changing version of jar file caused only more problem with map.
Edit:
Additional info:
for osmdroid I'm using this lib jar file: osmdroid-android-4.2.jar and here is the screen from MOBAC

and then I click create atlas button.
Path to tiles:
SD Card\osmdroid\tiles\MapQuest
tiles is the rar file which is atlas created as output from mobac

A: Since osmdroid 4.2, the default format of MapQuestOSM tile source is "jpg". So your conversion to png is not necessary.
EDIT - And this could be a part of your issue.
Refer to this post: Download maps for osmdroid
Do you have sub-dirs in SD Card\osmdroid\tiles\MapQuest, or is this directory COMPLETELY empty? If it's not empty, the tiles displayed could come from this cache, not from your zip file. This could explain the behaviour (zip file not used at all, cached tiles used when available). To be 100% sure: if it's not empty, delete it.
And could you also specify exactly the full path location of your MOBAC zip file on your device?

A: Zips and archives should be in /sdcard/osmdroid/ (not in the tiles directory). That's part of the problem.
The 'zoomed in' picture is osmdroid scaling the previous zoom level to fill the screen. This only happens while you're zooming in and is then replaced with the actual tile for that zoom level. The last part isn't happening since it's not loading your tiles.


text:
Q: C++ declare a string array with content and size based on user input I am trying to set up an array of string that's size and content dependent on the users input.  I am getting an error declaring my array, it says the variable for the size is not the right type.  I've spent a few hours on this just thought I'd ask.
Here's my code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << "Enter number of names /n";
    int a;
    cin >> a;
    string namesArray[a];         //Error is here.
    for( int i=0; i<a; i++) {
        string temp;
        cin >> temp;
        namesArray[i] = temp;
    }

    for( int j=0; j<a; j++) {
        cout << "hello " << namesArray[j] << "/n";

    }
    return 0;
}

The error is at string namesArray[a];

A: An array needs to have a compile-time value for its size. Your code wont compile because a is not a compile-time constant.
Better use std::vector:
#include <iostream>
#include <string>
#include <vector>   // <-- Must be included

using namespace std;

int main()
{

    cout << "Enter number of names /n";
    int a;
    cin >> a;

    vector<string> namesArray;    // HERE!!!

    for( int i=0; i < a; i++) {
        string temp;
        cin >> temp;
        namesArray.push_back(temp);   // Notice the difference
    }

    for( int j=0; j<a; j++) {
        cout << "hello " << namesArray[j] << "/n";
    }

    return 0;
}

A: You can declare your namesArray in this way:
string * namesArray = new string[a];

This should work, since it dynamically allocates memory based on input value a.
But certainly, it is better to use vector instead. You don't need to delete the array if use vector.

A: You cannot use a variable as the size of statically intiailised array, to do this you need to dynamically allocate your array, with something like
string* namesArray =  new string[a];

But it is much wiser to use std::vector instead and save yourself from memory leaks!
With a vector you can do it like this:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    cout << "Enter number of names /n";
    int a;
    cin >> a;
    vector<string> names;
    for( int i=0; i<a; i++) {
        string temp;
        cin >> temp;
        names.push_back(temp);
    }

    vector<string>::iterator
        it = names.begin(),
        ite = names.end();
    for(; it != ite; ++it) {
        cout << "hello " << *it << "/n";
    }

    return 0;
}

A: As Mark said, it's a compile-time issue. You can use vector, but another way to do this would be to dynamically allocate memory for the array. This would mean using the keyword new.
So, your code would be string* namesArray = new string[a];
Using new returns a pointer to the array, so adjust accordingly.


text:
Q: Magento transactional email new order email template product image missing In my store am using transactional email new order template for get notification.
All Are working good. But in order email product image is missing how can i solve this error.
This is error:

transactional email new order code:

YOUR ORDER CONFIRMATION

                        Thank you for shopping with us, {{htmlescape var=$order.getBillingAddress().getName()}}!

                        We wanted to let you know that:

                         • Your order (Order no: {{var order.increment_id}}) was received, and is in process.

                         {{block type="core/template" template="email/order/example.phtml" order=$order}}
                         • We'll follow up with another e-mail once your package is on its way.

In the meantime, all the details are below, and you can check your

order status online anytime.

You can check the status of your order by logging into your account.

The MW Team is Here to Help

If you have any questions regarding your order or would like to make changes, please feel free to email us on contactus@abc.in or call us on +91 9008423121 Monday-Saturday 10 AM - 6 PM IST

                            Billing Information:

                            Payment Method:

                                {{var order.getBillingAddress().format('html')}}

                                {{var payment_html}}

                    {{depend order.getIsNotVirtual()}}

                            Shipping Information:

                            Shipping Method:

                                {{var order.getShippingAddress().format('html')}}

                                {{var order.getShippingDescription()}}

                    {{/depend}}
                    {{layout handle="sales_email_order_items" order=$order}}

{{var order.getEmailCustomerNote()}}

If you are not the intended recipient or have received this email in error, please delete immediately.
Any dissemination, distribution, or copying of this message by any person other than the intended recipient is strictly prohibited.


text:
Q: scrollable views in drupal 6 is needed I want to create a views with scrollable content. I've searched using google and found this : http://drupal.org/project/scrollable  but it is abandoned.
Is there anything similar to it ? I use Drupal 6.

A: there are other modules available like ,
http://drupal.org/project/scrollable_content
http://drupal.org/project/views_infinite_scroll
http://drupal.org/project/infinitescroll


text:
Q: Find and replace all occurrence of a function definition I want to delete all occurrences of a function definition.
I have a lot of member functions with the same prototype overloaded in multiple derived classes
For example,
void **********::func()
{
.
..
...
}

The above function definition are different in number of lines in each occurrence.
Is there a way to do this in visual studio? If not in notepad++ or some other editor?


text:
Q: my sonarqube always said no code coverage for java hi all i have build unit testing for controller, repository and Service but why in my sonarqube code coverage always give me code coverage only 0 percent. my question is how to make my percentage up ?

here what i was code in my testing

A: Sonarqube uses existing code coverage reports from JaCoCo (in the case of Java). Usually, you would set up the JaCoCo Maven plugin (or Gradle) to gather coverage info on test run and Sonarqube then loads this report.
See also the Sonarqube docs for info on setup. But if you are using Maven/Gradle, I believe Sonarqube is able to automatically pick up the correct file unless you have some special configuration.


text:
Q: Out of memory trying to install ext-gd on Heroku I have to install ext-gd on my app in Heroku but when I do composer update it fails because of not enough memory. I am using free tier.

PHP Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 18947584 bytes)

It seems that I can't change memory size, also I don't understand if it's possible to consume all memory just with a composer update.
Error in Heroku


text:
Q: VSCode multiple versions of custom snippets I am creating custom javascript snippets in VS Code. I have a snippet that creates a React component class, but using the same prefix, I want to have a slightly different version of the react component class. This is my code:
   "Creates a React component class": {
        "prefix": "rcc",
        "body": [
          "import React from 'react'",
          "",
          "class ${1:className} extends React.Component {",
          "    render() {",
          "        return (",
          "            <div>",
          "",
          "            </div>",
          "        )",
          "    }",
          "}",
          "",
          "export default ${1:className}"
        ],
        "description": "Creates a React component class"
    },

I want to type rcc and have it give me two options, one is default, and the other pastes this code:
   "Creates a React component class": {
        "prefix": "rcc",
        "body": [
          "import React from 'react'",
          "",
          "class ${1:className} extends React.Component {",
          "    render() {",
          "        const runCallback = (cb) => {",
          "            return cb()",
          "         }",
          "        return (",
          "            <div>",
          "",
          "            </div>",
          "        )",
          "    }",
          "}",
          "",
          "export default ${1:className}"
        ],
        "description": "Creates a React component class"
    },

A: I have come to realize you cannot do this at this scale. The choices feature in VS Code custom snippets, only allows you to chose between a couple one-line words in your code.
It looks like this:
${1|choice1, choice2|}

A: You can do this without choices:
  "Creates a React component class": {
  "prefix": "rcc",
  "body": [
    "import React from 'react'",
    "",
    "class ${1:className} extends React.Component {",
    "    render() {",
    "        ${2:const runCallback = (cb) => {\n\t\t\t\t\treturn cb()\n\t\t\t\t\t\\}}",

    "        return (",
    "            <div>",
    "",
    "            </div>",
    "        )",
    "    }",
    "}",
    "",
    "export default ${1:className}"
  ],
  "description": "Creates a React component class"
}

choices do not appear to allow returns in them, but a default option does.
If you don't want the default option, just Ctr+X twice when it is selected.
If you want it tab.


text:
Q: Load data from a MySQL database to an Objective C/XCode Project I have a simple question to XCode/iOS developers out there. I just want to know what are the most basic ways of fetching/inserting data into a MySQL database from an Objective C/XCode program. Basically, what I am planning to do is to create a mobile application version of the website I am currently developing. In short, the XCode program I'm planning to do is a way smaller version of a PHP web application. The XCode program will be able to modify, insert, and fetch data from the database of the website.
Can you guys give me a hint? A tutorial (or links)? I'm not even a new XCode developer, I'm only about to begin being one for the capstone project I am developing with my group (I'm in college, if this info is even necessary LOL).

A: You should do :

*

*Implement a sever API (Web Services) with your preferred language ( PHP,...) that can communicates with the Data base.

*An objective C client ( iOS application) that communicates with the data base but using your API ( Web Services).
here are excellent tutorials that will show you how to do all the steps. Tutorial

A: I would use REST webservice:
Write a piece of code with XCode which do HTTP GET and HTTP Post to your server. Query data with GET and Insert Update delete with POST.
After this write your  server side code in PHP , Java, whatever you know / like to receive those 4 operations, connect to database and send a result you.
This architecture is used in many mobile applications.
Has some Pro and so Cons, like everthing.
The Pro:
separated code connection to database, separated units => improved security. Probably you don't want everybody see your mysql root password... who can decompile the iPhone app.
With separated client-server: it allowed multiple connections, caching.
The list is very long here.
The cons:
Probably need to know 1 more developing language than Objective -C
Need web hosting, not only database hosting
The list is a lot shorter here and less important.


text:
Q: Front end dependency manager for appending
A: As @morganney pointed out, Require.js is designed pretty much exactly for this purpose. Many popular libraries export their libraries in UMD format, which supports the AMD (Async Module Definition) logic Require.js expects.

A: This will simply import asynchronously all the first level libraries in your object, using just JavaScript import.
From the network debugger tab, we can observe the HTTP code 200 success:

const ScriptLoader = async (libs) => {
  for (const [k] of Object.entries(libs)) {
    console.log(k, libs[k].attr.src);
    await import(libs[k].attr.src)
    // Lib ready here
  }
}

const scriptLoader = ScriptLoader({
    "jquery@3.4.1": {
        "attr": {
        "src": "https://code.jquery.com/jquery-3.4.1.min.js",
        "integrity": "sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=",
        "crossOrigin": "anonymous",
        },
    },
    "bootstrap@4.0.0": {
        "attr": {
        "src": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js",
        "integrity": "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl",
        "crossOrigin": "anonymous",
        },
        "dependencies": ["jquery@3.4.1", "popper@1.12.9"],
    },
});


text:
Q: Window Azure Deploying Cloud Services with A6 vmsize In my cloud service I have one web role and worker role. I changed my web role VM size from medium to A6.
When I tried to deploy to Windows Azure, I get the following error message:s seem prompt me error

The VM size (or combination of VM sizes) required by this deployment cannot be provisioned due to deployment request constraints. If possible, try relaxing constraints such as virtual network bindings, deploying to a hosted service with no other deployment in it and  to a different affinity group or with no affinity group, or try deploying to a different region.

What does that mean?

A: Basically, you've asked it for one of the new "Uber" A6 Instances (with additional memory/process resources) and it was unable to provision your request (i.e. provide you with the required amount of cloud computing power for an A6 Instance).
You could try deploying to a different geographic location or affinity group or just wait and try again.


text:
Q: Is it possible to open a Text File in Pascal several times in the same program? I am trying to make a program that allow me to read a text file and then print it in the terminal.
I just put the simplified parts below so that you see how I think it should work.
My problem is that if for example I open the file a.txt then b.txt it works.
But when I want to open a.txt again, the program stops with an error 217. Same if I want to open another file name c.txt for example. I've spent days on this problem but I do not know where it comes from. I looked on the internet and erorr 217 seems to be related to a non-existing file ? but it is not the case for me...
The error seems to occur on the 'assign' function.
To clarify :
'key' is a Char,
'map' is a two dimension dynamic array of a Record Type.
Repeat
     readln(key);
     name := key +'.txt';
     fileLoading(name, map, maxX, maxY);
Until key = 'l';

...
procedure fileLoading (name : String; var map : PPObjet; var maxX,maxY : Integer);
var
    fichier : Text;
    i, j : Integer;
    chaine : String;

begin

    if (FileExists(name)) then
    begin
        assign(fichier, name);
        reset(fichier);
        read(fichier,maxX);
        readln(fichier,maxY);
        if (maxX < 1) or (maxX > MAX) or (maxY < 1) or (maxY > MAX) then
        begin
            writeln('Tailles invalides');
            halt();
        end;

        allocationTab(maxX, maxY, map);
        while (not eof(fichier)) do
        begin
            for j := 1 to maxY do
            begin
                readln(fichier,chaine);
                for i := 1 to maxX do
                begin
                    case chaine[i] of
                    '0'     :   begin
                                    map[j][i].solide := false;
                                    map[j][i].nature := 'v';
                                    map[j][i].valeur := chaine[i];
                                end;
                    '1'     :   begin
                                    map[j][i].solide := true;
                                    map[j][i].nature := 'm';
                                    map[j][i].valeur := chaine[i];
                                end;
                    '2'..'9' :  begin
                                    map[j][i].solide := false;
                                    map[j][i].nature := 's';
                                    map[j][i].valeur := chaine[i];
                                end;

                    end;
                end;
            end;
        end;
    end
    else
    begin
        writeln('Erreur le fichier n''existe pas');
        halt();
    end;
    close(fichier);
end;

...
This is the first time I ask a question on stack overflow and I'm not really familiar with it, so I hope my problem is clear enough, as well as my english.
Thanks in advance for all the help you may bring.

A: try setting
 filemode:=0;

before your assign/reset


text:
Q: How to create a single Feature by selecting from a FeatureCollection? I have a FeatureCollection of the Burmese state and region boundaries. As my study site only includes one state (the Ayeyarwady Region), I would like to mask my other data (mangrove cover, in this case) by this state.
I tried the following:
// Load state and region boundaries of Myanmar
var MMR_RegionBoundaries = ee.FeatureCollection('users/simonsesytze/aeo_research/MMR_region_boundaries')

// Select Ayeyarwady Region
var AyeyarwadyBoundary = ee.Feature(MMR_RegionBoundaries.select('Ayeyarwady'))

// Load Global Mangrove Watch coverage
var GMW_2016 = ee.FeatureCollection('users/simonsesytze/aeo_research/GMW_2016')

// Filter mangroves to Ayeyarwady Region
var GMW_Ayeyarwady = GMW_2016.filterBounds(AyeyarwadyBoundary)

// Display layer
Map.addLayer(GMW_Ayeyarwady, {}, 'Mangroves in Ayeyarwady Region');

However, this results in an error:
Mangroves in Ayeyarwady Region: Layer error: Feature, argument 'geometry': Invalid type.
Expected type: Geometry.
Actual type: FeatureCollection.

How can I extract a geometry from the FeatureCollection and use it to mask a layer to?

A: Try
var GMW_Ayeyarwady = GMW_2016.filterBounds(AyeyarwadyBoundary.geometry());


text:
Q: Schematic title block question Does the second schematic sheet title block need all the same information as the first sheet. To me it seems kind of redundant to keep the signoffs and proprietary statement...

A: Absolutely. All information should be on all sheets. Consider that the schematic could be printed, and the sheets separated. A copyright notice on page one is not much use when someone copies page two.
Put it another way, why not have all info on all sheets?
If it's space - you're already doing it wrong.


text:
Q: How to use RegEx to find strings deep inside an array of objects I'm currently trying to find a way to match user input to find a user in Discord, for commands that we didn't necessarily want tagging the user. As it is, the method I'm using to get that username is
var member = message.guild.members.find('nickname', `${searched}`);

However this only pulls the name if it's an exact match, which is kind of annoying.
How would I go about pulling a name with only a partial bit of it?
For further clarification, the variable 'searched' is what I'm looking to replace in order to match the string provided by user input to the nickname attribute in Discord's members objects.
EDIT
Found what I was looking for
var member = message.guild.members.find(element => element.nickname.includes(searched) == true);

A: This should work if members is an array. It should match nickname anywhere in the string.
const nickRegx = new RegExp('nickname')
var member = message.guild.members.find((member => nickRegx.test(member));

A: Found the answer to my own question after an hour or so
var member = message.guild.members.find(element => element.nickname.includes(searched) == true);


text:
Q: How to install Xorg 1.18.4 on Ubuntu 18.04 LTS? After migrating from Ubuntu 16.04 LTS to Ubuntu 18.04 LTS I faced this old and annoying Xorg bug. It's impossible to use Ctrl+Shift hotkeys in Unity if Ctrl+Shift is configured to change keyboard layout. This issue is also mentioned here.
A bugfix ported from ArchLinux is proposed:
sudo add-apt-repository ppa:nrbrtx/xorg-hotkeys
sudo apt update
sudo apt dist-upgrade

but it doesn't work for Unity.
Ubuntu 18.04 is shipped with Xorg 1.19.6 while Ubuntu 16.04 - with Xorg 1.18.4 (and hotkeys were working with it in Unity). My hope was to find 1.18.4 version for bionic in xorg-edgers but seems it's only available for xenial.
My question: how can I downgrade Xorg to 1.18.4 on Ubuntu 18.4? Should I start to dig into sources to build it manually or is there an easiest way?

A: I'm sorry but even as being an author of this PPA I do not have a solution.
Downgrading Xorg and patching it may end with difficult long deep dependency resolution.
I tried to install Xenial HWE packages from my PPA on Bionic with no luck.
So there is something wrong inside Unity or GNOME sHell.
You can read my complete opinion on Ubuntu Community (first and second). I cite latter here:

The universal remediation to fix current bug - do not use both GNOME sHell and beloved Unity
and purge them with commands below:
sudo apt-get purge gnome-shell ubuntu-gnome-desktop \
ubuntu-desktop ubuntu-unity-desktop unity-session

sudo apt-get autoremove

but use Cinnamon, KDE, MATE (my favorite) or Xfce instead with packages from my PPA:
#Choose your favorite desktop
#sudo apt-get install cinnamon-desktop
#sudo apt-get install kubuntu-desktop
sudo apt-get install ubuntu-mate-desktop^
#sudo apt-get instal xubuntu-desktop

#Add my PPA
sudo add-apt-repository ppa:nrbrtx/xorg-hotkeys
sudo apt-get update
sudo apt-get dist-upgrade

#Reboot and enjoy
sudo reboot

Optionally pin (lock/hold) related packages to prevent their upgrade with:
cat <<EOF | sudo tee /etc/apt/preferences.d/pin-xorg-hotkeys
Package: *
Pin: release o=LP-PPA-nrbrtx-xorg-hotkeys
Pin-Priority: 1337
EOF

If you are not satisfied with obtained results - write a letter to Mark Shuttleworth / Xorg / GNOME / all bug-trackers / all IRCs / all LoCos / all treads of Ubuntu-Forums / Bill Gates about your problem and then execute:
sudo apt-get install ppa-purge
sudo ppa-purge ppa:nrbrtx/xorg-hotkeys
sudo rm /etc/apt/preferences.d/pin-xorg-hotkeys

If you would like to complete with installation of MATE DE you can use Mutiny panel layout to avoid some headache :)

The last option - you can try to write PM to the user, suggested to downgrade Xorg to give you complete working instruction.


text:
Q: Detect window or form defocus How can i detect a window change (or form defocus)?
I have 1 picturebox, & 1 label (not visible)  above the picturebox with text "UNAUTHORIZED COPY"
the question is: how to make it visible if the window, or form gets defocused or when the user open another program. But Focus is property for "controls" but not for forms, then there is not easy way.
Additionally my program already clear the clipboard when detect the printscreen key to avoid the most common snapshot from any windows user, i just want to add now this watermark text for use of third party screen capture software.

A: To see if the form lost focus, use Deactivate in the events
Double click on your form, and go to the right side where it says: "Load". Click on the "Load" text and search for a event called: "Deactivate", click on that and the following code has entered in your code:
Private Sub Form1_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate

End Sub

I hope it helped!
EDIT: Thanks to LarsTech for pointing out that LostFocus is only used when updating UICues or when writing custom controls. (Control.LostFocus Event)


text:
Q: how do you record webcam video using asp.net mvc 3 and adobe flash media server? I want to record a video from webcam in asp.net mvc 3 application and stream it to Adobe Flash Media Server to save the file for later viewing. I have googled for about 2 hours and have had no luck. I must be blind for not finding an answer. Can anyone point me in the right direction? Any links to a decent tutorial or tips?
Thanks!

A: You're going to need to write an Actionscript application or a Flex application that attaches the webcam to a NetStream, and then publishes that stream to Flash Media Server (FMS). Then compile this app into SWF and embed the SWF in your asp app's HTML.
The Actionscript code for doing this with or without the Flex framework is basically the same. The concepts are:

*

*Get access to the webcam, Flash player automatically displays a security dialog asking the user for permission

*To display the camera output to the user, attach it to a Video object and add the Video to the stage. In a Flex application, the Video object needs to be wrapped in a Flex container (this is only difference).

*Create a NetConnection and connect it to the FMS. You attach event listeners to the NetConnection to know when it's connected (so you can proceed), or if it fails.

*After connecting, create a NetStream, attach the webcam to it, and publish to FMS.
Here's an example that someone else was nice enough to write.


text:
Q: Permanently allow apps downloaded from "anywhere"
I want to trust unidentified developers' applications. I've gone to System Preferences > Security & Privacy and tried to enable "Allow apps downloaded from: Anywhere", but OS X claims it will reset my "Anywhere" selection after 30 days of inactivity. Actually, I don't want OS X to make it unusually difficult for me to use my software, ever. Is it possible to make this selection permanent?

A: It took me some time to figure this out but you can disable it through a global preference using the terminal:
sudo defaults write /Library/Preferences/com.apple.security GKAutoRearm -bool NO

This will disable the auto rearming of the Gatekeeper in OS X. Tested on both Yosemite and Mavericks

A: Not enough to get the password, you need to change a new one (password) to allow apps downloaded from a particular source can run.


text:
Q: Como aplicar opacidade em um elemento DOM - createImage(); - através de um editor em javascript? Estou usando o p5.js - uma biblioteca javascript - para capturar imagens de uma API de notícias. Gostaria que essas imagens fossem sobrepostas, mas com opacidade, de forma que as imagens se mesclem.
Não estou conseguindo aplicar a opacidade direto pelo código javascript. Consigo alterar a posição das imagens ( fotos.position(x ,y); ), mas não encontro o caminho para aplicar a opacidade.
function setup() {
createCanvas(900,600);
loadJSON("https://newsapi.org....ec6490",gotData);
}

function gotData(data) {
console.log(data);

var img = data.articles;
var imgs = [];

for (var i = 0; i < img.length; i++) {
imgs.push(img[i].urlToImage);

var fotos = createImg(img[i].urlToImage);

fotos.position(0, 0);
}
}

Uma solução que encontrei lendo alguns posts aqui no stackflow, foi alterar manualmente a opacidade das imagens, uma por uma, através do inspetor HTML do browser, mas isso serve apenas para poucas imagens.

Mas isso fica impossível no caso de 2 mil imagens, por exemplo. Preciso automatizar esse processo.
Portanto, como faço para aplicar opacidade numa imagem - elemento DOM direto pelo código javascript?

A: Pelo visto na sua imagem da pergunta, todas as imagens que você adiciona estão dentro do body, então basta adicionar no seu CSS a opacidade que você deseja que irá ser aplicada a todas as tags <img>, sem a necessidade de recorrer ao JavaScript:
<style>
body > img{
   opacity: .3;
}
</style>


text:
Q: What is the meaning of Directivity and Reflection coefficient for a RX antenna? it's known that the circuital models of TX and RX antennas are the following ones:

They are fine, but I find it hard to understand the meaning of some concepts when applied at the RX case. For instance:
1) INPUT REFLECTION COEFFICIENT
In TX case, the antenna input reflection coefficient quantifies the reflected power at the input port because of an impedance mismatch between the source impedance Zg and the antenna impedance Za. The reflected power goes towards the source, while the difference between incident and reflected power goes into the antenna and is radiated (or, in part, accumulated in antenna parasitic reactances).
But, what does it represent in RX case? Even in this case it describes a mismatch between the other circuit (here called ZL, but suppose it's equal to Zg) and the antenna impedance. So, I'd say that the difference between incident and reflected power goes to the load circuit ZL. But where does the reflected power go in RX case? In theory, it should come back to the surrounding space of the antenna... but it seems quite strange.
2) DIRECTIVITY
The directivity of a TX antenna is the ratio between the power radiated per solid angle of our antenna and of an isotropic antenna. What is its meaning in case of a RX antenna? Is it ratio the incident power (power induced on antenna conductors by the time-varying incident Electric and Magnetic fields) on the antenna? Is the directivity the same in TX and RX?

A: There's a long discussion in comments. Here's some echoes.
You use the common series equivalent circuit for the  antenna. It's the Thevenin equivalent. If we assume that the equivalent circuit is valid then the radiation resistance can be shown to exist also when an antenna receives and it should re-radiate (=scatter) 50% of the catched power if nothing is dissipated in resistive losses and the load (=line+receiver) are exactly matched to the antenna. More re-radiation can be got by having mismatched load and that extra can be calculated with the reflection factor you asked. An open or shorted receiver end of the antenna reflects everything back and that is radiated to the space if nothing is dissipated in resistive losses.
The said automatic 50% minimum re-radiation power in lossless case can be found in numerous antenna theory writings including Wikipedia and the book of Balanis which is referenced in comments. The book is freely readable here https://archive.org/details/Antenna.Theory.Analysis.and.Design3rd.Edition/page/n97/mode/1up
The 50% re-radiation is presented in page 85 (by the original page numbering, not the web reader numbering).
Not everyone accept the idea that well matched lossless antennas should re-radiate 50% of the catched RF power. But it must happen if we accept that an antenna should have the same simplistically deduced Thevenin equivalent circuit, no matter is it connected to a passive load or to a device which maybe also transmits something.
How to present Thevenin (or Norton) equivalent of receiving antenna without that obscure automatic re-radiation? Some people seem to want that the receiver should see an equivalent circuit which outputs what's really captured. Some scientific papers are published of the problem. Here's links to 2 of them. The first one is free (or pirated), but full of cryptic math: https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.205.6066&rep=rep1&type=pdf
I unfortunately haven't good enough math skills to judge the calculations and how well it succeeds to get over the automatic 50% re-radiation. Maybe someone with the needed skills could give a comprehensive explanation for practical electricians.
The text has in its end a long list of references to earlier  texts of the same problem.
The second one must be purchased (I do not have it): https://ieeexplore.ieee.org/document/1203128
Directivity is connected with the effective catching area of the antenna. For the radiation which comes from the most sensitive direction of the antenna the effective catching area Ae = G((wavelength)^2 )/(4Pi) where G=the gain. The catched power is the wave intensity (watts/square meter) multiplied by Ae.


text:
Q: Understanding a struct in c - a uart config I'm looking at the config for a UART on an mcu. There is a structure describing the status of the UART below.
At the beginning of main() there is this line of code
uart_status_t uart_status __attribute__((unused)) = 0;
Could somebody explain what this line does?
Thanks

A: it is not a structure but an enumeration. The declaration sets uart_status to UART_IDLE. THe gcc documentation states : [unused]means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
For the gcc compiler directive, please see gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Variable-Attributes.html
– clarasoft-it


text:
Q: Using MVC2, how do I validate that a date is within a given date range? I have a requirement, in an MVC2 web application, to validate that the user is at least 13 years old.  Is there a date/datetime validation attribute that will enable me to do this?

A: Since you're not "really" validating a date, you're validating based an equation (Today - Date > 13), you'll probably have to write a custom validation attribute. Something like this (this is just a back-of-the-napkin example).
using System.ComponentModel.DataAnnotations;
public class AgeValidationAttribute : ValidationAttribute
    {
        public int MinAge { get; set; }

        public override bool IsValid(DateTime value)
        {
            if (value == null)
            {
                return true;
            }

            return DateTime.Now.Subtract(value).TotalDays > (MinAge * 365.25);
        }
    }


text:
Q: Same output repeating in loop Why does my program only show the line of code U=float(input( "Enter the value of the letter 'U' : " )) in the terminal?
    B=0
    A=0
    U=0

    while(U == 0):

         U=float(input( "Enter the value of the letter 'U' :" ))

         ent=[200,101,255,11]

         for i in ent:

             A = A + (i * ( 1 -(1/10**2)  ) / 255)  -1/(10**2)

             B = B + i

    print(B)

The output of the program in the terminal is this:
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  9
4536

Process finished with exit code 0

A: it seems like you need to fix indentation on the "print(B)" line
By giving one more TAB you will be printing each time the user inputs something, and with one more TAB you will be printing for each value inside your array!
For example, by having print() inside the for loop, the variable B will be shown 4 times (due to the ent variable) each time the user inserts a number:
    B=0
    A=0
    U=0

    while(U == 0):

         U=float(input( "Enter the value of the letter 'U' :" ))

         ent=[200,101,255,11]

         for i in ent:

             A = A + (i * ( 1 -(1/10**2)  ) / 255)  -1/(10**2)

             B = B + i

             print(B)


text:
Q: How to conclude the following process is the predictable projection of the other process? When reading a textbook, I couldn't understand how to conclude from the following condition that a stochastic process is predictable projection of the other. In the sequel I will try to formulate all relevant conditions and hopefully nothing essential is missed.
All processes mentioned below are cadlag. Say we have a Brownian filtration $\mathscr{F}_t$ and a bounded process $X$, which is $\mathscr{B}[0,T]\times\mathscr{F}_T$ measurable (here $T$ is a fixed real number). $X$ is not necessarily adapted. On the other hand, $\phi$ is a predictable process such that $\mathbb{E}[\int_0^T \phi_t^2 dt] < \infty$. Now, let's say we have that for any bounded $\mathscr{F}_t$-predictable process $u$,
$$
\mathbb{E}\left[\int_0^T X_t u_t dt\right] = \mathbb{E}\left[\int_0^T \phi_t u_t dt\right]
$$
How can we conclude from this equality that $\phi$ is the predictable projection of $X$? As far as I know, we need to establish that
$$
\mathbb{E}\left[X_S\right] = \mathbb{E}\left[\phi_S\right],\mbox{ for any stopping time $S \leq T$}
$$
But I can't see how this follows from the forgoing equality. Any hint will be greatly appreciated!


text:
Q: Fingerprint Module R305 Output decoding My hardware counterpart is passing me a series of Hex Codes as the output of an R305 Fingerprint sensor. The output is essentially a 16 x 16 Hex array, that I convert to a byte array of 256.
I have searched high and low on Google and else where, but not got any information as to what this data represents. The Hardware / IoT guy tells me it is a 8 Bit Grayscale image that contains the BMP of the Fingerprint.
I have tried to run this through SourceAFIS as the input and it rejects this as Template Data and the BMP I generate from the 256 bit array is rejected as "Source Image is too small".
I would like to know what does the 256 Hex Code output stand for? Sample Output from R305 sent to my code

EF, 1, FF, FF, FF, FF, 2, 0, 82, 3, 1, 5F, 25, 0, 0, FE,
3E, FC, 2, F8, 2, F0, 0, F0, 0, F0, 0, E0, 0, E0, 0, E0,
0, E0, 0, E0, 0, E0, 0, E0, 0, E0, 0, E0, 0, E0, 0, E0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 64, 11, E4, FE, 6C, A0, A6, BE, 25, 23, 67, DE, 3C, AA, D1,
3E, 71, AF, 67, 9E, 3B, 3F, E7, 9E, 3D, B, 50, 7F, 58, 34, 51,
7F, 27, BB, A6, FF, 24, 41, D0, 5F, 59, 8, 63, 94, 5C, B, A5,
9C, 33, 39, 67, BC, 73, 13, E4, 75, 74, 10, 4C, 7A, 2B, 1B, CF,
32, 38, B1, D1, 3A, 36, BC, 11, 1A, 2F, BB, EF, 1, FF, FF, FF,
FF, 2, 0, 82, 33, 8E, 27, 7B, 6C, C, 4E, 18, 35, 11, 10, 72,
32, 12, E6, F2, 38, 1E, 8E, F8, 3C, 35, 51, 78, 28, 1E, 66, D3,
33, A2, E6, 99, 40, 35, E7, F9, 6E, 8D, E2, F6, 2C, 34, D1, 70,
34, 16, E6, 34, 3B, 96, CF, 8E, 40, 25, 26, B4, 32, 2F, A7, D4,
36, 24, 8F, F2, 28, 36, 91, CD, 26, 2E, EB, 50, 26, 31, 14, B1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

My conversion procedure from Hex to Byte Array

    var templateData = File.ReadAllText(filename);
    var data = templateData.Split(new[] { ',' },StringSplitOptions.RemoveEmptyEntries);
    byte[] tmplData = new byte[data.Length];
    for (int i = 0; i
Scratching my head since last two days. Any pointers appreciated.

A: Its the Fingerprint template of 256 bytes in hex format. You can use python PIL library.
 From PIL import Image

 im=Image.frombytes('L',(16,16),data)

 im.show()


text:
Q: Visual Studio 2019 new solution location I am using Visual Studio 2019.
I want to create a new .NET Core Console App and have an option to choose a location.
Currently Visual Studio 2019 is putting every console app in the same location and doesn't let me change the location or the name...
Just to be clear, I open Visual Studio 2019 and see this:

I click Create a new Project

Select Console App (.NET Core), click Create
A new project is created in L:\ExhaustivePatternMatching and it's always called ConsoleApp1, but if I create another it goes into same folder and is called ConsoleApp2...
Is their a setting I can change so that I can select the project / solution location and also the name?
Edit: I upgraded to version and it sorta works...

A: Resharper messes things up on that dialog, sometime freezes it, and may also completely wipe out the location input fields.  Refresh / reinstall the newest Resharper to fix it.

A: I upgraded to Version 3.0 and it sorta works, albeit with a messed up interface


text:
Q: Using CallByName with an 'event sink' for a field on a form I have text boxes on several forms in my application that have a "zoom" capability -- double-click on them and a pop-up form appears which you can resize and edit to your hearts content. This is coded via a class module "appZoomText" which acts as an 'event sink' for the text box events.
I'm trying to create a content menu and ribbon item which replicates the double click behaviour (for those of my users who don't read documentation but might wonder what a zoom icon does if they see it.)
On entry to a zoomable text box, this code is executed:
dim mclsZoomtext as appZoomtext
set mclsZoomtext = new appZoomtext
Set mclsZoomText.pTextBox = ActiveControl

In the class module, the following code is executed in Set pTextBox
Private WithEvents myTextBox As Access.TextBox
Set myTextBox = pTextBox
myTextBox.OnDblClick = "[Event Procedure]"

The double-click code for myTextBox is:
Private Sub myTextBox_DblClick(intCancel As Integer)
   OpenZoomForm 'Opens the relevant form with the right contents -- works fine
End Sub

The relevant menu item is enabled in Set ptextBox and disabled when pTextBox is exited (this is working fine).
The code invoked when the context menu item is clicked is:
Public Function OnActionZoom() As Boolean

Dim ctl As Control

Set ctl = GetCurrentControl
'GetCurrentControl returns the current Control object on a form or subform and works fine

CallByName ctl.Parent, ctl.Name & "_DblClick", VbMethod

OnActionZoom = True

End Function

I get an error 2465 ("can't find the field referred to") on the CallByName line.  I'm assuming that this is because the DblClick code is in the event sink not the form. ctl.parent and ctl.name are set correctly.
How can I code this to invoke the event sink code?
Update: I've tried creating an empty (Public) Field_DblClick sub in the form; doesn't help - this empty sub runs but the event in the class module doesn't fire. Neither does making myTextBox_DblClick Public instead of Private.
In this instance I could just invoke OpenZoomForm directly, or maybe I could have a single public instance of appZoomText that gets associated with different textboxes as required (I haven't tried this).
However, I need to use a similar method to create a menu item to drill-down in a number of comboboxes and textboxes -- double-clicking in the combo-box/textbox opens an edit form for the item in the ox -- but the edit form isn't always the same, and I can't have a single public instance of each event sink.
Similar code:
Combobox_Enter or TextBox_Enter:
dim mclsClass as ClassX
set mclsClass as new ClassX
set mclsClass.ComboBox = ActiveControl 'Or set mclsClass.textbox = activecontrol

in ClassX:
    Private Withevents myComboBox as ComboBox
    Public Property Set ComboBox (pctlComboBox as ComboBox)
       set myComboBox = pctlComboBox
       myComboBox.OnDblClick = "[Event Procedure]"
    End Property

   Private WithEvents myTextBox as TextBox
    Public Property Set TextBox(pctltextBox as TextBox)
       set myTextBox= pctltextBox
       myTextBox.OnDblClick = "[Event Procedure]"
    End Property

Public Sub myComboBox_DblClick(intCancel As Integer)
   If Not IsNull(KeyID(myComboBox.Text)) Then 'Check that there is a record to edit
       EditFormX(myComboBox) 'EditFormX depends on the Class
       'Some more code in here depending on the user's edit
       myComboBox.Requery
   End If
End Sub

Public Sub mytextBox_DblClick(intCancel As Integer)
   If Not IsNull(KeyID(myTextBox.Text)) Then 'Check that there is a record to edit
       EditFormX(myTextBox) 'EditFormX depends on the Class
       'Some more code in here depending on the user's edit
       myTextBox.Requery
   End If
End Sub

A: For CallByName to work, you need to ensure the following:
1) The method being called is public not private.
2) All required parameters are passed.
As such, you need to make the event handlers public (as you are now doing), and pass an additional argument to CallByName for the DblClick handers' Cancel parameter. Since you aren't doing anything with that parameter inside the methods themselves, passing just 0 will do:
CallByName Ctl.Parent, Ctl.Name + "_DblClick", 0

Update 1 - example of this working [note this proves too simple in the OP's case - see Update 2 below]
a) Create a new Access project.
b) Add a new blank form to the project, and a TextBox to the form.
c) Double click the text box's On DblClick event in the Properties window, choosing the Code Builder option if prompted.
d) Add the following code for the handler:
Private Sub Text1_DblClick(Cancel As Integer)
  MsgBox "Hello World!"
End Sub

e) Amend the method's header so that it reads Public Sub not Private Sub
f) View (open) the form, and focus the text box by clicking inside it.
g) Go back into the VBA editor, and add a new standard module.
h) Add the following sub-routine to the module:
Sub Test()
  Dim Ctl As Access.Control
  Set Ctl = Screen.ActiveControl
  CallByName Ctl.Parent, Ctl.Name + "_DblClick", VbMethod, 0
End Sub

i) With the caret inside the Test routine, press F5 or click the Run button
On this, the 'Hello World' message appears for me.
Update 2
With the use of WithEvents now explicit, a demo of something that may work in your situation:
1) In Access, create a new database and add a blank form to it.
2) Add a text box and a combo box to the form, and call then txtTest and cboTest; next, add three command buttons, calling them cmdCreateControllers, cmdDestroyControllers and cmdExecuteController respectively, and setting their captions to 'Create controllers', 'Destroy controllers' and 'Execute controller'. Also set cmdDestroyControllers and cmdExecuteController's Enabled properties to False.
3) In the VBA editor, add a class module, rename it IController, and add the following code:
Option Explicit

Sub Execute()
End Sub

This is our interface type (i.e., abstract class definition).
4) Via Tools|References..., add a reference to 'Microsoft Scripting Runtime', of whose Dictionary class we will shortly be using.
5) Add a standard module, and the following code to it:
Option Explicit

Private mControllers As New Scripting.Dictionary

Sub RegisterController(Obj As Object, Controller As IController)
  mControllers.Add Obj, Controller
End Sub

Sub UnregisterController(Obj As Object)
  mControllers.Remove Obj
End Sub

Function GetController(Obj As Object) As IController
  Set GetController = mControllers(Obj)
End Function

Function IController_Initialize(Controller As IController, _
  OldObj As Object, NewObj As Object) As Object
  If Not (NewObj Is OldObj) Then
    If Not (OldObj Is Nothing) Then UnregisterController OldObj
    If Not (NewObj Is Nothing) Then RegisterController NewObj, Controller
  End If
  Set IController_Initialize = NewObj
End Function

The last function here is a helper one for IController implementations. Let's now create a couple -
6) Add another class module, rename it MyTextBoxController, and add the following code:
Option Explicit

Implements IController

Private WithEvents mTextBox As Access.TextBox

Property Set TextBox(NewValue As Access.TextBox)
  Set mTextBox = IController_Initialize(Me, mTextBox, NewValue)
  If Not (mTextBox Is Nothing) Then mTextBox.OnDblClick = "[Event Procedure]"
End Property

Private Sub mTextBox_DblClick(Cancel As Integer)
  IController_Execute
End Sub

Private Sub IController_Execute()
  MsgBox "Hello from the example text box controller!"
End Sub

7) Add another class module, rename it MyComboBoxController, and add the following code:
Option Explicit

Implements IController

Private WithEvents mComboBox As Access.ComboBox

Property Set ComboBox(NewValue As Access.ComboBox)
  Set mComboBox = IController_Initialize(Me, mComboBox, NewValue)
  If Not (mComboBox Is Nothing) Then mComboBox.OnDblClick = "[Event Procedure]"
End Property

Private Sub mComboBox_DblClick(Cancel As Integer)
  IController_Execute
End Sub

Private Sub IController_Execute()
  MsgBox "Hello from the example combo box controller!"
End Sub

8) Go back the form and handle cmdCreateControllers' Click event as thus:
Option Explicit

Private mTextBoxController As MyTextBoxController, mComboBoxController As MyComboBoxController

Private Sub cmdCreateControllers_Click()
  If mTextBoxController Is Nothing Then Set mTextBoxController = New MyTextBoxController
  Set mTextBoxController.TextBox = txtTest
  If mComboBoxController Is Nothing Then Set mComboBoxController = New MyComboBoxController
  Set mComboBoxController.ComboBox = cboTest
  cmdDestroyControllers.Enabled = True
  cmdExecuteController.Enabled = True
End Sub

9) Handle the other two buttons' Click events like this:
Private Sub cmdDestroyControllers_Click()
  cmdCreateControllers.SetFocus
  cmdDestroyControllers.Enabled = False
  cmdExecuteController.Enabled = False
  Set mTextBoxController.TextBox = Nothing
  Set mComboBoxController.ComboBox = Nothing
End Sub

Private Sub cmdExecuteController_Click()
  Dim Name As String
  Name = InputBox("Enter the name of the control whose controller you want to execute:")
  If Name = "" Then Exit Sub
  GetController(Me.Controls(Name)).Execute ' add error handling as desired!
End Sub

10) Open the form, and double click either the text box or the combo box - nothing should happen.
11) Click Create Controllers, and double click again: a message box should show.
12) Click Execute Controller, and enter txtTest: a message box should again show.
13) Unhook the custom event sinks and unregister them as object controllers by clicking Destroy Controller; having done that, double clicking either of the subject controls should once more do nothing.

A: I've found the following works for the "zoomable" boxes, where the name of the relevant class and the textbox control within it are always the same.
Within the form:
Public mclsZoomText As appZoomText

and on entry to the control:
set mclsZoomtext = new appZoomtext
Set mclsZoomText.pTextBox = ActiveControl

Within the class:
    Public WithEvents myTextBox As Access.TextBox
    Public Sub myTextBox_DblClick(intCancel As Integer)
      OpenZoomForm
    End Sub

and when the zoom option is invoked from the menu:
Public Function OnActionZoom() As Boolean

Dim ctl As Control
dim intX as Integer

Set ctl = GetCurrentControl
'GetCurrentControl returns the current Control object on a form or subform

Call ctl.Parent.mclsZoomText.myTextBox_DblClick(intX)

OnActionZoom = True

End Function

For the more complex case this answer is excellent.


text:
Q: Loop through a table and get the value of each checked checkbox I have a problem right now. I'm trying to loop through my current table td and get each value of the checked checkboxes and concatenate all the checked values into a string, but I'm unable to accomplish it.
This is what I have so far:
HTML:

         <input type="checkbox" id="chkBox1" value="TestVal1">Test Val 1
         <input type="checkbox" id="chkBox2" value="TestVal2">Test val 2

          <input type="checkbox" id="chkBox3" value="TestVal3">Test val 3

Javascript:
var TableVals = "";
    $('.TestTable').each(function(){
        TableVals += $('.TestTable').find('input[type="checkbox"]:checked').val();
        alert(TableVals);
    })

So if id chkBox1, chkBox2, chkBox3 was checked, I'm expecting:
Test Val 1, Test val 2, Test val 3 are checked

If only chkBox1, then
 Test Val 1 is checked

JSFiddle attached here: https://jsfiddle.net/hegx4a0t/3/

A: You need to add an event listener to them so that the js will happen when the user clicks and not when the page loads where none of them will be checked.
https://jsfiddle.net/hegx4a0t/19
var tableVals = "";
var checkboxes = document.querySelectorAll('.TestTable input[type="checkbox"]')

checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function(e) {
    tableVals += e.target.value
    alert(tableVals)
  }, { once: true })
})

A: Please try this. It will work for you.

var TableVals = "", helpingVerb = ' is ';
var allCheckedInput = $('.TestTable td input[type="checkbox"]:checked');

for(key in allCheckedInput){
    if(key > 0){
      TableVals += ', ';
    }

    TableVals += $(allCheckedInput[key]).val();
}

if(allCheckedInput.length > 1){
  helpingVerb = ' are ';
}
var finalString = TableVals + helpingVerb + 'checked';
 console.log(finalString);

    <input type="checkbox" id="chkBox1" value="Test Val 1" checked>Test Val 1
    <input type="checkbox" id="chkBox2" value="Test val 2" checked>Test val 2

    <input type="checkbox" id="chkBox3" value="Test val 3">Test val 3


text:
Q: How to expand primary partition when WUBI is used to install? I have installed Ubunut 12.04 using WUBI. The "Installation size" options I chosen was 18GB i.e the amount of space you want to "give up" for WUBI. That is the space wubi's Ubuntu install is able to use. Wubi creates a disk image (loopmounted device) on your host system in/on which Ubuntu is installed. Now, I am running out of memory in primary partition.
Could anyone help me out to extend/stretch the partition size?

A: *

*-Boot from an Ubuntu Live CD

*-Mount your NTFS partition that the root.disk file lives. For me it was sda3 but just check in GParted (included on the Live CD) In most
cases it is the one that is largest, labeled OS. You must mount it
with these commands (make sure that you mount the correct drive, if
yours is sda1 then replace "sda3" in the command with "sda1"):  sudo
mkdir -p /media/winsudo mount /dev/sda3 media/win

*-Check the size of your root.disk (optional) de -h --apparent-size /media/win/ubuntu/disks/root.disk

*-Run fsck on root.disk fsck -f /media/win/ubuntu/disks/root.disk

*-Resize root.disk (this command resizes it to 40GB, but you can resize it to whatever you want, ONLY IF YOU HAVE THE REQUIRED SPACE
ON YOUR HARD DRIVE) resize2fs /media/win/ubuntu/disks/root.disk 40G

*-Shutdown and boot into your WUBI installation
But if while doing this process some crash happens you can recover deleted files and folders from corrupted or formatted hard disk drive, memory card, SD cards and many more storage device use windows data recovery software


text:
Q: Angular JS ng-include binding issues I have created a pager widget using template file which I am using twice in my HTML page. I have a select for go to page option and also links for previous and next page.
Problem is that when I use select box for updating current page its updated and then I use previous and next page links, the current page gets updated but select box doesn't get updated.
Please tell me what I am doing wrong. Is there any logical mistake in my approach to building a pager widget like this?
Controller Code:
 var gallery = angular.module('gallery', []);
    gallery.controller('ItemListCtrl', ['$scope', function($scope){
      /*  Pagination Code */
    $scope.currentPage = 1;
    $scope.itemsPerPage = 24;
    $scope.total = 100;
    $scope.range = function(min, max, step){
      step = step || 1;
      var input = [];
      for (var i = min; i <= max; i += step) input.push(i);
      return input;
    };
    $scope.prevPage = function (){
      if($scope.currentPage > 1){
        $scope.currentPage--;
      }
    };
    $scope.nextPage = function (){
      if($scope.currentPage < $scope.pageCount()){
        $scope.currentPage++;
      }
    };
    $scope.pageCount = function (){
      return Math.ceil($scope.total / $scope.itemsPerPage);
    };
    $scope.setPage = function (n){
      if(n >= 0 && n <= $scope.pageCount()){
        $scope.currentPage = parseInt(n, 10);
      }
    };
  }]);

Here is the plnkr URL for reproducing the issue.
http://plnkr.co/edit/9LUJnVzWAS9BauyORQn5?p=preview

A: The root cause is ng-include will create a separate scope for targeted element, so a quick fix to your code is adding $parent prefix to all scope objects.
<fieldset class="pager">

Page {{$parent.currentPage}} of {{$parent.pageCount()}}

Go to page
<select ng-model='$parent.currentPage' ng-change="$parent.setPage($parent.currentPage)">
<option ng-repeat="n in range(1,$parent.pageCount())" value="{{n}}" ng-selected="n === $parent.currentPage">{{n}}</option>
</select>

Previous Page
 |
Next Page

</fieldset>

Per Angular document Understanding Scopes, Scope inheritance won't work as you expected when you try 2-way data binding (i.e., form elements, ng-model) to a primitive. This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models


text:
Q: Why does `const` qualifier gets discarded in this initialization? I'm getting initialization discards 'const' qualifier from pointer target type warning in the line .grid_col = &c_ax_gd i.e. assigning an address expression to a pointer, which is part of a constant structure.

struct color {
    double r;
    double g;
    double b;
    double a;
};
struct graph {
    double origin[2];
    double dim[2];
    double scale[2];
    double grid_line_width;
    double axes_line_width;
    struct color *grid_col;
    struct color *axes_col;
};

int main(void) {
    static const struct color c_ax_gd = {0.5, 0.5, 0.5, 1};
    static const double h = 600, w = 800;
    const struct graph g = {
            .origin = {w / 2, h / 2},
            .dim = {w, h},
            .scale = {w / 20, h / 20},
            .grid_line_width = 0.5,
            .axes_line_width = 1,
            .grid_col = &c_ax_gd,
            .axes_col = &c_ax_gd
    };
    ....
}

I found the following in C99 standard

More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following:

*

*an arithmetic constant expression,

*a null pointer constant,

*an address constant, or

*an address constant for an object type plus or minus an integer constant expression.

  An address constant is a null pointer, a pointer to an lvalue designating an object of static storage duration, or a pointer to a function designator; it shall be created explicitly using the unary & operator or an integer constant cast to pointer type, or implicitly by the use of an expression of array or function type

My question is, doesn't that mean &c_ax_gd is an address constant? If so, how does using an address constant inside an initializer for a constant structure discards the const qualifier?

A: The problem is somewhere else. Even if a struct is const, if it has pointers as members, the objects those pointers point to are not automatically const. You can see that from the following example.
struct example {
  int * p;
};

int
main()
{
  /* const */ int a = 1;
  const struct example s = {&a};
  *(s.p) = 2;
  return 0;
}

Therefore, if you uncomment the /* const */ and assign the address of a to s.p, you're discarding the const qualifier on a. That's what your compiler warns you about.

A: g is const, which means all its members are const (including grid_col). So grid_col is a const pointer to struct color and &c_ax_gd is a pointer to const struct color.
You are tryting to initialize const struct color pointer with a struct color pointer and that's why you get the warning.
C99 6.5.16.1

both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right

If you ignore the warning, you'll just get undefined behavior if you modify the value grid_col points to.


text:
Q: subclassing dict; dict.update returns incorrrect value - python bug? I needed to make a class that extended dict and ran into an interesting problem illustrated by the dumb example in the image below.

Why is d.update() ignoring the class's __getitem__?
EDIT: This is in python2.7 which does not appear to contain collections.UserDict
Thinking UserDict.UserDict is the equivalent I tried this, and it gets closer, but still behaves interestingly.

A: This is an example of the open-closed-principle (the class is open for extension but closed for modification).  It is good thing to have because it allows subclassers to extend or override a method without unintentionally triggering behavior changes in others and without breaking the classes's invariants.
We even do this in pure python code as well; for example, inside the pure python ordered dict code, the class local call from __init__() to update() is done using name mangling.  This allows a subclasser to override update() without accidentally breaking __init__().
Sometimes, this is inconvenient.  It means that a subclasser has to override every method whose behavior they want to change including get(), update(), and others.  However, there are offsetting benefits (protection of internal invariants, preventing implementation details from leaking from the abstraction, and allowing users to assume the methods are independent of one another).
This style (chosen by Guido from the outset) is the default for the builtin types (otherwise we would forever be fighting segfaulting invariant violations) and for some pure python classes.
We do document when there is a departure from the default.  For example, the cmd module uses the framework design pattern, letting the user define various do_action() methods.  Also, some of the http modules do the same, specifically documenting that a user's do_GET() method is called and that is how you attach customized HTTP event handlers.
In the absence of specifically documented method hooks (i.e. those listed above or methods like dict.__missing__(), a subclasser should presume method independence.  Otherwise, how are you to know whether __getitem__() calls get() under the hood or vice-versa?
FWIW, this isn't unique to Python.  It comes up quite a bit in object oriented programming.  Correctly designed classes either document root methods that affect the behavior of other methods or they are presumed to be independent.
There may need to be a FAQ for this, but nothing is broken or wrong here (other than Python having way too many dict variants to chose from).  If someone mistakenly assumes or believes that __getitem__() must be called by the other accessor methods, they find out very quickly that assumption is wrong (that is if they run even minimal tests on the code).


text:
Q: C# How to run a process as a host? I want to run a program that will be a host for another one, so the main program would be launched, which would then launch for example another executable and the main program would be the main process running it?
To summarize:

*

*Launch.exe

*Actualprogram.exe

Launch.exe executes (hosting) running Actualprogram.exe, so only Launch.exe would be listed as a process. Thanks


text:
Q: Let $ a \neq 0,$ $b$ integers, show that $N_{a,b} := \{a + nb: n \in \mathbb{Z}\}$ is basis for some topology on $\mathbb{Z}.$ It is Hausdorff? Each $N_{a,b}$ is closed, why?
I am having trouble in how to show that each $N_{a,b}$ is closed... I saw in wikipedia that $N_{a,b}^c = \mathbb{Z} - \cup_{j=1}^{a-1}N_{a,b+j}.$ But, how can I see this?
How do I check that it is Hausrdoff or not?

A: First of all, there is an error in your question: denoting
$$N_{a,b}= \{ a+nb : n \in \Bbb{Z} \} = a+b \Bbb{Z}$$
you need $b \neq 0$ and not $a \neq 0$ (in fact, for $b=0$ this is just the singleton $\{ a \}$: this would generate the discrete topology on $\Bbb{Z}$).
You can see that $N_{a,b}$ is simply a coset of the subgroup $b \Bbb{Z}$. To check that these form a basis for a topology of $\Bbb{Z}$ (called the profinite topology of $\Bbb{Z}$) we have to check the usual axiom of basis of a topology (which I will not write down). Let
$$x \in (a+b\Bbb{Z}) \cap (a' + b'\Bbb{Z})$$
or, equivalently, let $x$ satisfy the system of congruences
$$x \equiv a \mod{b} \\ x \equiv a' \mod{b'}$$
Then one can easily see that $x+bb', x+2bb', x+3bb', \dots$ are solutions for this system; hence
$$x \in x + bb' \Bbb{Z} \subseteq (a+b\Bbb{Z}) \cap (a' + b'\Bbb{Z})$$
and this was exactly what you had to check.
Now, to see that all these basis elements are closed, I make an example. Fix $b=2$. Then, in practice, you have
$$2\Bbb{Z} , 1+ 2 \Bbb{Z}$$
and all of these form a partition of $\Bbb{Z}$. Since both are open, their complement is closed: but they are complements each other! So these two sets are closed.
You can do the same for
$$b\Bbb{Z} , 1+ b\Bbb{Z} , \dots , (b-1)+b\Bbb{Z}$$
these are pairwise disjoint open sets, forming a partition of $\Bbb{Z}$. Since the complement of each of these is a union of basic open sets (hence it is open), each of these is also closed.


text:
Q: GitHub API secret encryption with libsodium in Node.js: UnhandledPromiseRejectionWarning: Error: bad public key size I want to set a repository secret via the GitHub REST API. I use the example from the docs:
const sodium = require('tweetsodium');

const key = "base64-encoded-public-key";
const value = "plain-text-secret";

// Convert the message and key to Uint8Array's (Buffer implements that interface)
const messageBytes = Buffer.from(value);
const keyBytes = Buffer.from(key, 'base64');

// Encrypt using LibSodium.
const encryptedBytes = sodium.seal(messageBytes, keyBytes);

// Base64 the encrypted secret
const encrypted = Buffer.from(encryptedBytes).toString('base64');

console.log(encrypted);

I receive this error:
(node:6008) UnhandledPromiseRejectionWarning: Error: bad public key size
    at checkBoxLengths (C:\Users\User\probot\node_modules\tweetnacl\nacl-fast.js:2158:54)
    at Function.nacl.box.before (C:\Users\User\probot\node_modules\tweetnacl\nacl-fast.js:2231:3)
    at Object.nacl.box (C:\Users\User\probot\node_modules\tweetnacl\nacl-fast.js:2225:20)
    at Object.tweetSodium.seal (C:\Users\User\probot\node_modules\tweetsodium\dist\index.umd.js:53:33)
    at createSecret (C:\Users\User\probot\src\service\secret.js:55:33)
    at Object.<anonymous> (C:\Users\User\probot\src\service\secret.js:73:1)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
(node:6008) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6008) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Problem: How do I correctly encrypt and decrypt the secret so i can use it in my API?
Solution: @Topaco mentioned that you need to use a base64 encoded key such as 2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvvcCU=. This solves the error descibed above.
EDIT
I will use different secrets in different repositories. Should I generate a new base64 encoded key for each repo?

A: The example code was not quite clear what the key actually is and where you get it. You need the "repository public key" that you get from the /repos/{owner}/{repo}/actions/secrets/public-key endpoint.
Use the repository public key together with the value from your new secret:
const key = "base64-encoded-public-key"; // this is the repository public key you need to fetch from GitHub
const value = "plain-text-secret"; // the secret value

Then you can create or update your key:
  const res = await octokit.actions.createOrUpdateRepoSecret({
    owner: "GITHUBUSER",
    repo: "GITHUB_REPO",
    secret_name: "KEY_NAME",
    encrypted_value: encrypted,
  });

A: Here is a code that I used.
const crypto = require('crypto');

const sodium = require('tweetsodium');
const { Octokit } = require("@octokit/core");

// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo
const octokit = new Octokit({ auth: process.env.GH_PERSONAL_ACCESS_TOKEN });

module.exports = async () => {
  const encryptionKey = crypto.randomBytes(16).toString('hex');
  const publicKeyResponse = await octokit.request('GET /repos/<USERNAME>/<REPO>/actions/secrets/public-key');
  const publicKey = publicKeyResponse.data.key;
  const publicKeyId = publicKeyResponse.data.key_id;

  // Convert the message and key to Uint8Array's (Buffer implements that interface)
  const messageBytes = Buffer.from(encryptionKey);
  const keyBytes = Buffer.from(publicKey, 'base64');

  // Encrypt using LibSodium.
  const encryptedBytes = sodium.seal(messageBytes, keyBytes);

  // Base64 the encrypted secret
  const encryptedEncryptionKey = Buffer.from(encryptedBytes).toString('base64');

  await octokit.request('PUT /repos/<USERNAME>/<REPO>/actions/secrets/ENCRYPTION_KEY', {
    owner: '<USERNAME>',
    repo: '<REPO>',
    secret_name: 'ENCRYPTION_KEY',
    key_id: publicKeyId,
    encrypted_value: encryptedEncryptionKey,
  });

  return encryptionKey;
};


text:
Q: Performance of map pattern in multithreaded program lower than expected (4x speedup vs 8x) I'm getting started in multithreaded programming so please excuse me if the following seems obvious. I am adding multithreading to an image processing program and the speedup isn't exactly the one I expected.
I'm currently getting a speedup of 4x times on a 4 physical processor cpu with hyperthreading (8), so I'd like to know if this kind of speedup is expected. The only thing I can think of is that it may make sense if both hyperthreads of a single physical CPU have to share some sort of memory bus.
Being new to multithreading it's not entirely clear to me if this would be considered an I/O bound program considering that all memory is allocated in RAM (I understand that the virtual memory manager of my OS will be the one deciding to page in/out this supposed memory amount from the heap) My machine has 16Gb of RAM in case it helps deciding if paging/swapping can be an issue.
I've written a test program showcasing the serial case and two parallel cases using QThreadPool and tbb::parallel_for
The current program as you can see has no real operations other than setting a supposed image from black to white and it's done on purpose to know what the baseline is before any real operations are applied to the image.
I'm attaching the program in hope that someone can explain me if my quest for a roughly 8x speedup is a lost cause in this kind of processing algorithm. Note that I'm not interested in other kinds of optimizations such as SIMD as my real concern is not just to make it faster, but to make it faster using purely multithreading, without getting into SSE nor processor cache level optimizations.
#include <iostream>
#include <sys/time.h>

#include <vector>
#include <QThreadPool>
#include "/usr/local/include/tbb/tbb.h"

#define LOG(x) (std::cout << x << std::endl)

struct col4
{
    unsigned char r, g, b, a;
};

class QTileTask : public QRunnable
{
public:
    void run()
    {
        for(uint32_t y = m_yStart; y < m_yEnd; y++)
        {
            int rowStart = y * m_width;
            for(uint32_t x = m_xStart; x < m_xEnd; x++)
            {
                int index = rowStart + x;
                m_pData[index].r = 255;
                m_pData[index].g = 255;
                m_pData[index].b = 255;
                m_pData[index].a = 255;
            }
        }
    }

    col4*          m_pData;
    uint32_t       m_xStart;
    uint32_t       m_yStart;
    uint32_t       m_xEnd;
    uint32_t       m_yEnd;
    uint32_t       m_width;
};

struct TBBTileTask
{
    void operator()()
    {
        for(uint32_t y = m_yStart; y < m_yEnd; y++)
        {
            int rowStart = y * m_width;
            for(uint32_t x = m_xStart; x < m_xEnd; x++)
            {
                int index = rowStart + x;
                m_pData[index].r = 255;
                m_pData[index].g = 255;
                m_pData[index].b = 255;
                m_pData[index].a = 255;
            }
        }
    }

    col4*          m_pData;
    uint32_t       m_xStart;
    uint32_t       m_yStart;
    uint32_t       m_xEnd;
    uint32_t       m_yEnd;
    uint32_t       m_width;
};

struct TBBCaller
{
    TBBCaller(std::vector<TBBTileTask>& t)
        : m_tasks(t)
    {}

    TBBCaller(TBBCaller& e, tbb::split)
        : m_tasks(e.m_tasks)
    {}

    void operator()(const tbb::blocked_range<size_t>& r) const
    {
        for (size_t i=r.begin();i!=r.end();++i)
            m_tasks[i]();
    }

    std::vector<TBBTileTask>& m_tasks;
};

inline double getcurrenttime( void )
{
    timeval t;
    gettimeofday(&t, NULL);
    return static_cast<double>(t.tv_sec)+(static_cast<double>(t.tv_usec) / 1000000.0);
}

char* getCmdOption(char ** begin, char ** end, const std::string & option)
{
    char ** itr = std::find(begin, end, option);
    if (itr != end && ++itr != end)
    {
        return *itr;
    }
    return 0;
}

bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
    return std::find(begin, end, option) != end;
}

void baselineSerial(col4* pData, int resolution)
{
    double t = getcurrenttime();
    for(int y = 0; y < resolution; y++)
    {
        int rowStart = y * resolution;
        for(int x = 0; x < resolution; x++)
        {
            int index = rowStart + x;
            pData[index].r = 255;
            pData[index].g = 255;
            pData[index].b = 255;
            pData[index].a = 255;
        }
    }
    LOG((getcurrenttime() - t) * 1000 << " ms. (Serial)");
}

void baselineParallelQt(col4* pData, int resolution, uint32_t tileSize)
{
    double t = getcurrenttime();

    QThreadPool pool;
    for(int y = 0; y < resolution; y+=tileSize)
    {
        for(int x = 0; x < resolution; x+=tileSize)
        {
            uint32_t xEnd = std::min<uint32_t>(x+tileSize, resolution);
            uint32_t yEnd = std::min<uint32_t>(y+tileSize, resolution);

            QTileTask* t = new QTileTask;
            t->m_pData = pData;
            t->m_xStart = x;
            t->m_yStart = y;
            t->m_xEnd = xEnd;
            t->m_yEnd = yEnd;
            t->m_width = resolution;
            pool.start(t);
        }
    }
    pool.waitForDone();
    LOG((getcurrenttime() - t) * 1000 << " ms. (QThreadPool)");
}

void baselineParallelTBB(col4* pData, int resolution, uint32_t tileSize)
{
    double t = getcurrenttime();

    std::vector<TBBTileTask> tasks;
    for(int y = 0; y < resolution; y+=tileSize)
    {
        for(int x = 0; x < resolution; x+=tileSize)
        {
            uint32_t xEnd = std::min<uint32_t>(x+tileSize, resolution);
            uint32_t yEnd = std::min<uint32_t>(y+tileSize, resolution);

            TBBTileTask t;
            t.m_pData = pData;
            t.m_xStart = x;
            t.m_yStart = y;
            t.m_xEnd = xEnd;
            t.m_yEnd = yEnd;
            t.m_width = resolution;
            tasks.push_back(t);
        }
    }

    TBBCaller caller(tasks);
    tbb::task_scheduler_init init;
    tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), caller);

    LOG((getcurrenttime() - t) * 1000 << " ms. (TBB)");
}

int main(int argc, char** argv)
{
    int resolution = 1;
    uint32_t tileSize = 64;

    char * pResText = getCmdOption(argv, argv + argc, "-r");
    if (pResText)
    {
        resolution = atoi(pResText);
    }

    char * pTileSizeChr = getCmdOption(argv, argv + argc, "-b");
    if (pTileSizeChr)
    {
        tileSize = atoi(pTileSizeChr);
    }

    if(resolution > 16)
        resolution = 16;

    resolution = resolution << 10;

    uint32_t tileCount = resolution/tileSize + 1;
    tileCount *= tileCount;

    LOG("Resolution: " << resolution << " Tile Size: "<< tileSize);
    LOG("Tile Count: " << tileCount);

    uint64_t pixelCount = resolution*resolution;
    col4* pData = new col4[pixelCount];

    memset(pData, 0, sizeof(col4)*pixelCount);
    baselineSerial(pData, resolution);

    memset(pData, 0, sizeof(col4)*pixelCount);
    baselineParallelQt(pData, resolution, tileSize);

    memset(pData, 0, sizeof(col4)*pixelCount);
    baselineParallelTBB(pData, resolution, tileSize);

    delete[] pData;

    return 0;
}

A: Yes, 4x speedup is expected. Hypertreading is a kind of time sharing implemented in hardware, so you can't expect to benefit from it if one thread is using up all superscalar pipelines available on the core, as it is your case. The other thread will necessarily have to wait.
You can expect an even lower speedup if your memory bus bandwidth is saturated by the threads running in less than the total number of cores available. Usually happens if you have too many cores, like in this question:
Why doesn't this code scale linearly?


text:
Q: How to share a link to facebook fan page as admin of fanpage with facebook API I have a issue with the facebook API. I created a fan page and set admin of page which is my account facebook. After that, I want to use Facebook API to post a feed to fan page. In this case, I have tested with 2 types : status message and share link.
1>Post a message to fanpage :

    $publishStream = $fb->api("/" . $fbPageId ."/feed", 'post',
    array(
        'message' => 'test ' . time() . ' http://example.com',
        )
    );

Result : I've posted to fanpage success and owner of feed was fanpage.
2> Share a link to fanpage

    $publishStream = $fb->api("/" . $fbPageId ."/feed", 'post',
    array(
        'link' => 'http://example.com',
        )
    );

Result : I've posted link to fanpage success and owner of feed was user. This feed will show in Recent Posts by Others on ABC Page (ABC is name of fanpage).
Anyone have got same issue like me ? Thanks.

A: Replace feed with links
$publishStream = $fb->api("/" . $fbPageId ."/feed", 'post', (...)

to
$publishStream = $fb->api("/" . $fbPageId ."/links", 'post', (...)

A: I just confirmed this behavior, it's really unexpected. When using a user token and posting with only the message attribute set it posts as the page.
The "Always comment and post on your page as Page.." box is unchecked in the admin settings, which is even weirder. They must be using different back ends for posting messages, as they don't have to scrape outside url links for og tags.
Anyway, use page access_tokens from the graph.facebook.com/USER_ID/accounts endpoint for consistent behavior.

A: I am having the same issue. And I am using Page access tokens each time. If the post has a "message" it goes in on the Page (and thus shared with those who like the page). If it only has a "link" it goes to my personal news feed and is shared only with friends.
And by the way, I tried including both "message" and "link" and it went on my personal new feed, not the page.

A: What kind of access token did you use each time? Looks like you used a page access token the first time, and an user access token the second.


text:
Q: Always-in-front dialogs Is there a way to create a modeless dialog box in C++ MFC which always stays on top of the other windows in the application? I'm thinking sort of like the Find dialog in Visual Studio 2005 - where it stays on top, but you can still edit the underlying text.
(If it makes any difference, it's not MDI; it's a dialog-based app)

A: Note: This does not work under Windows 10, and may not work under Windows 7 and 8 (Reports vary).
From Nish:

###Making your dialog stay on top
Haven't you seen programs which have
an "always-stay-on-top" option? Well
the unbelievable thing is that you can
make your dialog stay on top with just
one line of code. Simply put the
following line in your dialog class's
OnInitDialog() function.
SetWindowPos(&this->wndTopMost,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);

Basically what we are doing is to use
the SetWindowPos function to change
the Z-order of our dialog window. We
make our dialog stay on top of all
other windows by moving it to the top
of the Z-order. Now even when you
activate some other window, our window
will stay on top. But I'd advise you
to make sure you know exactly what you
are doing when you do this, for it
might annoy people if they can't get
your window out of the way when they
want to do that.

As you mentioned in the comments, the above line makes the window sit on top of every application.  You'll need to do
SetWindowPos(&this->wndTop,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);

To make a window sit on top of only your application.

A: The accepted answer fails for Windows 7 or above. (Or perhaps its me)
But making the modeless dialog as popup instead of child solves it.
It now gets positioned wrt main dialog window but you can write code to constrain anywhere.
Using the no border or top bar makes it a simple window.

A: It worked for me in Microsoft Windows Version 10.0.18362.476. Had to put SetWindowPos(&this->wndTopMost,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); in OnInitDialog and make the dialog as a PopUp.


text:
Q: Why does Autofac.config fail to load in [ClassInitialize] when running all tests? I have a class initialize method that runs sets up an autofac.config amoung other dependencies in mstest. When I run the tests in the file individually they pass. however when I run the tests together I get the following error:

"The configuration file 'autofac.config' was not found and is not optional.":null`

var applicationPath = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath;

var containerBuilder = new ContainerBuilder();
var msContainerBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
msContainerBuilder.AddXmlFile(Path.Combine(applicationPath,"autofac.config"));

var msContainer = msContainerBuilder.Build();
var module = new Autofac.Configuration.ConfigurationModule(msContainer);
containerBuilder.RegisterModule(module);

I am completely lost as to what is causing this. Can anybody help solve this issue?
Edit:
Opening up the msContainerBuilder object gives the same information whether the tests are run individually or all at once.


text:
Q: Track changes by JQuery on the Input Component I am trying to track changes on input element below element.
<input type="text" id="amount" style="border:0; color:#f6931f; font-weight:bold;">

This is working when I changed input values manually
$( "input[type='text']" ).change(function() {
    alert( "Test" );
  });

But when I add readonly parameter to input value and change input values via Jquery it does not working anymore? How can track changes handled by JQuery?
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">

=============================
Thanks to
Neeraj Amoli
Pranav C Balan
Solution:
Html
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">

JQuery
$("#amount").val("Something").trigger('change');

$("#amount").change(function () {
    console.log("Test");
    });

A: $("#amount").on('change',function() {
   alert("Test" );
   console.log($(this).val());
});


text:
Q: Div with overlay and button i need of add overlay opacity 0.5 up on

div has the css
 .panel.panel-default {
    border-top-color: #F5F5F5;
    border-top-width: 1px;
}
.panel {
    float: left;
    width: 100%;
    border: 0px;
    border-top: 2px solid #E5E5E5;
    margin-bottom: 20px;
    position: relative;
    -moz-box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.2);
    -webkit-box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.2);
    box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.2);
}
.panel-default {
    border-color: #ddd;
}
.panel {
    margin-bottom: 20px;
    background-color: #fff;
    border: 1px solid transparent;
    /* border-radius: 4px; */
    -webkit-box-shadow: 0 1px 1px rgba(0,0,0,.05);
    box-shadow: 0 1px 1px rgba(0,0,0,.05);
}
html * {
    outline: none !important;
}
* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
user agent stylesheetdiv {
    display: block;
}

Now I would like the div with opacity above 0.5, and the center of this opaque div I enter 4 buttons at the center vertically and horizontally
so I have to insert a new div to the opacity and another div for 4 buttons central,

1

2

3

4

http://jsfiddle.net/qu62mvkk/10/
http://jsfiddle.net/qu62mvkk/13/

A: Do not use opacity because all children elements will inherit this, use background-color RGBA instead. eg:
background-color: rgba(255,255,255,0.5),
this will make only your selected div with opacity.


text:
Q: Splitting columns but not all new rows are created I have a csv that looks like this:
    FIPS     display_name               Value
    2013    "Aleutians East, (AK)"      172.9
    2016    "Aleutians West, (AK)"      172.2

I want to split a column into 2 columns. I tried this:
df['county','state'] = df['display_name'].str.split(', ',expand=True)

The output was this:
cnty_fips   display_name    Value   (county, state)
2013    "Aleutians East    172.9    "Aleutians East
2016    "Aleutians West    172.2    "Aleutians West

Not sure why the second half of the data is erased and not made into a new column.
How can I get two new columns when I split a column where one gives the county and another the state?

A: The issue here is that str.split returns two columns, but you are trying to assign that value to a single column. The following should produce the desired output.
temp = df.display_name.str.split(", ", expand=True)
temp.columns = ["county", "state"]

pd.concat([df.drop("display_name", axis=1), temp], axis=1)

   FIPS  value          county state
0  2013  172.9  Aleutians East  (AK)
1  2016  172.2  Aleutians West  (AK)

A: When you split a column into two separate columns, you need to store them in two separate columns. In your case, your are storing it in columns, but not wrapping it into the dataframe.
df = pd.DataFrame({'Fips': [2013,2016],
                   'display_name': ["Aleutians East, (AK)","Aleutians West, (AK)"],
                   'value': [172.9,172.2]})
df[['county','state']] = df['display_name'].str.split(',',expand=True)

Notice that the two columns are wrapped together into the dataframe as df[['county','state']], while you simply wrote it as df['county','state'].
The output looks like:
   Fips          display_name  value          county  state
0  2013  Aleutians East, (AK)  172.9  Aleutians East   (AK)
1  2016  Aleutians West, (AK)  172.2  Aleutians West   (AK)

If you want to delete the original column before separation
df = df.drop('display_name',axis=1)
print(df)
   Fips  value          county  state
0  2013  172.9  Aleutians East   (AK)
1  2016  172.2  Aleutians West   (AK)


text:
Q: Is there a way to select only partial matching and not the exact ones I have two character vectors. The first one contains some references of natural disasters: "avalanche","flash flood","thunderstorm winds"...etc.
The second one with similar data but slightly different:"avalanche","flood","heat","winds" etc..... I am trying to find, not only the exact, but also the partial matching of the first one within the second one. So I thought I could do it separetely.
The first one is quite direct: match(dt_event,ref_event). Now I need also the "thunderstom winds" and"floash flood" to be considered as "flood" and "winds" from the ref_event, and thus get the indices as well instead of NAs. If there is a way to have both exact and partial matching in one command that would be better. Thanks in advance.
dt_event <- c("avalanche","flash flood","thunderstorm winds")
ref_event <- c("avalanche","flood","winds")
match(dt_event,ref_event)

1 NA NA

A: Assuming that two vectors are ordered and you want to compare element-wise:
dt_event[unlist(Map(grepl, ref_event, dt_event))]

or in a more general case:
dt_event[sapply(ref_event, function(x) which(grepl(x, dt_event)))]


text:
Q: Is non-stationary AR(p) process constant in mean? A non-stationary $AR(1)$ process, which is a random walk, is constant in mean, but not constant in variance. How about the other $AR(p)$ processes with the order $p>1$? Are they constant in mean?

A: If we define non-stationary AR(p) processes as the ones having single unit root, they all can be written as
$$X_t=X_{t-1}+Z_t$$
where $Z_t$ is a stationary linear process. Then the answer is yes, they are constant in mean.
In general situation is more complicated even for the AR(1) process, since in general we can define it as
$$X_t=\mu+\rho X_{t-1}+Z_t$$
Now if $\rho=1$ the process is not constant in mean.