text:
Q: XPath exclude text from last element if it meets condition The goal is to exclude text if it is contained in the last element within the tags
...
.
...

"We are a better country because of these commitments," he said. "I'll go further – we would not be a great country without [them]."

Liberals were mostly delighted by what the Washington Post called "the most ambitious defence [Obama] may ever have attempted of American liberalism and of what it means to be a Democrat".

This was the Obama many of them hoped for when they voted him into office on that wave of enthusiasm back in 2008.

Felicity Spector is a deputy programme editor for Channel 4 News.

The output should be:
"We are a better country because of these commitments," he said. "I'll go further – we would not be a great country without [them]."
Liberals were mostly delighted by what the Washington Post called "the most ambitious defence [Obama] may ever have attempted of American liberalism and of what it means to be a Democrat".
This was the Obama many of them hoped for when they voted him into office on that wave of enthusiasm back in 2008.

So, need to grab everything excluding the text if it is located in the last
 tag and there is no other text between
 and  tags as well as no other text between  and
 as illustrated in example above.
I m using
//p[normalize-space()]

but it returns eveerything including the text from the last tag
...:
"We are a better country because of these commitments," he said. "I'll go further – we would not be a great country without [them]."
Liberals were mostly delighted by what the Washington Post called "the most ambitious defence [Obama] may ever have attempted of American liberalism and of what it means to be a Democrat".
This was the Obama many of them hoped for when they voted him into office on that wave of enthusiasm back in 2008.
Felicity Spector is a deputy programme editor for Channel 4 News

while the last sentance should be excluded.
Appreciate for any hints.
UPD
Example 1. The next text should be returned if it is located in last
 (since not all the text is inside :

I was once on a travelling sanitation carnival in Uttar Pradesh when someone rushed up to me. "Rose! Rose! There's a real 'no loo no I do'!" If that's the story of Ek Prem Katha, then I'm all in favour.  But because bringing a toilet into the world, when there are still 2.4 billion people without one, is by any reckoning a very happy ending.

Example 2. The next text should not be returned if it is located in last
 (because all the text in inside ):

Sophie Elmhirst is an assistant editor of the NS

A: It is still unclear what exactly the rules are, but here is a suggestion that you can comment on:
//p[normalize-space() and not(position() = last() and em)]

which translates to
//p                           find all `p` elements anywhere in the document
[normalize-space()            but only if the contain at least 1 character that is not a white-space
and not(position() = last()   and only if the `p` element is not the last `p` child of its parent
and em)]                      and only if the `p` element has no child named `em`

and returns as a result (individual results separated by -------):

"We are a better country because of these commitments," he said. "I'll go further – we would not be a great country without [them]."

-----------------------

Liberals were mostly delighted by what the Washington Post called "the most ambitious defence [Obama] may ever have attempted of American liberalism and of what it means to be a Democrat".

-----------------------

This was the Obama many of them hoped for when they voted him into office on that wave of enthusiasm back in 2008.

Caveat: if the structure of your document is actually more complex this might go wrong in places, for example when p elements can occur anywhere in the hierarchy.

Maybe normalize-space isn't required but I always use it.

Only use it if you really want to exclude elements that have only whitespace in them.

i need to exclude text from the last p only if the whole text surrounded within em

Well, in your own example of a last p element with em in it that's not the case: the last . is actually outside of em, it's a text node of p.

EDIT Reacting to a comment:

I just figured out that the xpath doesn't return text if there is a text outside the em in last p. I have updated an example

Then use the path expression below:
//p[normalize-space() and not(position() = last() and em and not(text()))]

Sorry, I might have misunderstood you until now. The not(text()) takes into account whether there is text which is a child of p itself, outside of em.


text:
Q: d3 transitions not working in multiple browsers My question has to do with this chart (Beeswarm plot). I have a project which is based on this more or less. Some things are different and the volume of data is a little higher. For some reason, I don't see any transitions in IE, Firefox or Edge when the chart is updated with new data; however it works perfectly in chrome.
When I click on the filters to update the data, there is a 2-4 second lag and the new data is reflected after that. There is no transition but more like a graph refresh.
The exact browser versions are as follows:
Chrome v56 [Works]
Firefox v51
IE v11.576
Edge v38

Does any one have any idea about what might be causing this? Thanks in advance
Note: The example I used to make this chart works on IE, Firefox and Edge.
Jsfiddle here

A: The lag can be easily explained. You forgot to change this:
for (var i = 0; i < dataSet.length; ++i) simulation.tick();

In my original code I had approximately 190 countries. However, you have 440 data points, and that takes more time to compute.
Thus, simply change the number of calls to tick to something between 100 and 300:
for (var i = 0; i < 150; ++i) simulation.tick();
//                   ^-------- tweak this number

The greater this number the smaller the chance of overlapping circles, but the greater the lag. In a "normal" D3 force directed chart with the default settings, tick runs 300 times before the simulation stops.
If you want to keep the ticks as dataset.lenght, introducing a delay in the transitions reduces the visual effect of the lag.
Here is your updated fiddle: https://jsfiddle.net/oo20pdnk/
Regarding the other browsers, I couldn't reproduce the problem: It is working in Firefox and IE to me. However, you have some jQuery code at the bottom (which I removed anyway, mixing D3 with jQuery gives me headache).
PS: When using someone else's code, I believe it's a good idea changing the variable names. Right now you have something like africaColor, europeColor, countriesCircles etc, which makes sense in my code, but not in yours!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django+Cython import cython module in django app views a newbie to django and Cython. I am creating an app in django and need to import function in views.py from cythonized module. following is views.py inside my app.
from django.shortcuts import render
import sys
import numpy as np
import random
import math
from cython_node_val import node_val

def home(request):
    return render(request,'Home.html',{"name":"user"})

def shortest_path1(request):

    K=int(request.POST['number of layers'])
    if ((K%2!=0) or (K < 0)):
        return render(request,"shortest_path1.html",{'shortest_path1':"K must be an even integer"})
    else:
    ......

    Node_val=node_val(Hash,C,K) #node_val is from cython_node_val which is a .pyx file, Hash C and K
                                are defined in body after else statement.

    sPath=np.zeros((K,3))
    sPath[K-1,:]=Node_val[n-1,:]
    for m in range(K-2,-1,-1):
             sPath[m,:]=Node_val[int(sPath[m+1,1])]
    return render(request,"shortest_path1.html",{'shortest_path1':sPath[:,3]})'''

the directory of my project is like following:

my app directory looks like this

cython_node_val.pyx works fine when importing into a normal .py file, but when doing the same inside views.py in my app it throws me following error
File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\urls.py", line 9, in <module>
    from . import views
  File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\views.py", line 6, in <module>
    from cython_node_val import node_val
ModuleNotFoundError: No module named 'cython_node_val'

I believe if views.py is a python file and we can do operations, it should pull cython_node_val and associated functions. Where am i wrong?
Thanks for your time.

A: Use os.getcwd() to debug where you are running from your script  views.py:
import os
print(os.getcwd())

ModuleNotFoundError: No module named 'cimport'

Then adjust the path to your needs
Is usually an error when you are trying to reference something that isn't in the python running path script + the path that you are giving inside your script.


text:
Q: TypeScript linter error when loading image in React I have a React app with Next.js where I import an image using:
import image1 from '../../../img/dummy-image-2.jpg';

Later on I use:
<img src={image1} alt="Dummy" />

The app builds and runs as expected (the image is shown) but I'm getting a linter error on the src attribute in the <img> tag that reads:
Type 'StaticImageData' is not assignable to type 'string'.

How can I get rid of this error?

A: Create a file named assets.d.ts, if you don't already have a .d.ts file in you project and put the following:
declare module '*.jpg' {
  const content: any; // you can also set this to string
  export default content;
}

See this link if you want to know more about .d.ts files


text:
Q: Success message in comment form I am using wordpress 3.8. I am using comment_form(); I need to display a success message on successfully posted comment on blog. How to do this?

A: Without Ajax or plugins. Add to function.php:
add_action( 'set_comment_cookies', function( $comment, $user ) {
    setcookie( 'ta_comment_wait_approval', '1' );
}, 10, 2 );

add_action( 'init', function() {
    if( $_COOKIE['ta_comment_wait_approval'] === '1' ) {
        setcookie( 'ta_comment_wait_approval', null, time() - 3600, '/' );
        add_action( 'comment_form_before', function() {
            echo "
Your comment has been sent successfully.
";
        });
    }
});

add_filter( 'comment_post_redirect', function( $location, $comment ) {
    $location = get_permalink( $comment->comment_post_ID ) . '#wait_approval';
    return $location;
}, 10, 2 );

A: Try this: http://wordpress.org/plugins/wp-ajaxify-comments/
or (manually)
Add the following lines of code to your theme's functions.php file
    add_action('init', 'wdp_ajaxcomments_load_js', 10);
function wdp_ajaxcomments_load_js(){
        wp_enqueue_script('ajaxValidate', get_stylesheet_directory_uri().'/wdp-ajaxed-comments/js/jquery.validate.min.js', array('jquery'), '1.5.5');
        wp_enqueue_script('ajaxcomments', get_stylesheet_directory_uri().'/wdp-ajaxed-comments/js/ajax-comments.js',    array('jquery', 'ajaxValidate'), '1.1');
}
add_action('comment_post', 'wdp_ajaxcomments_stop_for_ajax',20, 2);
function wdp_ajaxcomments_stop_for_ajax($comment_ID, $comment_status){
    if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
    //If AJAX Request Then
        switch($comment_status){
            case '0':
                //notify moderator of unapproved comment
                wp_notify_moderator($comment_ID);
            case '1': //Approved comment
                echo "success";
                $commentdata=&get_comment($comment_ID, ARRAY_A);
                $post=&get_post($commentdata['comment_post_ID']); //Notify post author of comment
                if ( get_option('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] )
                    wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
                break;
            default:
                echo "error";
        }
        exit;
    }
}

You will need to add two JavaScript files jquery.validate.min.js and ajax-comments.js in the js directory of your theme.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
and the ajax-comments.js is:
jQuery('document').ready(function($){
    var commentform=$('form[action$=wp-comments-post.php]');
    commentform.prepend('

');
    var infodiv=$('#wdpajax-info');
    commentform.validate({
        submitHandler: function(form){
            //serialize and store form data in a variable
            var formdata=commentform.serialize();
            //Add a status message
            infodiv.html('
Processing...
');
            //Extract action URL from commentform
            var formurl=commentform.attr('action');
            //Post Form with data
            $.ajax({
                type: 'post',
                url: formurl,
                data: formdata,
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    infodiv.html('
You might have left one of the fields blank.
');
                },
                success: function(data, textStatus){
                    if(data=="success")
                        infodiv.html('
Thanks for your comment. We appreciate your response.
');
                    else
                        infodiv.html('
Error in processing your form.
');
                    commentform.find('textarea[name=comment]').val('');
                }
            });
        }
    });
});

Customize the style of messages
.wdpajax-error{
    border:1px solid #f9d9c9;
    padding:5px;
    color:#ff3311;
}
.wdpajax-success{
    border:1px solid #339933;
    padding:5px;
    color:#339933;
}
label.error{
    float:none !important;
    padding-left:5px;
    color:#ff3311;
}

Open your theme's comments.php and add some CSS classes to comment form input fields as described: To comment author name input, add class="required" To comment author email input, add class="required email" To comment author URL input, add class="url" To the comment textarea, add class="required"

A: if you do not want to use AJAX or any plugins, you can use $_GET to understand if comment form has been submitted or not.
<?= $_GET['unapproved'] ? '
success message
' : ''; ?>

In the above case, we have $_GET['unapproved'] if you have to approve the comments.
You can consider a statement for avoiding any errors:
if (count($_GET) > 0) {
    if ($_GET['unapproved']) {
        echo '
success message
';
    }
}


text:
Q: most efficient way to do this I have a csv file over 100,000 lines of 1 column
One column
lastName
Smith
Willams
Smith
David
Smith
Williams
David
I need to count the number of times each name occurs and print the result
I have no code to show because I don't know if I should read into a list or a dictionary.
Any thoughts would be appreciated.
I want to read in the csv and count how many times


text:
Q: Dynamic adding HttpModules and HttpHandlers Is adding / removing HttpModules and HttpHandlers at runtime from a website a good idea ?
I am looking at ways to make my website as dynamic as possible without uploading changed content all over again. Something like config files.
Rule engines exist, but learning them seems like a pain. I might be wrong in my perspective. Please suggest possible ways to change logic in the code at runtime.

A: ASP.NET 4 provides a PreApplicationStartMethod capability that can be used to add HttpModules programmatically.
I just did a blog post on that at http://www.nikhilk.net/Config-Free-HttpModule-Registration.aspx.
The basic idea is you create a derived HttpApplication that provides ability to add HttpModules dynamically at startup time, and it then initializes them into the pipeline whenever each HttpApplication instance is created within the app-domain.

A: For .NET4 and above:
For dynamically installing a HttpHandler, you need to create a HttpModule wrapper to do that. See the answer to: Any way to add HttpHandler programmatically in .NET?
To dynamically add a http module:

Install-Package Microsoft.Web.Infrastructure
Install-Package WebActivator

[assembly: PreApplicationStartMethod(typeof(MyPreStartClass), "Start")]

namespace .....
{
    public static class MyPreStartClass
    {
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(FooHttpModule));
        }
    }
}

A: One possible way is create a generic HTTPHandlerFactory which in turn returns the requested handlers.
Check out the link for more clarity


text:
Q: Using brain.js in nodejs server but getting error gpu.js not present I'm using brain.js library for creating Nural network.
Package installed perfectly, but when I ran the server then I get this error.
Cannot find module gpu.js
Then I installed "npm i gpu.js"
Then I got this error - This below error says that install visual studio 2022 latest version and run this in that. I did but didnt worked.
code part
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm ERR! code 1
npm ERR! path C:\Users\priya\JSAIML\ytHelper\node_modules\gl
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c prebuild-install || node-gyp rebuild
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@7.1.2
npm ERR! gyp info using node@18.8.0 | win32 | x64
npm ERR! gyp info find Python using Python version 3.10.3 found at "C:\Users\priya\AppData\Local\Programs\Python\Python310\python.exe"
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio
npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
npm ERR! gyp ERR! find VS For more information consult the documentation at:
npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
npm ERR! gyp ERR! stack     at VisualStudioFinder.fail (C:\Users\priya\JSAIML\ytHelper\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
npm ERR! gyp ERR! stack     at C:\Users\priya\JSAIML\ytHelper\node_modules\node-gyp\lib\find-visualstudio.js:74:16
npm ERR! gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Users\priya\JSAIML\ytHelper\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
npm ERR! gyp ERR! stack     at C:\Users\priya\JSAIML\ytHelper\node_modules\node-gyp\lib\find-visualstudio.js:70:14
npm ERR! gyp ERR! stack     at C:\Users\priya\JSAIML\ytHelper\node_modules\node-gyp\lib\find-visualstudio.js:372:16
npm ERR! gyp ERR! stack     at C:\Users\priya\JSAIML\ytHelper\node_modules\node-gyp\lib\util.js:54:7
npm ERR! gyp ERR! stack     at C:\Users\priya\JSAIML\ytHelper\node_modules\node-gyp\lib\util.js:33:16npm ERR! gyp ERR! stack     at ChildProcess.exithandler (node:child_process:420:5)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at maybeClose (node:internal/child_process:1091:16)
npm ERR! gyp ERR! System Windows_NT 10.0.22000
npm ERR! gyp ERR! command "C:\\Users\\priya\\.nvm\\versions\\node\\v18.8.0\\bin\\node.exe" "C:\\Users\\priya\\JSAIML\\ytHelper\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\priya\JSAIML\ytHelper\node_modules\gl
npm ERR! gyp ERR! node -v v18.8.0
npm ERR! gyp ERR! node-gyp -v v7.1.2
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\priya\AppData\Local\npm-cache\_logs\2023-01-08T17_34_38_565Z-debug-0.log```

this is how my code looks like

code ->

import express from 'express';
import * as brain from 'brain.js/dist/index.js';
import dotenv from 'dotenv'
import  ytData  from './md/data.js';

dotenv.config()
const app = express()
const PORT = process.env.PORT || 8000

const network = new brain.recurrent.LSTM();

const trainingData = ytData.map((item,i)=>({
    input : item.title,
    output : item.views,
}))

network.train(trainingData,{iterations : 2000});

const outputData = network.run("Simple Machine Learning With JavaScript - Brain.js")

app.get('/',(req,res)=>{
    // res.json({message : `On this title you will probably get around ${outputData} views`})
    res.send("hello")
})

app.listen(PORT, ()=>{
    console.log(`Running up the hill at ${PORT}km/hr`)
})

**Any help will be appreciated.**


text:
Q: Error when i open wamp server, the application was unable to start correctly (0xc0000142) I recently opened Wamp server after a long time I didn't touch it. It was fine back then, but when I try to open Wamp server now, I get an error that says

The application was unable to start correctly (0xc0000142).

In addition, the wamp icon is orange, while back then, it was green.
I have tried to search for a solution on the internet, but I wasn't able to find.
I have also noticed that when I try to open phpMyAdmin, the page says

#2002 - No connection could be made because the target machine actively refused it.
  The server is not responding (or the local server's socket is not correctly configured)

But i'm able to open my localhost start page (the one with the loaded extentions list).
Thanks for helping.

A: Same error after creators update 1703 (Windows 10).

Error: httpd.exe was unable to start correctly
Error code: 0xc0000142
I'll do a quick google search and see what this is about. I will get back for sure.
UPDATE: SOLUTION
WAMP has released a cumulative update to fix this. It is strongly encouraged that you apply this update after you've installed WAMP.
Wampserver update 3.0.8. Sourceforge.
Once you apply this fix, you will be able to start (Apache) WAMP normally.

A: Actually this error relate to Windows Firewall.
You can go to "Control Panel\System and Security\Windows Firewall\Allowed apps" after that click change settings and in Allow apps and feature find "Appache HTTP Server" and check public then click OK.

A: Verify your Windows Firewall Services is not running.
I faced the same issue after installing 64bit Wamp. While installing I was not prompted to allow http daemon by the firewall service.
Unsure what to do, I installed the 32bit Wamp & the firewall service prompted me to allow the http daemon.
Wamp started showing green!!


text:
Q: Why Set UAC Execution level to asInvoker is not effect? I've manifested a Visual Studio 2017 program to run asInvoker:

But when I run the compiled program: still requires elevation:

Notice the Shield overlay

I've tried searching, but I cannot see what I am doing wrong.

A: Use a tool like Resource Hacker to look at the RT_MANIFEST (id 24) assembly manifest resource:

If a manifest actually is correctly asking the OS to run the application asInvoker, then it's likely because the result of the elevation check is cached.
Try rebooting, or renaming the application to something else,e.g.:

PdfToWord - Testing renamed.exe

But since this question was asked a month ago, i assume the problem has went away since then; so you can't really know if this fixed solved it.


text:
Q: How to pass an std::barrier with a lambda completion function to a named function in C++ I am trying to make some working threads for some (quite) intensive signal processing tasks. I use C++20 for the moment to use std::jthread which I prefer over std::thread (although this is not restrictive and I don't think is related to my problem).
I would like to pass an std::barrier to a "worker function" called from some std::jthreads. If I set as argument in the "worker function" std::barrier<>& (which creates an std::barrier without a completion function) everything seems to be OK. I would like to pass an std::barrier with a custom completion function (a lambda at the moment but it may end up being a named function). I haven't managed to do that and I get compilation errors.
A working (actually it is not even compiling) example to replicate the problem is
    #include <thread>
    #include <barrier>

    int main() {
        std::barrier barrier(5, []() noexcept {std::cout << "Completion reached\n\n";}); // num of threads and completion function

        std::array<std::jthread> threads{};

        for (auto& thread : threads)
            thread = std::jthread(workerFunction, std::ref(barrier)); // Worker function (see below) and reference to the barrier

        return 0;
    }

As a "worker" function I have the following dummy (for testing purposes)
    void worker(std::stop_token stopToken, std::barrier<void(void)>& barrier) noexcept { // Most probably the issue is here at the std::barrier<void(void)>&
        while (!stopToke.stop_requested()) {
            // Do some processing and stuff (at the moment just some dummy increments)
            barrier.arrive_and_wait();
        }

        std::cout << "Termination requested for thread " << std::this_thread::get_id() << '\n';
        barrier.arrive_and_drop();
    }

At the moment I am working on Microsoft Visual Studio 2022 Community Edition (version 17.4.4) and compile (or at least try to) in debug mode.
The error I get is (where I have put some empty lines in between for clarity)

1>C:\Program Files\Microsoft Visual >Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\barrier(76,13): error C2338: static_assert >failed: 'N4861 [thread.barrier.class]/5: is_nothrow_invocable_v<CompletionFunction&> shall be true'
1>C:\Users\Aris\Documents\Development\Perception Neuron\DSP\TestBarrier.cpp(27,16): message >: see reference to class template instantiation 'std::barrier<void (void)>' being compiled
1>C:\Program Files\Microsoft Visual >Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\xmemory(1395,1): error C2207: >'std::_Compressed_pair<_Ty1,_Ty2,false>::_Myval1': a member of a class template cannot acquire a >function type
1>C:\Program Files\Microsoft Visual >Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\barrier(186,44): message : see reference to >class template instantiation >'std::_Compressed_pair<_Completion_function,std::barrier<_Completion_function>::_Counter_t,false>' >being compiled
1>        with
1>        [
1>            _Completion_function=void (void)
1>        ]

If I pass a lambda function to the thread instead, everything seems to work without errors or warnings. For example, completely dropping the worker() and instead do
    #include <thread>
    #include <barrier>

    int main() {
        std::barrier barrier(5, []() noexcept {std::cout << "Completion reached\n\n";}); // num of threads and completion function

        std::array<std::jthread> threads{};

        for (auto& thread : threads)
            thread = std::jthread([&barrier] (std::stop_token stopToken) {
                while (!stopToken.stopRequested()) {
                    // Do the same stuff
                    barrier.arrive_and_wait();
                }

                std::cout << "Termination requested for thread " << std::this_thread::get_id() << '\n';
                barrier.arrive_and_drop();
            });

      return 0;
    }

compiles and runs with intended behavior (or at least I haven't noticed anything unusual so far).
Any help and clarification would be most welcome.

A: First, you should pass a pointer-to-function type, not a function type directly, as the template argument for std::barrier:
std::barrier<void(*)(void)>&

The you also forgot to add noexcept to the function type void(void) (aka void()). noexcept is part of the type and here relevant because std::barrier requires a callable that is nothrow-invocable.
std::barrier<void(*)(void) noexcept>&

Because you are passing the barrier object to the function you also need to make sure that the type in main is the same. CTAD will deduce a different type because each lambda has a different type. So just std::barrier without template argument list doesn't work there. (The alternative would be to template worker on a template parameter T and then take a std::barrier<T>& as argument.)


text:
Q: Web Service => Web Reference Estoy trabajando con Visual Studio 2015, C#, app windows forms, al servicio que me conecto es de tipo XML
Estoy consumiendo dos web service los cuales están implementados por Web Reference
El primer web service sirve para validar un xml firmado hablemos en el escenario de que todo vaya bien:
Primer WS: Validación de xml si valido sin problemas recibo una respuesta que dice "RECIBIDA", muestro código.
private void btnFirmar_Click(object sender, EventArgs e)
    {
        try
        {
            // Create a new XML document.
            XmlDocument xmlDoc = new XmlDocument();
            var uidCert = GetCertificateByPath();

            using (var clientWs = new EnviarFactura.ec.gob.sri.celcer.RecepcionComprobantesOfflineService())
            {
                clientWs.Url = $"{sri_url}{"RecepcionComprobantesOffline"}";
                clientWs.ClientCertificates.Add(uidCert);

                FirmaXades firmaXades = new FirmaXades(SignMethod.RSAwithSHA1, DigestMethod.SHA1);

                // Cargue un archivo XML en el objeto XmlDocument.
                string path = System.Configuration.ConfigurationManager.AppSettings["testfiles.path"].ToString();
                xmlDoc.Load(Path.Combine(path, "Factura_001-500-000000005_60.01_XXXXXXXXXXXXX.xml"));

                XElement doc = XElement.Parse(xmlDoc.InnerXml);
                var result = doc.Elements("infoTributaria")
                    .Elements("claveAcceso").ToArray();
                _claveAcesso = result[0].Value;

                xmlDoc.PreserveWhitespace = true;

                firmaXades.SetContentEnveloped(xmlDoc);
                firmaXades.Sign(uidCert, SignMethod.RSAwithSHA1);
                RecepcionComprobantesOfflineService pf = new RecepcionComprobantesOfflineService();
                clientWs.validarComprobanteCompleted += ClientWsOnValidarComprobanteCompleted;
                clientWs.validarComprobanteAsync(System.Text.Encoding.UTF8.GetBytes(firmaXades.Document.InnerXml));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"{ex.Message}", @"Prueba");
        }
    }

    string _mensaje = string.Empty;
    string _estadoAurorizacion = string.Empty;

    private void ClientWsOnValidarComprobanteCompleted(object sender, validarComprobanteCompletedEventArgs validarComprobanteCompletedEventArgs)
    {
        if (validarComprobanteCompletedEventArgs != null)
        {
            _estado = validarComprobanteCompletedEventArgs.Result.estado;

            if (_estado == "RECIBIDA")
            {
                using (var client2Ws = new EnviarFactura.ec.gob.sri.celcer1.AutorizacionComprobantesOfflineService())
                {
                    client2Ws.Url = $"{sri_url}{"AutorizacionComprobantesOffline"}";
                    client2Ws.autorizacionComprobanteCompleted += Client2WsOnAutorizacionComprobanteCompleted;
                    //var response2 =
                    client2Ws.autorizacionComprobanteAsync(_claveAcesso);
                }
            }
        }
    }

En la implementación del Web reference se creo la clase a partir del xml, estoy usando un método asincrono que es el siguiente:
public void validarComprobanteAsync(byte[] xml) {
        this.validarComprobanteAsync(xml, null);
    }

    /// <remarks/>
    public void validarComprobanteAsync(byte[] xml, object userState) {
        if ((this.validarComprobanteOperationCompleted == null)) {
            this.validarComprobanteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnvalidarComprobanteOperationCompleted);
        }
        this.InvokeAsync("validarComprobante", new object[] {
                    xml}, this.validarComprobanteOperationCompleted, userState);
    }

    private void OnvalidarComprobanteOperationCompleted(object arg) {
        if ((this.validarComprobanteCompleted != null)) {
            System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
            this.validarComprobanteCompleted(this, new validarComprobanteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
        }
    }

    /// <remarks/>
    public new void CancelAsync(object userState) {
        base.CancelAsync(userState);
    }

Tengo la necesidad de trabajar con los métodos asincronos por que no se cuanto tiempo desmore en responder el primer web service de validación y cuando este responda necesito mandar un parámetro al segundo web service que también lo quiero trabajar asincronamente.
El problema que tengo es que no se hacer una implementación adecuada que me permita saber cuando respondio el primer Ws para poder llamar al segundo WS
En el código que les muestro se me ocurrio llamar al método clientWs.validarComprobanteCompleted, que me imagino que es cuando se completo la petición al primer WS y este respondió.
Ahora en el evento clientWs.validarComprobanteCompleted llamo al segundo WS pasandole un parámetro el cual no he podido capturar el mensaje que este responde.
private void ClientWsOnValidarComprobanteCompleted(object sender, validarComprobanteCompletedEventArgs validarComprobanteCompletedEventArgs)
    {
        if (validarComprobanteCompletedEventArgs != null)
        {
            _estado = validarComprobanteCompletedEventArgs.Result.estado;

            if (_estado == "RECIBIDA")
            {
                using (var client2Ws = new EnviarFactura.ec.gob.sri.celcer1.AutorizacionComprobantesOfflineService())
                {
                    client2Ws.Url = $"{sri_url}{"AutorizacionComprobantesOffline"}";
                    client2Ws.autorizacionComprobanteCompleted += Client2WsOnAutorizacionComprobanteCompleted;
                    //var response2 =
                    client2Ws.autorizacionComprobanteAsync(_claveAcesso);
                }
            }
        }
    }

    private void Client2WsOnAutorizacionComprobanteCompleted(object sender, autorizacionComprobanteCompletedEventArgs comprobanteCompletedEventArgs)
    {
        if (comprobanteCompletedEventArgs != null)
        {
            //foreach (var encontrado in comprobanteCompletedEventArgs.Result.autorizaciones.ToList())
            //{
            //    MessageBox.Show(_estadoAurorizacion = encontrado.estado);
            //    foreach (var x in encontrado.mensajes)
            //    {
            //        MessageBox.Show(_mensaje = x.mensaje1);
            //    }
            //}
            var result = comprobanteCompletedEventArgs.Result.autorizaciones.Select(x => x.estado);
        }
    }

El método async de este es el siguiente:
public void autorizacionComprobanteAsync(string claveAccesoComprobante) {
        this.autorizacionComprobanteAsync(claveAccesoComprobante, null);
    }

    /// <remarks/>
    public void autorizacionComprobanteAsync(string claveAccesoComprobante, object userState) {
        if ((this.autorizacionComprobanteOperationCompleted == null)) {
            this.autorizacionComprobanteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnautorizacionComprobanteOperationCompleted);
        }
        this.InvokeAsync("autorizacionComprobante", new object[] {
                    claveAccesoComprobante}, this.autorizacionComprobanteOperationCompleted, userState);
    }

    private void OnautorizacionComprobanteOperationCompleted(object arg) {
        if ((this.autorizacionComprobanteCompleted != null)) {
            System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
            this.autorizacionComprobanteCompleted(this, new autorizacionComprobanteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
        }
    }

public new void CancelAsync(object userState) {
        base.CancelAsync(userState);
    }

¿Cual es la implementación adecuada para trabajar métodos asincronos en el cual uno espere la respuesta del otro para poder llamar al segundo web service?

A: podrias probar utilizando ContinueWith, para mas informaciones podes visitar el siguiente enclance
un ejemplo de como podria ser es :
public async Task<T> MyAsyncFun() {
    T value = await ...
    return value;
}

MyAsyncFun().ContinueWith(...

se que no es mucho pero espero que te sea de ayuda, exitos
EDIT
Me olvidava especificar que seria un metodo equivalente al promise.then() utilizado en Javascript


text:
Q: add pure virtual function I'm working on my final project for school. This is what my teacher wants me to do to the code I wrote but I don't really understand it. Can some one help me out?  This is pretty much how the rest of my code is - I didn't want to put the whole thing up on account of it's too long.
"You don't have any classes, just function calls. If you create a Scene class that is abstract, make the RunScene() function pure virtual. Then you can create subclasses of Scene for Intro, Scene1, Scene2, and Scene3 and put the scene code in the appropriate RunScene() function for each. That would go a long way towards improving your structure."
void nichole() {
    int choice4;
    do {
    cout << "\t ----------------------------" << endl;
    cout << "\t ----------------------------" << endl;
    cout << "\t\n i really like nichole the best" << endl;
    cout << "\t\n Nichole it is What is her interst?" << endl;
    cout << "\t\n idk" << endl;
    cout << "\t\n What do you mean you dont know?" << endl;
    cout << "\t\n ive never really talked to her" << endl;
    cout << "\t\n Well then how is she your favorite?" << endl;
    cout << "\t\n because shes the prettiest lol" << endl;
    cout << "\t\n Of course she is bry. can you tell me anything about her?" << endl;
    cout << "\t\n shes a cheerleader" << endl;
    cout << "\t\n Perfect I can work with that" << endl;
    cout << "\t\n thank you :)" << endl;
    cout << "\t\n tomrow you have to ask her out on a date" << endl;
    cout << "\t\n what no way man shes way to hott" << endl;
    cout << "\t\n Then get beat up by your cousins giant boy friend then" << endl;
    cout << "\t\n ahh fine what do i say to her exactly ive never asked" << endl;
    cout << "\t out on a date before" << endl;
    cout << "\t\n Choose response:" << endl;
    cout << "\t 1.Ask her to the theater" << endl;
    cout << "\t\ 2.Ask her for a cup of coffee" << endl;
    cout << "\t\ 3.Ask her to a football game" << endl;
    cin >> choice4;

        if ((choice4== 1) && (choice4 = 2)) {
            cout << "\t\n are you sure" << endl;
            cout << "\t\n Yes im sure" << endl;
            cout << "\t\n ok if you say so" << endl;
            loose();
        }
        else if (choice4 = 3) {
            cout << "\t\n dude your a genius" << endl;
            cout << "\t\n I Know get back to me tomorow and let me know how it goes" << endl;
            loose();
        }
        else {
            cout << "Invalid choice" << endl;
        }
    }
    while ((choice4 != 1) && (choice4 != 2) && (choice4 != 3));
    system("pause");
}


text:
Q: Synchronizing reading and writing with synchronous NamedPipes A Named Pipe Server is created with
hPipe = CreateNamedPipe( zPipePath,
                         PIPE_ACCESS_DUPLEX,
                         PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
                         PIPE_UNLIMITED_INSTANCES,
                         8192, 8192, NMPWAIT_USE_DEFAULT_WAIT, NULL)

Then we immediately call:
ConnectNamedPipe( hPipe, BYVAL %NULL )

Which blocks until the client connects.
Then we proceed directly to ReadFile( hPipe, ...
The problem is that it takes the Client takes a finite amount of time to prepare and write all the fcgi request parameters. This has usually not completed before the Pipe Server performs its ReadFile(). The Read file operation thus finds no data in the pipe and the process fails.
Is there a mechanism to tell when a Write() has occurred/finished after a client has connected to a NamedPipe?
If I had control of the Client process, I could use a common Mutex, but I don't, and I really do not want to get into I/O completion ports just to solve this problem!
I can of course use a simple timer to wait 60m/s or so which is usually plenty of time for the write to complete, but that is a horrible hack.

A: I'm not sure what language you're using - I don't recognize the expression like
PIPE_TYPE_BYTE OR %PIPE_WAIT OR %PIPE_READMODE_BYTE

but it looks like to me that the server's ReadFile() should block until data is written by the client.
One thing that doesn't look right (but shouldn't be hurting anything) is the use of NMPWAIT_USE_DEFAULT_WAIT - that value is intended for a client's use when calling WaitNamedPipe().
Could you see if these 2 C++ programs interact like you expect (ie., with the server blocking until the client writes something)?  I took these programs from the Jones/Ohlund book "Network Programming for Windows"  The server blocks in the ReadFile() call for me as expected:
 - server.cpp
// Server.cpp

#include <windows.h>
#include <stdio.h>

void main(void)
{
    HANDLE PipeHandle;
    DWORD BytesRead;
    CHAR buffer[256];
    if ((PipeHandle = CreateNamedPipe("\\\\.\\Pipe\\Jim",
        PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1,
        0, 0, 1000, NULL)) == INVALID_HANDLE_VALUE)
    {
        printf("CreateNamedPipe failed with error %d\n",
            GetLastError());
        return;
    }

    printf("Server is now running\n");

    if (ConnectNamedPipe(PipeHandle, NULL) == 0)
    {
        printf("ConnectNamedPipe failed with error %d\n",
            GetLastError());
        CloseHandle(PipeHandle);
        return;
    }

    if (ReadFile(PipeHandle, buffer, sizeof(buffer),
        &BytesRead,  NULL) <= 0)
    {
        printf("ReadFile failed with error %d\n", GetLastError());
        CloseHandle(PipeHandle);
        return;
    }

    printf("%.*s\n", BytesRead, buffer);

    if (DisconnectNamedPipe(PipeHandle) == 0)
    {
        printf("DisconnectNamedPipe failed with error %d\n",
            GetLastError());
        return;
    }

    CloseHandle(PipeHandle);
}

 - client.cpp
// Client.cpp

#include <windows.h>
#include <stdio.h>

#define PIPE_NAME "\\\\.\\Pipe\\jim"

void main(void)
{
    HANDLE PipeHandle;
    DWORD BytesWritten;

    if (WaitNamedPipe(PIPE_NAME, NMPWAIT_WAIT_FOREVER) == 0)
    {
        printf("WaitNamedPipe failed with error %d\n",
            GetLastError());
        return;
    }

    // Create the named pipe file handle
    if ((PipeHandle = CreateFile(PIPE_NAME,
        GENERIC_READ | GENERIC_WRITE, 0,
        (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        (HANDLE) NULL)) == INVALID_HANDLE_VALUE)
    {
        printf("CreateFile failed with error %d\n", GetLastError());
        return;
    }

    if (WriteFile(PipeHandle, "This is a test", 14, &BytesWritten,
        NULL) == 0)
    {
        printf("WriteFile failed with error %d\n", GetLastError());
        CloseHandle(PipeHandle);
        return;
    }

    printf("Wrote %d bytes", BytesWritten);

    CloseHandle(PipeHandle);
}


text:
Q: VB.NET - Salesforce POST Request returns 400 Bad Request Error NOTE: I've never written vb.net code before this. I've googled for a solution but did not find anything that worked.
I'm trying to get access token from Salesforce. Below code worked just yesterday. And I have no idea why it is not working today. I've tried adding content-type as application/x-www-form-urlencoded but it did not work either. When I use curl I'm able to get access token. Also I'm able to get access token using advanced rest client in google chrome. Any ideas why it is returning 400 Bad Request unknown error retry your request?
Imports System.Collections.Specialized
Imports System.Net
Imports System.Text

Module Module1

Sub Main()
    Dim clientId As String = "clientId"
    Dim clientSecret As String = "clientSecret"
    Dim redirectUri As String = "https://test.salesforce.com"
    Dim environment As String = "https://test.salesforce.com"
    Dim tokenUrl As String = ""
    Dim username As String = "username@salesforce.com"
    Dim password As String = "passwordtoken"
    Dim accessToken As String = ""
    Dim instanceUrl As String = ""

    Console.WriteLine("Getting a token")

    tokenUrl = environment + "/services/oauth2/token"
    Dim request As WebRequest = WebRequest.Create(tokenUrl)

    Dim values As NameValueCollection = New NameValueCollection()
    values.Add("grant_type", "password")
    values.Add("client_id", clientId)
    values.Add("client_secret", clientSecret)
    values.Add("redirect_uri", redirectUri)
    values.Add("username", username)
    values.Add("password", password)

    request.Method = "POST"

    Try
        Dim client = New WebClient()
        Dim responseBytes As Byte() = client.UploadValues(tokenUrl, "POST", values)
        Dim response As String = Encoding.UTF8.GetString(responseBytes)
        Console.WriteLine(response)
        Console.ReadKey()
    Catch ex As Exception
        Console.WriteLine(ex.Message)
        Console.WriteLine("Press any key to close")
        Console.ReadKey()
    End Try

End Sub

End Module

A: Well, appearently problem was about TLS version mismatch. All Salesforce sandboxes refuse TLS 1.0 connections. Our vb.net test code was using TLS 1.0 thus returning an error. It would be great if Salesforce would return better error code.
All I needed to do was add a line of code on top of the code block:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11


text:
Q: How can I put HTML table inside a dropdownbox? How can I put HTML table inside a dropdownbox? So, something like:
<select>

</select>

or

<select>
    <option>

    </option>
</select>

A: With pure CSS and HTML this is not possible.
javascript is probably your best way to approach this. Using Jquery will also help your javascript tremendously

A: You will need some custom self-made element if you want to do this. There are no other HTML tags allowed in an <option> tag.
Look for example at javascript libraries that are enhancing the standard select element, for instance Chosen. Maybe you can get a little inspiration there on how to implement your table-logic.

A: I think you can't do such that..you have to stimulate that.
You need to construct a div with multiple rows and add down arrow to the first row to make it look like dropdownlist.

A: What you want to achieve is not possible using the select-tag only. Within this tag only optgroup- and option-tags are allowed. See on w3c.org: "17.6 The SELECT, OPTGROUP, and OPTION elements".
When we go further to the option-tag, you'll see that the Content Model only allows text within this element. Again on w3c.org: "4.10.12 The option element"
So the only way to get this one going is to create an element that looks and behaves similar to the option-tag using other HTML elements.
In this demo on jsfiddle you can see an example, how a possible solution could look like. This one works without JavaScript, as the content is displayed on :hover. But of course you can change this to an click-event using JavaScript or jQuery.


text:
Q: SFDX: How to retrieve the active, but not the newest version of a Flow? While working on a Flow implementation, one can create multiple versions of it.
Let's say I have my first release ready, Flow's name is "TestFlow". I'm retrieving it with the following command: sfdx force:source:retrieve -m Flow:TestFlow
What I receive is obviously the metadata of the Flow:
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>53.0</apiVersion>
    <interviewLabel>TestFlow {!$Flow.CurrentDateTime}</interviewLabel>
    TestFlow
    <processMetadataValues>
        <name>BuilderType</name>
        <value>
            <stringValue>LightningFlowBuilder</stringValue>
        </value>
    </processMetadataValues>
    <processMetadataValues>
        <name>CanvasMode</name>
        <value>
            <stringValue>FREE_FORM_CANVAS</stringValue>
        </value>
    </processMetadataValues>
    <processMetadataValues>
        <name>OriginBuilderType</name>
        <value>
            <stringValue>LightningFlowBuilder</stringValue>
        </value>
    </processMetadataValues>
    <processType>Flow</processType>
    <screens>
        <name>Hello</name>
        Hello!
        <locationX>176</locationX>
        <locationY>224</locationY>
        <allowBack>true</allowBack>
        <allowFinish>true</allowFinish>
        <allowPause>true</allowPause>
        <showFooter>true</showFooter>
        <showHeader>true</showHeader>
    </screens>
    <start>
        <locationX>50</locationX>
        <locationY>50</locationY>
        <connector>
            <targetReference>Hello</targetReference>
        </connector>
    </start>
    <status>Active</status>
</Flow>

But it turned out that the implementation needs some changes. Created my second version. One sfdx force:source:retrieve -m Flow:TestFlow later and here it goes - additional <screen> added:
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>53.0</apiVersion>
    <interviewLabel>TestFlow {!$Flow.CurrentDateTime}</interviewLabel>
    TestFlow
    <processMetadataValues>
        <name>BuilderType</name>
        <value>
            <stringValue>LightningFlowBuilder</stringValue>
        </value>
    </processMetadataValues>
    <processMetadataValues>
        <name>CanvasMode</name>
        <value>
            <stringValue>FREE_FORM_CANVAS</stringValue>
        </value>
    </processMetadataValues>
    <processMetadataValues>
        <name>OriginBuilderType</name>
        <value>
            <stringValue>LightningFlowBuilder</stringValue>
        </value>
    </processMetadataValues>
    <processType>Flow</processType>
    <screens>
        <name>Hello</name>
        Hello!
        <locationX>176</locationX>
        <locationY>224</locationY>
        <allowBack>true</allowBack>
        <allowFinish>true</allowFinish>
        <allowPause>true</allowPause>
        <connector>
            <targetReference>Hello2</targetReference>
        </connector>
        <showFooter>true</showFooter>
        <showHeader>true</showHeader>
    </screens>
    <screens>
        <name>Hello2</name>
        Hello2!
        <locationX>177</locationX>
        <locationY>370</locationY>
        <allowBack>true</allowBack>
        <allowFinish>true</allowFinish>
        <allowPause>true</allowPause>
        <showFooter>true</showFooter>
        <showHeader>true</showHeader>
    </screens>
    <start>
        <locationX>50</locationX>
        <locationY>50</locationY>
        <connector>
            <targetReference>Hello</targetReference>
        </connector>
    </start>
    <status>Obsolete</status>
</Flow>

But! It turned out that I don't like the second version and I reactivated the first one. But what does the sfdx force:source:retrieve -m Flow:TestFlow command retrieve now? Still the second version. In fact, I need to delete it to be able to retrieve the previous version of the Flow again.
Is there any known workaround to this problem other than deleting unused Flow versions with the higher number than the active one?

A: Ok, found the solution. The Flow Metadata Documentation says:

To deploy or retrieve a version, you can specify the version number. For example, sampleFlow-3 specifies version 3 of the flow whose unique name is sampleFlow. If you don't specify a version number, the flow is the latest version.

Accordingly sfdx force:source:retrieve -m Flow:TestFlow-1 will retrieve the first version.
There's one thing to have in mind: If, for instance, version number '3' is the newest one, sfdx force:source:retrieve -m Flow:TestFlow-3 won't retrieve the TestFlow-3.flow-meta.xml, but TestFlow.flow-meta.xml (without the number).


text:
Q: Why i am getting this error"TypeError: store.getState is not a function. (In 'store.getState()', 'store.getState' is undefined)" import { createStore, combineReducers, applyMiddleware } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';
import thunk from 'redux-thunk';
import { profileReducer } from './Reducer';

const rootReducer = combineReducers({
  Reducer: profileReducer
});

const initialState = {};

const middleWare = [thunk];

export default () => {
  const store = createStore(rootReducer, initialState, applyMiddleware(...middleWare));

  return { store };
};

// Why i am getting this error "TypeError: store.getState is not a function. (In 'store.getState()', 'store.getState' is undefined)" Please help me i am new for redux

A: Inside app.js:
import store from 'your-file-name'
....
<Provider store={store()}>
....
</Provider>

I think you are directly using store there, instead call it like so: store()


text:
Q: css hover not executing I want an image to slightly grow in size when hovering over it. I know it's pretty simple, but I have looked for a good hour over other examples and cannot seem to figure out what I am missing. I appreciate the help. These images are saved to my computer.

     Scope
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<embed src="73797^alarmclock.mp3"; autostart="true"; loop="true"; hidden="true";/>

  Pulling the sheets into my body, I begin to sink back into the bed...
          uggh... my alarm clock... time to get up..

And here is the stylesheet.css
#grow:hover {
width: 100px;
height: 150px;
}

A: The inline style which declared in the HTML element has a higher priority than other css rules. So consider make your rules !important or move the inline style out.
Anyway, the !important rules are not recommended to use regularly. So you have better remove your inline styles and put them in .css files (or at least


text:
Q: How to differentiate between standard-inputs (via pipe and via prompt) in NodeJS? My goal: piping standard input from echo to a node file and asking for more input via a prompt. But I need to know which input is from the piping and which one is from the prompt.
The node file x.js looks like this:
const readline = require("readline");

let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("yes or no? (y/n)", answer => {
    console.log("-" + answer + "-");
    rl.close();
});

This one works (A prompt is shown, I enter "hello" and it is written to the console):
> node x.js
-hello-
But this does not work (There is no prompt. The piped string is just written to the console.):
> echo "abcdefgh" | node x.js
-abcdefgh-

How can I differentiate between those 2 kinds of standard input?

A: Actually, your problem is worse than you think - the problem is not differentiating between the piped and keyboard input, it's being able to accept both in the first place.
When you pipe data, you're basically saying "THIS is my input" - the application can no longer capture keyboard input, and in fact stdin is closed immediately after the piped data is read.
Are you completely boned? Well, it depends what you want to do. As per your example, if you want to make the user confirm that something is OK before accepting it, you could use command-line arguments:
var stdin = process.stdin;

if (stdin.setRawMode)
{
        // No data is being piped, so fall back to your existing code
        const readline = require("readline");

        let rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });

        rl.question("yes or no? (y/n)", answer =>
        {
            console.log("-" + answer + "-");
            rl.close();
        });
}
else
{
        // resume stdin in the parent process (node app won't quit all by itself

        stdin.resume();

        // on any data into stdin
        let receivedData = '';
        stdin.on('data', (data) => {
                receivedData += data;
        });
        stdin.on('end', () => {
                // Input will have a \n appended
                receivedData = receivedData.slice(0, -1);

                console.log('I received "' + receivedData + '".');
                const args = process.argv.slice(2);
                for(const arg of args)
                {
                        if (arg.toLowerCase() === '--accept')
                        {
                                console.log('Accepted the input!');
                                return;
                        }
                }
                console.log('Is this OK? If so, pass --accept as a parameter');
        });
}

And it works like this:
~ # echo "abcdefhiy" | node input.js

I received "abcdefhiy".
Is this OK? If so, pass --accept as a parameter

~ # echo "abcdefhiy" | node input.js --accept

I received "abcdefhiy".
Accepted the input!

A: The answer given by Tom Mettam is not quite  right.
It is true that process.stdin is occupied by the pipe input, meaning that you cannot also then use it for keyboard input.
But that doesn't mean you can't use keyboard input at all. You can use the underlying TTY readStream that process.stdin relies on.
The easiest way I've found to do this is by using the Node package ttys, which is very simple but saves me having to write the same code again.
I think you would use tty.stdin and tty.stdout as the arguments for your readline interface. You could then still use process arguments to access what was piped in.
I just posted an answer to my own question on a very similar problem, which you might find useful to read for implementation purposes.


text:
Q: Questions about Rings and properties of GCD Suppose I have a ring $R$ and suppose if I am given two elements $x, y$ that are relatively prime to each other, or their $gcd(x,y)=1$. from this, can it be concluded knowing nothing else about the ring $R$ that it contains the identity element and hence some or all elements contains its own inverse?
Thank you in dvance


text:
Q: problem in xml or in the code i have written? I am parsing xml from this url:
http://www.pfizerpro.com/irj/servlet/prt/portal/prtroot/com.wyeth.conventioncalendar.XMLFeed
The coming xml is like this...
<?xml version="1.0" encoding="UTF-8"?>
<calendar_items>
<item>
<id>355</id>
<title>ASH</title>
<description>52nd Annual American Society of Hematology Meeting & Exposition</description>
<link>http://www.hematology.org/Meetings/Annual-Meeting/</link>
<event_start>12/04/2010</event_start>
<event_end>12/07/2010</event_end>
<event_category_term>Oncology, Hematology</event_category_term>

<city>Orlando</city>
<state>FL</state>
</item>
<item>
<id>357</id>
<title>null</title>
<description>Society of Urologic Oncology 2010 Annual Meeting</description>
<link>http://www.societyofurologiconcology.org/meetings/default.aspx</link>
<event_start>12/08/2010</event_start>
<event_end>12/10/2010</event_end>

<event_category_term>Hematology, Genitourinary, HIV, Immunology, Infectious Disease, Inflammation, Irritable bowel syndrome, Metabolic & Endocrine, Musculoskeletal, Neuroscience, Nutrition & Vitamins, Oncology</event_category_term>
<city>Bethesda</city>
<state>MD</state>
</item>
</calendar_items>

I am using this code for parsing:--
NSURL *url = [[NSURL alloc]initWithString:@"http://www.pfizerpro.com/irj/servlet/prt/portal/prtroot/com.wyeth.conventioncalendar.XMLFeed"];

    xmlParser = [[NSXMLParser alloc]initWithContentsOfURL:url];

    [xmlParser setDelegate: self];

    BOOL success = [xmlParser parse];

    if(success) {

        [actView stopAnimating];
        table_view.hidden = NO;
        [table_view reloadData];
        NSLog(@"No Errors");
    }
    else {

        NSLog(@"Error Error Error!!!");
        [actView stopAnimating];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Application cannot get data from internet.Check your internet connection." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

It always gives error..Why  this happenes.Url is working and the correct xml format is coming..
i am parsing the xmlfrom similar url ..:- http://www.pfizerpro.com/irj/servlet/prt/portal/prtroot/com.wyeth.medpage.DMLFeed
Where is the problem?? in coming xml or in the code i have written..?

A: The literal &s in line 6 and 23 are errors in your XML file (and they are indeed present in the original XML feed as I have just checked). They need to be & instead.
In general, the following characters need to be masked in normal XML text:
<   <
>   >
&   &
"   "
'   '

A: Hi
just to add on to this. We will also face problems when you are forming xml containing any of the above tags. The request will not be processed if your request has the above tags. I have faced this in my project.
In such case also we need to replace the tags with its corresponding special characters while forming the xml and send the request.


text:
Q: Why do these two apparently identical objects have different class types? I have a class User, only have two fields: id, name
package test;

public class User {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Then in the Main class, I tried to initialize the User object with two different approach:
package test;

/**
 * @author lhuang
 */
public class Main {
    public static void main(String[] args) {
        User u = new User() {
            {
                setId(1l);
                setName("LHuang");
            }
        };

        System.out.println(u.getClass());

        User u2 = new User();
        u2.setId(1l);
        u2.setName("LHuang");
        System.out.println(u2.getClass());
    }
}

then I can get the output
class test.Main$1
class test.User

The interesting is why the u class is the inner class type of Main? But actually I still can use the u.getId() and u.getName() method.

A: You're creating an anonymous class that extends from User here:
User u = new User() { //<-- this open bracket defines a new class
        {
            setId(1l);
            setName("LHuang");
        }
    };

A: This
User u = new User() { // here's your derived class
        {             // here's the initialiser block
            setId(1l);
            setName("LHuang");
        }
    };

creates a new anonymous subclass of User (the outer set of braces), and then defines an initialiser block within that (the inner set of braces).
It's often advised to avoid the above construction for reasons of clarity (not many people are aware of how it works), and since you're creating an inner class, it'll have an implicit reference to the outer class. This can cause issues for garbage collection and serialisation.
Having said that, I would use the above sparingly (e.g. for setting up test collections in unit tests etc. due to its conciseness)


text:
Q: Mac App Sandbox: can't open folder in sandbox container with NSWorkspace I want to open a folder in sandbox container with Finder, but can't get it working. This is my code.
- (IBAction)buttonClicked:(id)sender
{
    NSString *folder = [NSHomeDirectory() stringByAppendingPathComponent:@"Backup"];
    [[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:NULL];
    [[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:folder]];
}

And I got this error message in Console.
CoreServicesUIAgent: Quarantine resolution refused to pid 4288 because it is not allowed to read /Users/username/Library/Containers/com.domain.bundle/Data/Backup

The folder is in sandbox container, it was created by my sandboxed app and I can write files into it, so I think I should have read permission. If I created this folder manually with Finder, then I can open it successfully using NSWorkspace. It's so strange.
What's wrong with my code or is there another way to open folder with Finder in Mac App Sandbox?


text:
Q: Homogeneous gravitational field and the geodesic deviation In General Relativity (GR), we have the geodesic deviation equation (GDE)
$$\tag{1}\frac{D^2\xi^{\alpha}}{d\tau^2}=R^{\alpha}_{\beta\gamma\delta}\frac{dx^{\beta}}{d\tau}\xi^{\gamma}\frac{dx^{\delta}}{d\tau}, $$
see e.g. Wikipedia or MTW.
Visually, this deviation can be imagined, to observe the motion of two test particles in the presence of a spherically symmetric mass.In the case of a homogeneous gravitational field, such as a geodesic deviation should not be, because acceleration due to gravity equal at every point.
Clearly, such a field can be realized in a uniformly accelerated frame of reference. In this case, all components of the curvature tensor will be zero, and the equation (1) correctly states that the deviation will not be surviving.
But if a homogeneous field will be created by infinite homogeneous flat layer, in this case, the components of the curvature tensor are non-zero, then by (1) will be a deviation. It turns out that such fields, even though they are homogeneous, can be discerned. I think this situation is paradoxical. Is there an explanation?

A: The curvature tensor is the same in all coordinate systems.  If you have, say, the Schwarzchild metric, $R_{abc}^{d}$ will transform with the coordinate system and be nonzero in all reference frames.  In particular $R_{abcd}R^{abcd}$ will take on the same value at every point no matter what reference frame you choose, accelerated, freely falling, or no.
It is significant precisely because it is the simplest possible object that can't be set exactly equal to Minkowski space at a point by a choice of coordinates (unlike the metric tensor and the Christoffel symbols), so your paradox isn't a paradox at all.


text:
Q: MSExcel: Is it possible to make an adaptive formula through reference? Example:

Desired result:

(Please note that the red values in the first image above are made red to signify that they are actually functions, imagine adding an "=" sign before them.)
I have number values from the J column and the K column. In the L column next to them, I have referenced a nearby cell N2. N2 contains my formula J2+K2 which obviously adds the values of cells J2 and K2. However, it will not work on J3 and K3 because the formula is still J2+K2. Is there a way for the formula to adapt to it? If not, any suggestion about making this work easier would help! Thank you.

A: Put the formula =J2+K2 in cell L2. Then copy that cell, select cells L3:L7, and paste.
Alternatively, you can use the fill handle to drag the formula in L2 down to the cells below. The references will adjust automatically.
You don't need anything in N2.


text:
Q: Remove duplicate records from a csv file considering single column I have a file with records in such a type-
,laac_repo,cntrylist,idlist,domlist,typelist
1,22DE17,BA,S6CD6728,24JA13,6A
2,12FE18,AA,S6FD7688,25DA15,7D
3,22DE17,BA,S6CD6728,24JA13,6A
4,12FE18,AA,S6FD7688,25DA15,7D

I want to remove duplicate records considering 4th column which has "S6CD6728" these type of record and skipping first row which is
",laac_repo,cntrylist,idlist,domlist,type list"

I have tried
awk '{a[$4]++}!(a[$4]-1)' filename

And also tried
awk 'FNR > 1 {a[$4]++}!(a[$4]-1)' filename

The expected output is-
,laac_repo,cntrylist,idlist,domlist,typelist
1,22DE17,BA,S6CD6728,24JA13,6A
2,12FE18,AA,S6FD7688,25DA15,7D

P.S file has more than 10 million records, please suggest solution w.r.t that.( If any script given much appreciated, instead of single command).

A: What about this:
awk -F, 'FNR>1 && \!seen[$4]++' filename

1,22DE17,BA,S6CD6728,24JA13,6A
2,12FE18,AA,S6FD7688,25DA15,7D

awk -F, '\!seen[$4]++' filename

,laac_repo,cntrylist,idlist,domlist,typelist
1,22DE17,BA,S6CD6728,24JA13,6A
2,12FE18,AA,S6FD7688,25DA15,7D


text:
Q: "enter license" still exists after Sublime Text 3 deletion I installed ST3 but I deleted it using this: how to uninstall sublime text3 completely?. I didn't know it needed a license key. Then I installed ST2 but I couldn't open it because a dialog from ST3 asking for the license key still pops up (and the installation name is ¨Enter license¨). I tried to delete the ST2 "enter license" program (I don't know what it is) but it still exists (icon changed to default)
installed ST3 using:
sudo add-apt-repository ppa:webupd8team/sublime-text-3
sudo apt-get update
sudo apt-get install sublime-text-installer

and deleted using:
sudo apt-get purge sublime-text-installer

installed ST2 using:
sudo add-apt-repository ppa:webupd8team/sublime-text-2
sudo apt-get update
sudo apt-get install sublime-text

Here is the window that opens instead of ST2:

A: This can (also) be caused by having added the development branch to your apt sources by mistake, instead of the stable releases.
make sure that
/etc/apt/sources.list.d/sublime-text.list

contains
deb https://download.sublimetext.com/ apt/stable/

and not
deb https://download.sublimetext.com/ apt/dev/

The development branch is only available to licensed users as stated on their wobwob:
https://www.sublimetext.com/docs/3/linux_repositories.html
"Builds listed in the dev channel are only available to licensed users. Users who are evaluating Sublime Text before purchase will need to use the stable channel."

A: This update fixed this problem for me:
sudo add-apt-repository ppa:webupd8team/sublime-text-3
sudo apt-get update
sudo apt-get install sublime-text-installer
sudo apt-get install sublime-text

source: How to update Sublime Text Editor


text:
Q: Comparing date in Access SQL query I'm having trouble with Access sql query. Im new to this so bieng a rookie its difficult to figure out the syntax. below is my query.
SELECT *
FROM BookingMaster WHERE JourneyDate = #01/08/2012#;

below is the respective table data:
BookingID   BookingDate    JourneyDate   CustomerName   TelephoneNo  Address
5            01-08-2012     01-08-2012         roshan         78889     hjgj

the above query listed returns 0 results even though data exist for 01/08/2012 journey date.
Can anyone please help me out.

A: Unless you are working in a US locale, it is best to use a year, month, day format for dates:
SELECT *
FROM BookingMaster where JourneyDate = #2012/08/01#;

A: try this..
SELECT * FROM BookingMaster where (JourneyDate >= #01/08/2012#) and (JourneyDate < #01/09/2012#);


text:
Q: Convention for reporting 95% confidence interval for 100% success proportion In a clinical trial, if a successful endpoint is achieved by the entire population, what is the convention for reporting the exact confidence interval?
Eg, if 50/50 achieved success would it be most suitable to report "100%, 95%CI 92.9-100.0%" Or some other convention?


text:
Q: Setting body height to 100% I need to have the body of all my webpages (except homepage) located on http://www.zorglegal.nl to the same height (100% browser height), so the brown bar on the right is stretched full screen from top to bottom. How can I best achieve this?
html{
    height: 100%;
}

body{
    min-height: 100%;
}

doesn't work. I also tried to set a class for the content element and tried to set it to 100% height but that doesn't work either. How can i do this?
The brown bar is a png image and is set as a background image for a fullwidth container. So if that container is 100% high, it should work. But how?

A: You can use viewport height.
height: 100vh

This means that the div or whatever is as high as the browser window.

A: html, body{
    margin: 0;
    padding: 0;

    min-width: 100%;
    width: 100%;
    max-width: 100%;

    min-height: 100%;
    height: 100%;
    max-height: 100%;
}

This Css will help you to set height 100% for every page.

A: Body Height to 100%
html, body {
    width: 100%;
    height: 100%;
}

A: Try to achieve using javascript:
$(window).bind('resize', yourclassname);

In yourclassname also use yourID, give it to parent div.

A: You can also use table property here, for cross-browser support.
    html {
    width:100%;
    height: 100%;
    display: table;
    }

    body {
        width:100%;
        display:table-cell;
    }

    html, body {
        margin: 0px;
        padding: 0px;
    }


text:
Q: How to load the progressbar at the same time my method is running I have a long running method, so I created a progress bar to show what percentage my method was to completing, but I am having difficulty figuring out how to do this ,syncing  my progress bar with my method => excelHelper.InsertNewRows();.
public void ButtonSubmit_Click(object sender, EventArgs e)
{
    if (isProcessRunning)
    {
        MessageBox.Show("A Process is aleady running");
        return;
    }

    Thread backgroundThread = new Thread(
        new ThreadStart(() =>
        {
            for (int n = 0; n < 100; n++)
            {
                isProcessRunning = true;
                Thread.Sleep(50);
                progressBar1.Invoke(
                    new Action(() =>
                    {
                        progressBar1.Value = n;
                        label3.Text = ("Progress: " + n + "%");
                    }
                 ));
            }
            MessageBox.Show("Thread completed!");
            progressBar1.Invoke(
                new Action(() =>
                {
                    progressBar1.Value = 0;
                }
                ));
            isProcessRunning = false;
        }
        ));
    backgroundThread.Start();
    excelHelper.InsertNewRows();
    var folder = TextOutputFile.Text + @"\" +
    DateTime.Now.ToString("yyyy_MM_dd_") + "SA_Analysis_Report.xlsx";
    excelHelper.Save(folder);
    MessageBox.Show("File has been added to file");
}

A: IMO your problem is, that you dont have any communication between the working thread excelHelper.InsertNewRows(); and your progressbar thread. Both threads are running without any information about the other thread and their progress.
You could rewrite the background thread, so its capable of taking the percentage as a parameter, which is shown in the moment you call the thread.
E.g. Pseudo Code:
public void progressbarThread(int percentage)
{
    // Invoke the percentage to your progressbar, then terminate this thread
}

public void InsertNewRows()
{
    // Do something...
    // 10%
    Thread backgroundThread = new Thread(new ThreadStart(() => progressBarThread(10)));
    backgroundThread.Start();
    // Do something...
    // 50%
    Thread backgroundThread = new Thread(new ThreadStart(() => progressBarThread(50)));
    backgroundThread.Start();
    // etc. etc.
}

Update:
I've found this on my own research how to build a smooth loadingbar with an extra form, it maybe useful: Form in an extra Thread

A: I use this form class: -

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Yournamespace
{
    public partial class frmProgressBar : Form
    {
        public Action Worker { get; set; }

        System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();

        public const long MINIMUM_DISPLAY_TIME = 300;    // Minimum time to display the progress bar is 300 milliseconds

        public frmProgressBar(Action worker)
        {
            InitializeComponent();

            if(worker == null)
            {
                throw new ArgumentNullException();
            }

            Worker = worker;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        protected override void OnClosed(EventArgs e)
        {
            // the code that you want to measure comes here
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            if (elapsedMs < MINIMUM_DISPLAY_TIME) //ensure progress bar is displayed for at least 100 milliseconds, otherwise it just looks like the parent main form glitches.
            {
                long lDelay = MINIMUM_DISPLAY_TIME - elapsedMs;

                Thread.Sleep((int)lDelay);
            }
        }
    }
}

The form design looks like this : -

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/n4XqU.jpg

And I call it like this: -

            using (Yournamespace.frmProgressBar frm = new Yournamespace.frmProgressBar(Yourprocess))
            {
                frm.ShowDialog(this);
            }

Yourprocess is the code that you want to execute that is causing the delay.

The main problem with this implementation is Yourprocess cannot return a value or take parameters. I am sure the code can be changed to accomodate this but I did not have time so I use globals to pass in data and to see results(shame on me).

This is not my code, although I have modified it, came from a you tube video - Wait Form Dialog.

Edit. I forgot to say that I set my form to 100% opacity so the progress bar seems to float above my winform whenever I use it.

A: There are definitely resources to help you figure this out, however I spent like 2 days figuring it out so I'm going to help you out here and save you the headache. The progress bar itself is under the main UI thread (like any objects in your form) and needs to be handled by the main thread. Whatever you are trying to do on the side can be handled by a thread like this
    String a, b;
    a = txtUsername.Text;
    b = txtPassword.Password;
    Thread Login = new Thread(() => CompleteLogin(a, b));
    InversePbVisibility();
    Login.Start();

The InversePbVisibility() method would be replaced by whatever you are doing to make the progress bar visible to the user. A quick side note, any methods that are run on your declared thread can only pass variables and not anything already under the control of the main thread.


text:
Q: Nested NSUserDefaults arrays read/write I have the following structure of data:
- Cards
 -- Item 0
  --- Name: Card Name
  --- Number: Card Number
  --- Type: Card Type
 -- Item 1
  --- Name: Card Name
  --- Number: Card Number
  --- Type: Card Type
...

The user can add as many cards as he wants, so Name, Number and Type are user defined.
1st question is, how can I write this data to a NSUserDefauls (nested like this)
2nd Question is, and how can I retrieve this data and show the name of each card in a table view. (I already have the tableview set and working, so it's a matter of getting the data from the NSUserDefaults).
Any code example is well appreciated.
Thanks

A: To create this structure is quite simple, you create a dictionary that has an array value for your key `Cards'. Example below..
NSMutableDictionary *cards = [NSMutableDictionary dictionary];
NSMutableArray *cardArray = [NSMutableArray array];

NSMutableDictionary *item = [NSMutableDictionary dictionary];
[item setValue:@"Card Name" forKey:@"Name"];
[item setValue:@"Card Number" forKey:@"Number"];
[item setValue:@"Card Type" forKey:@"Type"];

[cardArray addObject:item];
[cards setValue:cardArray forKey:@"Cards"];

[[NSUserDefaults standardUserDefaults] setValue:cards forKey:@"user_cards"];
[[NSUserDefaults standardUserDefaults] synchronize];

In order to retrieve your cards, you would do something like..Assuming self.cards is an NSMutableArray ivar..
NSMutableDictionary *stored = [[NSUserDefaults standardUserDefaults] valueForKey:@"user_cards"];

self.cards = [stored valueForKey:@"Cards"];

Your tableview should use cards ivar to populate your data, like below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    ......

    //Now we populate each row of the cell with each `card` Name.
  cell.textLabel.text = [[self.cards objectAtIndex:[indexPath row]] valueForKey:@"Name"];

   .....
}

To resave any newly added cards to your stored dictionary you would do something like this..
NSMutableDictionary *newCard = [NSMutableDictionary dictionary];
[newCard setValue:@"Card Name" forKey:@"Name"];
[newCard setValue:@"Card Number" forKey:@"Number"];
[newCard setValue:@"Card Type" forKey:@"Type"];

[self.cards addObject:newCard];

[[NSUserDefaults standardUserDefaults] valueForKey:@"user_cards"] setValue:self.cards forKey:@"Cards"];
[[NSUserDefaults standardUserDefaults] synchronize];

If this has helped with your questions, please accept it as an answer.

A: save
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSArray
[prefs setObject:myArray forKey:@"keyToLookupArray"];

[prefs synchronize];

Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSArray
NSArray *myArray= [prefs stringForKey:@"keyToLookupArray"];


text:
Q: Can't initialize VM using vagrant I can't initialize vagrant typing vagrant up on cmd (Windows 10), this is the logs
`
C:\xampp\apache\ecomex\ecomex>vagrant up
Bringing machine 'ecomex' up with 'virtualbox' provider...
==> ecomex: Loading Berkshelf datafile...
==> ecomex: Sharing cookbooks with VM
==> ecomex: Checking if box 'grtjn/centos-7.0' is up to date...
==> ecomex: Clearing any previously set forwarded ports...
==> ecomex: Updating Vagrant's Berkshelf...
==> ecomex: Resolving cookbook dependencies...
==> ecomex: Fetching 'ecomex' from source at cookbooks/ecomex
==> ecomex: Using apt (3.0.0)
==> ecomex: Using ark (1.0.1)
==> ecomex: Using build-essential (3.2.0)
==> ecomex: Using chef_handler (1.3.0)
==> ecomex: Using ecomex (0.0.1) from source at cookbooks/ecomex
==> ecomex: Using nodejs (2.2.0)
==> ecomex: Using redisio (2.3.0)
==> ecomex: Using seven_zip (2.0.0)
==> ecomex: Using ulimit (0.3.3)
==> ecomex: Using windows (1.39.2)
==> ecomex: Using yum (3.10.0)
==> ecomex: Using yum-epel (0.6.6)
==> ecomex: Vendoring apt (3.0.0) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/apt
==> ecomex: Vendoring ark (1.0.1) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/ark
==> ecomex: Vendoring build-essential (3.2.0) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/build-essential
==> ecomex: Vendoring chef_handler (1.3.0) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/chef_handler
==> ecomex: Vendoring ecomex (0.0.1) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/ecomex
==> ecomex: Vendoring nodejs (2.2.0) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/nodejs
==> ecomex: Vendoring redisio (2.3.0) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/redisio
==> ecomex: Vendoring seven_zip (2.0.0) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/seven_zip
==> ecomex: Vendoring ulimit (0.3.3) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/ulimit
==> ecomex: Vendoring windows (1.39.2) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/windows
==> ecomex: Vendoring yum (3.10.0) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/yum
==> ecomex: Vendoring yum-epel (0.6.6) to C:/Users/EruAizen/.berkshelf/vagrant-berkshelf/shelves/berkshelf20160329-4476-mlo9s9-ecomex/yum-epel
==> ecomex: Clearing any previously set network interfaces...
==> ecomex: Preparing network interfaces based on configuration...
    ecomex: Adapter 1: nat
==> ecomex: Forwarding ports...
    ecomex: 3000 (guest) => 9898 (host) (adapter 1)
==> ecomex: Booting VM...
==> ecomex: Waiting for machine to boot. This may take a few minutes...
    ecomex: SSH address: 127.0.0.1:22
    ecomex: SSH username: vagrant
    ecomex: SSH auth method: private key

`
afther a few minutes, it trows the next error message

Timed out while waiting for the machine to boot. This means that
  Vagrant was unable to communicate with the guest machine within
  the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
  Vagrant had when attempting to connect to the machine. These errors
  are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
  working and you're able to connect to the machine. It is a common
  problem that networking isn't setup properly in these boxes.
  Verify that authentication configurations are also setup properly,
  as well.
If the box appears to be booting properly, you may want to increase
  the timeout ("config.vm.boot_timeout") value.

my vagrant file
# -*- mode: ruby -*-
# vi: set ft=ruby
VM = 'ecomex'

Vagrant.configure(2) do |config|
  #selecting Cent OS 7.0
  config.vm.box = 'grtjn/centos-7.0'
  config.vbguest.auto_update = false
  # proxy network: Node: 3000 & Apache: 9898
  config.vm.network :forwarded_port, guest: 3000, host:9898, auto_correct: true
  config.vm.network :forwarded_port, guest: 22, host: 2222, id: "ssh", disabled: "true"

  #VirtualBox setup
  config.vm.define VM
  config.vm.provider :virtualbox do |vb|
    vb.name = VM
  end

  #Fixing issue: stdin is not tty
  ssh_fix = 'bash -c "BASH_ENV=/etc/profile exec bash"'
  config.ssh.shell = ssh_fix unless ARGV[0] == 'ssh'

  #Adding omnibus & bershelf prugins
  config.omnibus.chef_version = :latest
  config.berkshelf.enabled = true
  config.berkshelf.berksfile_path = './Berksfile'

  #Chef provisioning
  config.vm.provision :chef_solo do |chef|
    chef.add_recipe VM
    chef.custom_config_path = 'Vagrantfile.chef'
    chef.json = {
      :nodejs => {
        :install_method => 'package',
        :npm => '2.13.4'
      }
    }
  end

  #start node app
  config.vm.provision :shell do |s|
    s.privileged = false
    s.inline = 'cd /vagrant && pm2 start pm2.json'
  end
end

I visited this thread Vagrant stuck connection timeout retrying and added the line in my vagrant file to see what was happend
config.vm.provider :virtualbox do |vb|
  vb.gui = true
end

after that, screen shows request login and this is where i got stuck, because after type 'vagrant' as login and password nothing happends.
NOTES:

*

*Im using Windows 10

*Windows Firewall is shutted down

*VM Network is set on NAT

Sorry for my spelling, im not good enough in english.
thanks for help!

A: There are a few interesting things in your post:

*

*Based on your directory path (C:\xampp\apache\ecomex\ecomex) from where you vagrant uped, it would seem you are running xampp. Running vagrant from inside an apache/xampp server config is an interesting idea to say the least. It also makes me think something about xampp may be interfering (is there anything mucking with port 22 or 2222?).

*Can you boot and ssh into a less customized vagrant box? The one you have provided has a bunch of moving parts, many of which could be to blame.

*Are you running from an elevated command prompt? (Run As Administrator).

*Try commenting out (adding # to the beginning) the following lines, as they are mucking with ssh:
ssh_fix = 'bash -c "BASH_ENV=/etc/profile exec bash"'
config.ssh.shell = ssh_fix unless ARGV[0] == 'ssh'

so that they become
#ssh_fix = 'bash -c "BASH_ENV=/etc/profile exec bash"'
#config.ssh.shell = ssh_fix unless ARGV[0] == 'ssh'

*Post the results of vagrant up --debug (which can also be output to a file, via vagrant up --debug > vagrantlog.log).


text:
Q: Missing charset in phpmyadmin. What to do? A friend asked me to add a php dynamic panel in his site whitch is generated by sum web based site generator. I am bulgarian and we use cp1251 edncoding whitch is Cyrillic Windows. But the site is generated with iso-8859-5 charset and is inpossible to convert it. If I use different cyr charset there are only question marks displayed in the page. And this encoding iso-8859-5 does not exsits in phpmyadmin. Give me please some advise what to do. Thank you very much.

A: I've manage somhow to change it to utf-8 and it's fine now


text:
Q: how check if GetElementsByTagName not match i have a script to load/read the xml to 15 texboxes with InnerText
here is the code.
doc = new XmlDocument();
doc.Load(dlgOpenFile.FileName);
root = doc.DocumentElement;
txt1.Text = root.GetElementsByTagName("Seksi")[0].InnerText;
txt2.Text = root.GetElementsByTagName("Kota")[0].InnerText;
txt3.Text = root.GetElementsByTagName("Tanggal")[0].InnerText;
txt4.Text = root.GetElementsByTagName("NoIntelejen")[0].InnerText;
txt5.Text = root.GetElementsByTagName("Peta")[0].InnerText;
txt6.Text = root.GetElementsByTagName("Kedar")[0].InnerText;
txt7.Text = root.GetElementsByTagName("Tahun")[0].InnerText;
txt8.Text = root.GetElementsByTagName("Lembar")[0].InnerText;
txt9.Text = root.GetElementsByTagName("TugasPokok")[0].InnerText;
txt10.Text = root.GetElementsByTagName("Intelejen")[0].InnerText;
txt11.Text = root.GetElementsByTagName("Taktis")[0].InnerText;
txt12.Text = root.GetElementsByTagName("Personil")[0].InnerText;
txt13.Text = root.GetElementsByTagName("Logistik")[0].InnerText;
txt14.Text = root.GetElementsByTagName("Teritorial")[0].InnerText;
txt15.Text = root.GetElementsByTagName("Perhubungan")[0].InnerText;

when i load a correct xml, the xml success load to text box, but when the GetElementsByTagName is not match, show error "Object reference not set to an instance of an object."
in row
txt10.Text = root.GetElementsByTagName("Intelejen")[0].InnerText;

how to check if GetElementsByTagName not match , so when the elements not match, the app show message and cancel load?

A: The GetElementsByTagName method will return a node collection of all matches elements, if no matches are found then it will return an empty collection. You can test if the collection is empty by using the Count property. This is what you need:
var matches = root.GetElementsByTagName("Seksi");
if(matches.Count > 0)
    txt1.Text = matches[0].InnerText;

As you are doing this quite a few times it would be useful to create a helper function. Something like so:
public void SetTextForTag(XmlElement root, TextBox tb, string tag)
{
    var matches = root.GetElementsByTagName(tag);
    if(matches.Count > 0)
        tb.Text = matches[0].InnerText;
}

which you can use like this, for example:
SetTextForTag(root, txt1, "Seksi");
SetTextForTag(root, txt2, "Kota");
//and so on...

A: Why not use a ternary operator like:
   txt1.Text = root.GetElementsByTagName("Seksi").Count < 1 ? "" : root.GetElementsByTagName("Seksi")[0].InnerText;

A: You could DRY up your code some by use of this extension method
public static bool TryGetInnerText(this XmlElement root, string childName, out string text)
    {
         var children = root.GetElementsByTagName(childName);
         if(children.Count > 0){
               text = children[0].InnerText;
               return true;
         }
         text = null;
         return false;
    }

then you can call it like this:
 if(!root.TryGetInnerText("Seksi", out txt1.Text)){
      //notify the uesr that the Seksi wasn't found
 }

and that will handle the checks for you as well

A: keep null checks in mind for non-existent elements, you can't assign what isn't there:
txt1.Text = (root.GetElementsByTagName("Seksi")[0] != null)
   ? root.GetElementsByTagName("Seksi")[0].InnerText
   : String.Empty;

A: var elements = root.Elements("Seksi");
        if (elements.Any())
        {
            string txt = elements.First().Value;
        }

A: Try this:
var element = root.GetElementsByTagName("Intelejen")[0];
if (element != null)
    txt10.Text = element.InnerText

Explanation: root.GetElementsByTagName("Intelejen")[0] returns null if no element is found. That is why InnerText throws a null exception


text:
Q: updating a progress bar while writing an Excel file using Apache POI Given code that writes a substential amount of data to an excel file using Apache POI:
var workbook = new SXSSFWorkbook()
addSubstentialAmountOfDataToWorkbook(workbook)
workbook.write(outputStream) // might take a few minutes and need to update the progress bar
workbook.close()

and a progress bar that can be updated with progressBar.add(10) // add 10% to the progress
How can one update a progress bar while writing a very big Excel file using Apache POI?
My initial thoughts were to look at the size of the xlsx file while it is being written in some asynchronous way but it seem to add a lot of clutter to the code.
Is there a better way to do it?

A: If the workbook writing use always the same amout of time you might do it. Otherwise, I would suggest a simple spinner (for example here) instead of a progressbar. Because you don't know how long it will take to generate your file. You can't determinate what is the "100%" and how long to achieve it.


text:
Q: Tomcat server remote redeployement We have a web app using Apache Shiro for security and deployed in a Tomcat 7 server, and an administration application in java swing. One of the purposes of the administration application is to manage urls access rights for users in the web application. When the rights are modified, the web app need to be redeployed.
We are already using JMX to start/stop/reload the web app in Tomcat, but is there a way to redeploy the web app each time the shiro.ini file is updated?

A: The place where the shiro.ini file was apparently wrong (it was in the classpath root folder). We've just tried to move it to WEB-INF folder, and now, we don't need manual redeployement anymore. Just a reload of the web app eventually, and it is possible to do it with JMX.
Thank you dinesh707, you're comment helped us in some way.


text:
Q: PyQt4 / QTableView : How to change the style of selection rectangle? I am trying to change the style of selection rectangle in QTableView.
I have tried with stylesheet; but it allowed me to set only the selection background color as shown in Figure 1. I wanted the selection rectangle as shown in Figure 2. (No Fill Color + Thick  black border)
Any idea?
def TableUi(self, Dialog):
    Dialog.setObjectName("Dialog")
    Dialog.resize(343, 179)

    self.tableWidget = QtGui.QTableWidget(Dialog)
    self.tableWidget.setGeometry(QtCore.QRect(10, 10, 321, 121))
    self.tableWidget.setStyleSheet("selection-color: rgb(255, 0, 127);\n"
    "selection-background-color: rgb(85, 255, 127);")
    self.tableWidget.setRowCount(3)
    self.tableWidget.setColumnCount(3)

Full Code Sample: https://justpaste.it/5fe3r

A: To style the selected cell you can target QTableView::item::selected in your stylesheet.
self.tableWidget.setStyleSheet('''
    QTableView::item::selected {
      border: 5px solid black;
    }
''')


text:
Q: Installing opencv for Python I have both Python 3.7 and 2.7 installed currently, and have a simple image processing script that calls for opencv. However, I keep getting the "module not found" error. I've tried using pip install, pip3 install, and installing the Windows executable from the opencv website, none of which have fixed the problem. The script won't run from either 3.7 or 2.7! I'm currently trying to use Visual Studio Code on a Windows 10 Surface computer.
Other threads seem to suggest that I need to update the Python registry/pointer or something to reflect the actual install location, but I can't seem to find how to do this. Or can I simply copy/paste the directory or files into Python directly? (Python 3.7 is preferred, or for both if possible!)
Edit: After uninstalling and reinstalling both Python 2.7 and 3.7, I think I figured out what the problem was! I was still having issues upon reinstall, so I tried rolling back a version to 3.6. During this installation, I noticed that even pip wasn't working anymore. It was at this point I realized that somehow my installation of Python was done with administrative privileges by default. Even though my account is the only one running on my personal computer, I still had to install pip with elevated privileges to get it to work. Now it seems like OpenCV and other modules are working!


text:
Q: Define a new addition and multiplication and check the equality Consider the set $V$ = {$(x,y): x,y \in \mathbb{R}$}.
Define a new addition and multiplication on $V$ by $(x,y) + (a,b) = (x+a-2,y+b)$ and $k(x,y) = (kx-2k-2x+6,ky)$.
Check whether the following equality holds for all $u,v \in V$ and all $k \in \mathbb{R}$:
$$k(u+v)=ku+kv$$

A: We would like to check if the equation
$$
k(u+v) = ku + kv
$$
is true for all $u,v \in V$ and all $k \in \mathbb{R}$.
Let me give you a blueprint for the solution of this problem:
Let $k$ be an arbitrary real number and $u,v$ be arbitrary elements in $V$.

*

*Since $u,v \in V$, there are real numbers $a,b,x,y \in \mathbb{R}$ such that
$$
u = (x,y) \quad \text{and} \quad v =(a,b).
$$

*Compute $u+v$ by using your newly defined addition.

*Compute $k(u+v)$ by using your newly defined multiplication.

*Compute $ku$ and $kv$ by using your newly defined multiplication.

*Compute $ku + kv$ by using your newly defined addition.

*Compare your results from 3. and 5. by comparing the entries of the vectors. This shows whether your equality is true or not.

*

*If the equality seems to be not true, try to find explicit $a,b,x,y$, so that the equality does not hold.

If you need further help, then you can let me know and I try to give you more hints.