text:
Q: How do I disable a program without uninstalling it in Windows 10? Is there a way that I can disable a program without uninstalling it? Essentially, the program would no longer be listed in programs and the program itself wouldn't show up in search, but the physical files themselves wouldn't be removed. Attempting to launch the program while it's disabled would require it to be re-enabled. Re-enabling the program would be significantly faster than reinstalling and simply be a matter of allowing it to show up in programs and search. Is this a thing in Windows? Is this possible to do—with third party programs or otherwise?

A: I don't know if this is a solution that works the way you want it, but you can try it out and see for yourself. Also, I don't think it'll work 100% the way you want it
Normally all programs/applications will be shown if you start typing the name in the start menu. If you right-click on them, you can select "Go to file location". This will send you to StartMenu\Programs directory. If you move the required program away from this folder (to the desktop for example), it will no longer appear in your start menu when searching it in the start menu. You can move it back in if you want to reuse it.
Optimally, you can write a script (I presume you are familiar with this) that automatically copies the program that's linked in the start menu to a seperate folder and back.

A: Easy - use the windows registry like that:
Press Win+R and type regedit and hit Enter to open the Registry Editor.
Now navigate to the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

If you are looking for an application which is 32-bit and your system is 64 bit use the following instead:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

Now, inside this folder, find the folder for the application that you want to hide. Right-click on the application folder, select New and then click on DWORD. Name the new value SystemComponent and give it a value of 1.

A: There are three methods I can think of off the top of my head on how this can be done, all permissions related.  You can either remove a user or group's read access to a folder and/or files in the File Permissions dialog.  Alternatively, you can remove the execute permission in the advanced permissions of the aforementioned dialog.
With the former method, the affected users will not be able to read the files or folders contents, thereby making it unable to be executed.  Be aware, all files with this change cannot be read at all, meaning a text file in the folder, or a configuration file, will not be able to opened or edited.  You can limit the permission change to just the executable.
With the latter method, it is more targeted and only the executable would be affected and unable to run.
Lastly, you could mark the files/folders hidden.  This wouldnt make them non-executable, but unable to be seen without some snooping.
Of course, you would manually remove the Start Menu entries manually.
I wont go in to much detail on how to do it, as there are countless guides you can Google on how to do this.  Here is one example.

A: How to Block (or Allow) Certain Applications for Users in Windows
If you'd like to limit what apps a user can run on a PC, Windows gives you two options. You can block the apps you don't want a user to run, or you can restrict them to running only specific apps. Here's how to do it.
RELATED: How to Use System Restore in Windows 7, 8, and 10
NOTE: Be absolutely sure that you are making changes to a user account you actually want to restrict, and that you always have an unrestricted administrative account available to undo those changes. This is especially true if you are restricting users to a specific set of apps, as those users will lose access even to tools like Registry Editor and Local Group Policy Editor. If you do accidentally apply restrictions to your administrative account, the only way we've found to reverse the changes is to run System Restore by going to Settings > Update & Security > Recovery and clicking the "Restart now" button under Advanced Startup. From there, you can find the setting for running System Restore after a restart, since you won't be able to run System Restore the normal way. For this reason, we also highly recommend creating a restore point before making any of the changes here.
Home Users: Block or Restrict Apps by Editing the Registry
To block or restrict apps in the Home edition of Windows, you'll need to dive into the Windows Registry to make some edits. The trick here is that you'll want to log on as the user you want to make changes for, and then edit the Registry while logged onto their account. If you have multiple users for which you want to changes for, you'll have to repeat the process for each user.
Standard warning: Registry Editor is a powerful tool and misusing it can render your system unstable or even inoperable. This is a pretty simple hack and as long as you stick to the instructions, you shouldn't have any problems. That said, if you've never worked with it before, consider reading about how to use the Registry Editor before you get started. And definitely back up the Registry (and your computer!) before making changes.
Block Certain Apps Through the Registry
First, you'll need to log on to Windows using the user account for which you want to block apps. Open the Registry Editor by hitting Start and typing "regedit." Press Enter to open Registry Editor and give it permission to make changes to your PC.
In the Registry Editor, use the left sidebar to navigate to the following key:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies
Next, you're going to create a new subkey inside the Policies key. Right-click the Policieskey, choose New > Key, and then name the new key Explorer .
Next you're going to create a value inside the new Explorer key. Right-click the Explorer key and choose New > DWORD (32-bit) value. Name the new value DisallowRun .
Double-click the new DisallowRun value to open its properties dialog. Change the value from 0 to 1 in the "Value data" box and then click "OK."
Back in the main Registry Editor window, you're now going to create a new subkey inside the Explorer key. Right-click the Explorer key and choose New > Key. Name the new key DisallowRun , just like the value you already created.
Now, it's time to start adding apps you want to block. You'll do this by creating a new string value inside the DisallowRun key for each app you want to block. Right-click the DisallowRunvalue and then choose New > String Value. You'll be naming these values with simple numbers, so name the first value you create "1."
Double-click the new value to open its property dialog, type the name of the executable you want to block into the "Value data" box (e.g., notepad.exe ), and then click "OK."
Repeat this process, naming the second string value "2" and the third "3" and so on, and then adding the executable file names you want to block to each value.
When you're done, you can restart Windows, log onto that user account, and then test things by trying to run one of those apps. You should see a "Restrictions" window pop-up letting you know that you can't run the app.

A: The easy and user-friendly solution would be the Microsoft Family website, checkout this post. But you'll be using a new Member/Standard user account since your existing one would be the Administrator account and it's not possible to set restrictions on it, but you'll be using that to block the apps for the Standard user.
Follow this article to create the Standard user account and have it connected with your device. Remember to turn Activity Reporting on. Once done, sign into your device with this user account and just once launch the app you want to block, use it for a couple of minutes and close it. Then login to the Microsoft Family website with your Administrator account and you'll find the app show up under Screen time -> Apps & Games for that user and select Block app.
Additionally you may also want to turn on the App and Game limits option there and then you may limit your apps usage by duration and/or time window for specific days of the week.

A: As @Biswapriyo mentioned in the comments, I just rename the executable file. (I add -disabled to the end of the name.) Then if I want it to work again, I just rename it to the original name. Of course, this doesn't fully hide it from all menus, as you requested, but it's very fast and easy.

A: Take a look at the procedure here: https://www.howtogeek.com/howto/8739/restrict-users-to-run-only-specified-programs-in-windows-7/
This may also work in Windows 10. It's done by registry keys/values.


text:
Q: ZF3: Controllers with child routes doesn't work I'm ZF2 developer and I'm migrating to ZF3 and I'm having troubles whith some controllers.
For example, I have this url: http://localhost/admin which calls to the correct controller (IndexController) and show the correct view. But If I want to associate this url: http://localhos/admin/articulo with ArticuloController doesn't work. When I call to this url: http://localhost/admin/articulo the controller called is AdminController and doesn't find the view.
OPTION 1 => module.config.php:
namespace Admin;

use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'router' => [
        'routes' => [
            'admin' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/admin[/:action]',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
            'admin/articulos' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/admin/articulos[/:action]',
                    'defaults' => [
                        'controller' => Controller\ArticulosController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\IndexController::class => InvokableFactory::class,
            Controller\ArticulosController::class => InvokableFactory::class,
        ],
    ],
    'view_manager' => [
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout-admin.phtml',
            'admin/index/index'       => __DIR__ . '/../view/admin/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
        /*
         * Con este array de parámetros permitimos enviar datos y no mostrar vista
         */
        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],
];

OPTION 2 => module.config.php (ZF2 style):
namespace Admin;

use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'router' => [
        'routes' => [
            'admin' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/admin[/:action]',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
            'admin/articulos' => [
                'type'    => Literal::class,
                'options' => [
                    'route'    => '/admin/articulos[/:action]',
                    'defaults' => [
                        'controller' => 'Articulos',
                        'action'     => 'index',
                    ],
                ],
                'may_terminate' =>  true,
                'child_routes'  =>  [
                    'default'   =>[
                        'type'  =>  Segment::class,
                        'options'   =>  [
                            'route' =>  '/[:controller[/:action][/:id1]]',
                            'constraints'   =>  [
                                'controller'    =>  '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'        =>  '[a-zA-Z][a-zA-Z0-9_-]*',
                                'id1'           =>  '[0-9_-]*'
                            ],
                            'defaults'  =>  [],
                        ],
                    ],
                ],
            ],
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\IndexController::class => InvokableFactory::class,
            Controller\ArticulosController::class => InvokableFactory::class,
        ],
    ],
    'view_manager' => [
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout-admin.phtml',
            'admin/index/index'       => __DIR__ . '/../view/admin/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
        /*
         * Con este array de parámetros permitimos enviar datos y no mostrar vista
         */
        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],
];

OPTION 3 => module.config.php (following zf3 tutorial):
https://docs.zendframework.com/zend-mvc/routing/#http-routing-examples
namespace Admin;

use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'router' => [
        'routes' => [
            'admin' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/admin[/:action]',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
                'may_terminate' =>  true,
                'child_routes'  =>  [
                    'articulos' =>  [
                        'type'  =>  Segment::class,
                        'options'   =>  [
                            'route' =>  '/articulos[/:action]',
                            'defaults'  =>  [
                                'controller'    => Controller\ArticulosController::class,
                                'action'        =>  'index'
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\IndexController::class => InvokableFactory::class,
            Controller\ArticulosController::class => InvokableFactory::class,
        ],
    ],
    'view_manager' => [
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout-admin.phtml',
            'admin/index/index'       => __DIR__ . '/../view/admin/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
        /*
         * Con este array de parámetros permitimos enviar datos y no mostrar vista
         */
        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],
];

For all of the configurations when I call the url: http://localhost/admin/articulos the view that I get is ...

Where you can see that the controller called is Admin\Controller\IndexController and not Admin\Controller\ArticulosController
What am I doing wrong?
Update 1:
The option 3 configuration works fine!!! I have delete all the content from /cache directory and now the controller is found but ... I have got now an error rendering the template ...
Message:

Zend\View\Renderer\PhpRenderer::render: Unable to render template
  "admin/articulos/index"; resolver could not resolve to a file

Stack Trace:

0 /var/www/html/31juegos/vendor/zendframework/zend-view/src/View.php(207):
  Zend\View\Renderer\PhpRenderer->render()
1 /var/www/html/31juegos/vendor/zendframework/zend-view/src/View.php(236):
  Zend\View\View->render(Object(Zend\View\Model\ViewModel))
2 /var/www/html/31juegos/vendor/zendframework/zend-view/src/View.php(200):
  Zend\View\View->renderChildren(Object(Zend\View\Model\ViewModel))
3 /var/www/html/31juegos/vendor/zendframework/zend-mvc/src/View/Http/DefaultRenderingStrategy.php(105):
Zend\View\View->render(Object(Zend\View\Model\ViewModel))
4 /var/www/html/31juegos/vendor/zendframework/zend-eventmanager/src/EventManager.php(322):
  Zend\Mvc\View\Http\DefaultRenderingStrategy->render(Object(Zend\Mvc\MvcEvent))
5 /var/www/html/31juegos/vendor/zendframework/zend-eventmanager/src/EventManager.php(171):
  Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent))
6 /var/www/html/31juegos/vendor/zendframework/zend-mvc/src/Application.php(367):
  Zend\EventManager\EventManager->triggerEvent(Object(Zend\Mvc\MvcEvent))
7 /var/www/html/31juegos/vendor/zendframework/zend-mvc/src/Application.php(348):
  Zend\Mvc\Application->completeRequest(Object(Zend\Mvc\MvcEvent))
8 /var/www/html/31juegos/public/index.php(40): Zend\Mvc\Application->run()
9 {main}

A: It is a typo issue. Try with this http://localhost/admin/articulos (note the ending "s") because your router is /admin/articulos which points to this ArticulosController's indexAction(). That is why this url http://localhost/admin/articulo (without ending "s") was not able to dispatch. And the view structure should be of type module/controller/action.

A: (Posted on behalf of the OP).
Finally, I have fixed my last problem. The problem was due to my index.phtml was in an wrong directory /view/admin/articulos/**index/**index.phtml. The correct directory is /view/admin/articulos/index.phtml.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React Native v Xamarin Forms - Choosing Cross Platform App Environment I have been looking at Xamarin Forms for building a cross platform App. We would like a framework which targets iOS, Android and Windows Phone. It seems like a nice product, but the license cost may cause us a problem with our business model and also licensing for Windows Phone development is unclear.
I have come across another framework called React Native which claims to be able to build cross platform apps.  I wondered if anyone could give me an idea of its strengths and weaknesses, in particular, relative to Xamarin Forms if possible.  One thing is that it uses Javascript, which may not scale well (either in terms of code maintenance or execution performance).  But I would be grateful for input from anyone who has looked closer at React and has formed some objective opinions about its usefulness.
https://facebook.github.io/react-native/
Thanks.

A: disclosure: I'm not a Facebook or Microsoft employee, I'm not involved with either platform, I'm a web developer that just started learning how to develop with react native.
react native
built by facebook and open sourced - it currently (as of October 2015) supports iOS and Android only. It is similar to Xamarin on the fact that the UI components you build are converted into native components, and DON'T run inside of a web view, such as in other frameworks (e.g: Cordova); the advantage is that native components are more responsive than web components.
Apps should be able to share the business logic code, and most of the UI components, but as the team behind react native puts each platform has its own distinct interface, and your app should account for that, and as such it allows and encourages you (it doesn't enforce you though) to write your app UI interface for each platform.
All the code is written in Javascript (not Java), running in a nodejs process, with the UI described using XML elements, and styled with a pattern that is similar to CSS, but internally parsed as Javascript.
Your app will run in two threads, the main thread where most of the UI will run, and the nodejs thread where your business logic will run. This have some implications when you architect your application.
The framework is mature enough for you to build production ready applications, but the cross-platform components officially supported still needs to increase. The community is also building great cross platform components that you might want to use, most if not all of them are free.
what is the team behind react native working now? (based on the talks I've watched online):

*

*fixing the workflow of assets - currently if you modify an asset, first you have to do it in a different place for each platform supported and in order to see the change when developing you have to recompile the app.

*increasing the number of react native UI elements (specially for the android platform)

In summary these are the points you need to consider:
                 Xamarin                     React Native

built by:        Xamarin                     Facebook
language         C#                          Javascript (nodejs)
age              mature                      (prod ready), but not mature
community:       good support                good support
platforms        iOS, Android, Windows       iOS, Android
cost             FREE (open sourced)         FREE (open sourced)


text:
Q: Does Couchbase have a query language? Does Couchbase have a query language, its counterpart to SQL, and does it have a concept of "Join"? I am a long-time Codd and Date guy, who recognizes the limitations of that paradigm for certain kinds of data management problems.   If it does have one, what's it called?

A: Couchbase has a query language called N1QL. It is SQL like and does have JOINs. It is not production ready yet. Your best source of information is at http://query.couchbase.com.
UPDATE: Couchbase's query language came out in Couchbase 4.0 as of October 6th 2015. Go grab the latest version at the download page.


text:
Q: What delimiter to use in FOR loop for reading lines? I have a txt file that contains the following lines
jfo3 93jfl
lvls 29fdj
nskd jfuwe
xlkw eklwe

I'm trying to read the file line by line, and do something with it. What delimiter should I use?
The delim I'm using here reads each word separately.
@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%x in (lines.txt) do (
    echo %%x
)

A: This reads line by line for me:
for /f "delims=" %x in (lines.txt) do echo %x

A: The problem is not related to delims, but to tokens:
for /f "tokens=*" %%x in (lines.txt) do echo %%x

A: If this is your input file:

abc,def
ghi,jkl
mno,pqr

then use
FOR /F "tokens=1,2,3 delims=," %%i in (test.txt) do (whatever u want)


text:
Q: Javascript setAttribute Vs jquery multiple attribute setter I want to set so many attributes for multiple elements. Javascript always give better performance when comparing to jquery.
i want to know which one gives better performance when settling multiple attributes via jquery and javascript.
Jquery multiple attribute setter:
$(element).attr({'id': 'id1', 'index':1, 'value':10,'check':'checked'});

using javascript setAttribute :
element.setAttribute('id','id1');
element.setAttribute('index','1');
..................................

when am using javascript i need to write multiple lines. otherwise need to create custom function for this.
can anyone explain which one gives better performance ?  and why ?
Thanks,
Siva

A: Here is a jsperf which tests setting of attributes. I'm not sure that it covers your situation but as the others said - pure javascript is a lot faster then using a library. (I'm not even sure that the jsperf is a valid one. I mean if it test what you need).
http://jsperf.com/aaa-setting-attribute
jQuery version is 66% slower then the pure javascript variant.

A: Computers cost much less than programmers.
Let's say:
Using pure js will make code run for 1ms, and programmer work 3 hours.
Using jQuery will make code run for 2ms and programmer work 1 minute
See profit?

A: You should probably be setting properties, not attributes, as they are more consistent across browsers and have a more consistent effect on DOM elements (sometimes setting an attribute affects the property, sometimes it doesn't). Setting the property nearly always has the desired affect (e.g. setting a checkbox to checked), setting the related attribute doesn't always.
You can also use a small function if you want to set multiple properties on an element:
function setProperties(element, props) {
  for (var prop in props) {
    if (props.hasOwnProperty(prop)) {
      element[prop] = props[prop];
    }
  }
}

I can't see that it would be any slower than jQuery.

A: jQuery is a library, so I think it better than pure javascript. It help you to use javascript easier. I supposed that!
You can see the same question here
If you want to get all of attributes of element, you can see here also.


text:
Q: Create a class which accept Runnable but include better control I want to create a structured code like this:
EventWrapper.newWrapper().
    ifThen(isSunday(),
            () -> announceSunday()).
    pauseFor(Duration.ofSeconds(10)).
    addAsyn(() -> System.out.println("Asynch System out")),
    add(() -> System.out.println("Sync System out")).execute();

I want to have multiple functions such as
pauseFor which pause the execution of this Wrapper, addAsyn which execute a runnable but using a threadpool, add which execute the runnable but others wait until the content of the runnable is executed and ifThen which accept a boolean condition and execute the given runnable if true.
My code so far base on a previous post i made here (and thank you very much) is the following:
public class EventWrapper
{
    private final List<Runnable> _wrappers = new ArrayList<>();

    public EventWrapper add(final Runnable runnable)
    {
        _wrappers.add(runnable);
        return this;
    }

    public void execute()
    {
        _wrappers.forEach(Runnable::run);
    }

    public static EventWrapper newWrapper()
    {
        return new EventWrapper();
    }
}

Is there any idea on how to add these functions in this class and while execute it to be able to control the way i mentioned? Thanks a lot.


text:
Q: Open file stored in byte[] in webbrowser control Is there a way to take a byte[] and open the file rather than having to write it to disk and delete it when finished? They will be pdf files.
Update 2
if (e.Result is byte[])
            {
                byte[] message = (byte[])e.Result;
                using (MemoryStream stream = new MemoryStream(message))
                {
                    stream.Position = 0;
                    wbMessage.NavigateToStream(stream);
                }
            }

I scrapped this idea and used Adobe's COM object to display my PDFs

A: MemoryStream has constructor that takes byte[]


text:
Q: How to use server database in TestContext in spring instead of the in memory h2 database? I need to use a server database in my TestConfiguration. I have defined a Postgresql database in my application.properties, which should be used by the application, however the TestContext is using an embedded h2 database.
The application.properties has the following content:

H2 is defined as a dependency in the pom.xml file, when I remove and try to build without I get an error:
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.getDriverClassName(DataSourceProperties.java:180)
at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource(DataSourceAutoConfiguration.java:121)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)

What am I doing wrong?

A: The problem was the scope that I have defined in the pom for postgresql.
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

When I set the scope to provided everything works fine.


text:
Q: Karate framework - What is the correct way to use conditional logic "if-then-else" in scenario? I tried couple of ways to make use of IF-Else conditional logic as mentioned in these two links   1 How to check additional values with if condition (using karate framework)? [2]https://github.com/intuit/karate#conditional-logic  After trying different combinations I am still unsuccessful and I don't see other ways to make my scenario work. For better visibility and understanding I have attached screenshot.
As shown both output2.c.data and z.d.data are empty array's. Using these two references I have defined      *def output4 = (z.d.data == output2.c.data ? {pass:true} : {pass:false})  I was expecting my output - output4- to be   {"pass":true}  For unknown reasons my scenario is giving me the opposite of what I am expecting.

A: You can't do an equals operation on two arrays in JavaScript, which is why Karate's "deep equals" match is needed.
* def foo = { data: [] }
* def bar = { data: [] }

# wrong
* def result = foo.data == bar.data ? { pass: true } : { pass: false }
* match result == { pass: false }

# right
* def result = karate.match(foo.data, bar.data).pass ? { pass: true } : { pass: false }
* match result == { pass: true }

EDIT - this is a more detailed answer: https://stackoverflow.com/a/50350442/143475


text:
Q: Convert string to hex-string in C# I have a string like "sample". I want to get a string of it in hex format; like this:
"796173767265"

Please give the C# syntax.

A: few Unicode alternatives
var s = "0";

var s1 = string.Concat(s.Select(c => $"{(int)c:x4}"));  // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"

var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", "");       // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"

// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");

A: In .NET 5.0 and later you can use the Convert.ToHexString() method.
using System;
using System.Text;

string value = "Hello world";

byte[] bytes = Encoding.UTF8.GetBytes(value);

string hexString = Convert.ToHexString(bytes);

Console.WriteLine($"String value: \"{value}\"");
Console.WriteLine($"   Hex value: \"{hexString}\"");

Running the above example code, you would get the following output:
String value: "Hello world"
   Hex value: "48656C6C6F20776F726C64"

A: For Unicode support:
public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

A: var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));

OR
var result  =string.Join("",
                input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));

A: First you'll need to get it into a byte[], so do this:
byte[] ba = Encoding.Default.GetBytes("sample");

and then you can get the string:
var hexString = BitConverter.ToString(ba);

now, that's going to return a string with dashes (-) in it so you can then simply use this:
hexString = hexString.Replace("-", "");

to get rid of those if you want.
NOTE: you could use a different Encoding if you needed to.

A: According to this snippet here, this approach should be good for long strings:
private string StringToHex(string hexstring)
{
    StringBuilder sb = new StringBuilder();
    foreach (char t in hexstring)
    {
        //Note: X for upper, x for lower case letters
        sb.Append(Convert.ToInt32(t).ToString("x2"));
    }
    return sb.ToString();
}

usage:
string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"

Another approach in one line
string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x2")));

A: In case detailed conversion with regard to endianness of bytes or words is required, here is an example of the craft to do bitwise conversion.
var bcd = new byte[] { 64, 7, 19, 0, 0, 0 };
var str = String.Join("", bcd.Reverse().Select(b => $"{b:X2}"));

str => 000000317004
To also swap 4-bit nibbles of each byte, shift and mask to format each 4 bit separately.
var bcd = new byte[] { 64, 7, 19, 0, 0, 0 };
var str = String.Join("", bcd.Reverse().Select(b => $"{b & 0x0F:X1}{b>>4:X1}"));

str => 000000130740


text:
Q: PHPmailer parseAddresses - How to get rid of "notice" messages I'm trying to get rid of the following message in one of my scripts when using the PHPmailer parseAddresses function:
Notice: Unknown: Must use comma to separate addresses: xxx (errflg=3) in Unknown on line 0
$mailer = new PHPMailer(true);
try {
    $a = $mailer->parseAddresses('aaa@aaa.aaa xxx');
}
finally {
    ...
}

I'm using PHP 7.0.8 with the following error handling presets:
declare(strict_types = 1);
error_reporting(E_ALL);
ini_set('display_errors', 'stdout');

I know that I can just stop the errors from being displayed but this doesn't seem to be the proper way to do. And of course I know that the provided email addresses in my example are not correct...

A: I'm not sure what you're complaining about: it's telling you you have malformed input when you provide malformed input! The way to avoid the error is not to pass in malformed input!
As the error says, it's expecting one or more addresses in comma-delimited RFC822 format (not what you provided), which might be something like:
xxx <aaa@aaa.aaa>, yyy <bbb@aaa.aaa>

If you don't provide data in that format, it will complain, as you're seeing. This is covered in the docs on the parseAddress method.
Are you expecting it to do something else?

A: PHPMailer writes notices to output, so you could start an output buffer and just flush it after your call.  Something like:
$mailer = new PHPMailer(true);
try {
    ob_start();
    $a = $mailer->parseAddresses('aaa@aaa.aaa xxx');
    //$notices = ob_get_contents();
    ob_end_clean();
}
finally {
    ...
}

A: I had to deal with the same issues. Simply created a homemade solution that does mostly the same thing in a more flexible way. For anyone that is interested:
/**
 * split_addresses Split a list of email addresses with potential validation
 *          Similar concept as PHPMailer->parseAddresses, but more forgiving
 * @param $list - a list of comma delimited email addresses in simple or RFC822 format
 * @param $default_name an optional name to add if not present
 * @param $validate logical var to indicate to only accept validated emails
 * @author Jacques Amar
 * @copyright 2019 Amar Micro Inc.
 */

function split_addresses($list, $default_name='', $validate=true) {
    $valid_arr = [];
    if (empty($list)) { return $valid_arr; }
    $split_arr = preg_split('/\s*,\s*/', $list);
    foreach ($split_arr as $email_candidate) {
        // Validate email_candidate if the form "first last <adrs@email.com>"
        $actual_name  = $default_name;
        $actual_email = $email_candidate;
        if (preg_match('/\s*(.+)\s*\<\s*([^@]+@.+)\s*\>/', $email_candidate, $actual_emails) == 1) {
            $actual_name  = $actual_emails[1];
            $actual_email = $actual_emails[2];
        }
        if ($validate) {
            if  (filter_var($actual_email, FILTER_VALIDATE_EMAIL)) {
                $valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
            }
        } else {
            $valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
        }
    }
    return $valid_arr;
}

Should be self explanatory


text:
Q: Dynamic Macro That Auto Updates Graph Scale Misfiring When File Opens I have an issue that makes no sense to me.
Option Explicit

Private Sub Worksheet_Calculate()

Dim Chtob As ChartObject
Dim wks As Worksheet
Set wks = ActiveSheet

On Error GoTo Terminate

For Each Chtob In ActiveSheet.ChartObjects
With Chtob.Chart
    If wks.Range("$G$2").Value <> .Axes(xlCategory).MaximumScale Then
        .Axes(xlCategory).MaximumScale = wks.Range("$G$2").Value
    End If
    If wks.Range("$C$2").Value <> .Axes(xlCategory).MinimumScale Then
        .Axes(xlCategory).MinimumScale = wks.Range("$C$2").Value
    End If
    If wks.Range("$G$2").Value <> .Axes(xlCategory, xlSecondary).MaximumScale Then
        .Axes(xlCategory, xlSecondary).MaximumScale = wks.Range("$G$2").Value
    End If
    If wks.Range("$C$2").Value <> .Axes(xlCategory, xlSecondary).MinimumScale Then
        .Axes(xlCategory, xlSecondary).MinimumScale = wks.Range("$C$2").Value
    End If
End With
Next

Exit Sub
Terminate:
MsgBox "Storm Event Not Valid, Please check if such event number exists"
End

Exit Sub

This macro is used on a tab that has two charts. When a certain cell changes the macro updates the graph scale. This tab will be then duplicated numerous times to show different time events.
The issue arises when someone else tries to open this file. The moment the file is open they get the error to pop up as many times as the amount of tabs created. This for some reason causes a different tab with a different graph to reset it's x scale. This different tab does not have the dynamic macro attached to it and no other macros are being used.
I want to say that a different version of Excel might be part of the problem, but there are times when this doesn't happen.
The way it should work is when somebody enters the wrong value in cell B2 the macro can't execute. So instead of going into debug, one gets an error message. So I need the error portion of the macro to be there.
I should mention that the tab also has another dynamic macro that automatically renames the tab name if the same cell changes.
Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$2" Then
    If Not Target.HasFormula Then
        If Not Target.Value = vbNullString Then
             On Error GoTo ErrHandler
             ActiveSheet.Name = "Event" & " " & Target.Value
        End If
    End If
End If
Exit Sub
ErrHandler:
MsgBox "Error " & Err & ":" & Error(Err)
On Error GoTo 0
End Sub

A: Thanks to comments made by Scott, my issue has never poped up again
I just changed Set wks = Activesheet to Set wks = Me and then changed all of the wks to Me in the script
Option Explicit

Private Sub Worksheet_Calculate()

Dim Chtob As ChartObject
Dim wks As Worksheet
Set wks = Me

On Error GoTo Terminate

For Each Chtob In Me.ChartObjects
    With Chtob.Chart
  If wks.Range("$G$2").Value <> .Axes(xlCategory).MaximumScale Then
    .Axes(xlCategory).MaximumScale = wks.Range("$G$2").Value
  End If
  If wks.Range("$C$2").Value <> .Axes(xlCategory).MinimumScale Then
    .Axes(xlCategory).MinimumScale = wks.Range("$C$2").Value
        End If
  If wks.Range("$G$2").Value <> .Axes(xlCategory, xlSecondary).MaximumScale Then
    .Axes(xlCategory, xlSecondary).MaximumScale = wks.Range("$G$2").Value
  End If
  If wks.Range("$C$2").Value <> .Axes(xlCategory, xlSecondary).MinimumScale Then
    .Axes(xlCategory, xlSecondary).MinimumScale = wks.Range("$C$2").Value
        End If
    End With
Next

    Exit Sub
Terminate:
    MsgBox "Storm Event Not Valid, Please check if such event number exists"
    End

End Sub


text:
Q: how to inject keystrokes in a program like Safari from a bash script? I am trying to automate some keypresses every few minutes. The exact timing is still undetermined. But basically I want to capture a live chat dialogue. I'm sure I could do this more elegantly. I don't know much if anything about html or javascript or php etc.. I know a little bit of Bash and a little bit of AppleScript.
osascript -e 'tell app "Safari" to activate'
osascript -e 'set Script to "keystroke \"a\" using command down"'
osascript -e do Script

This would keep going and activate TextEdit and paste into there. But I haven't gotten past this point. This results in: syntax error: Can't set script to "keystroke \"a\" using command down". Access not allowed. (-10003)
Changing Script to myScript and I get: keystroke "a" using command down.
But both methods still result in: execution error: The variable do is not defined. (-2753)
The fact that it calls "do" a variable makes my head spin.
I thought about using the expect program. I know I can run expect and say something like send \n to get a new line. However, that's about all I know. And I cannot find much documentation on how to send modifier keys like Cmd-A. It doesn't really matter whether expect or osascript as long as  the end result works.
I would like to somehow get away from the select all step because it selects the entire webpage to be copied instead of just the chat box. Any help would be appreciated very much.

A: Try this instead:
osascript -e 'tell Application "Safari" to activate'
osascript -e 'tell application "System Events"' -e 'keystroke "a" using command down' -e 'end tell'


text:
Q: Web View is not working in iOS5 I am very new to iPad and was trying "Loading a web page using the Web View" - opening the google page!
I followed all the steps given in the box/tutorial but I am not able to view the page.
Step 1 : Added web view in the view window
Step 2 : decalre outlet for web view by adding following code
@interface WebiPadViewController : UIViewController {
   IBOutlet UIWebView *webDisplayiPad;
 }
 @property(nonatomic,retain) UIWebView *webDisplayiPad;

Step 3 : Connect webview outlet to Web view using file manager
Step 4 : Create URl and request object using followng code:
 - (void)viewDidLoad {
    NSString *urlAddress = @"http://www.google.com";

 //Create a URL object.
   NSURL *url = [NSURL URLWithString:urlAddress];

//URL Requst Object
  NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

//Load the request in the UIWebView.
  [webDisplayiPad loadRequest:requestObj];

 [super viewDidLoad];
 }

Step 5 : Save and run the app to see google page.
But the Simulator shows only a white background!

A: Let me start by saying it is possible you simply haven't setup your ViewController class and View outlet property properly, as sergio describes, since that can also lead to a blank white background.
But I'm going to assume that it is your webDisplayiPad property that is not connected. I think this most likely since your "Step 3 : Connect webview outlet to Web view using file manager" seems a sketchy description at best.
To check your connection go to your WebiPadViewController.xib and right-click (cntrl-click) on the File's Owner icon. Under outlets there should be your webDisplayiPad listed with a circle to the right of it. If the circle is empty, and I suspect it is, drag from the circle to the UIWebView. The UIWebView will do a little flash to confirm. And your done.
Also the modern way of connecting IBOutlets is to put that keyword in the property definition and forget the ivar completely. For example:
@interface WebiPadViewController : UIViewController {

}
@property(nonatomic,retain) IBOutlet UIWebView *webDisplayiPad;

and in the .m file to do this:
@implementation WebiPadViewController
@synthesize webDisplayiPad = _webDisplayiPad;

The synthesize will create the backing variable for you and the _ character will help you keep them straight.
If you were to change to this way your loadRequest call would look like one of the following two:
[_webDisplayiPad loadRequest:requestObj]; // Calls through ivar
[self.webDisplayiPad loadRequest:requestObj]; // Calls through accessor method

A: Don't forget in you implementation:
@synthesize webDisplayiPad = _webDisplayiPad;

A: I guess that you got some problems with your Nib/Xib connections.
Please, check the following:

*

*your nib's file's owner class is set to be WebiPadViewController;

*your controller's view outlet is connected to the web view.

A: Set delegate.
web page loads only when u set the delegate.
other wise it will be an empty page

A: I think you have to load HTML into a UIWebView,


text:
Q: Grounding with a wood table vs a metal table standing on a carpet floor I have the acer nitro 5 AN515-53.
I'm standing on carpet flooring and I suspect that will produce static electricity overtime.
Would a wood table and metal table have the same grounding properties as long as they are on the floor I'm standing on? How do they differ as conductive vs non-conductive material?
Do I need to feel the "shock" from touching something conductive to be grounded? Would I feel that shock from touching wood, and if not would I still be "grounded?"

A: Neither would be grounded, as neither connect to ground. They're both just a floating potential, the same as you.
If you get static shocks when you touch the water taps or large electrical appliances - fridge, cooker etc, then I'd start to worry about it… otherwise I wouldn't bother.
Your computer's case is a faraday cage anyway. Even if you get a spike from it, it's being routed to the mains socket's potential [even if the socket's not grounded you still will reach an equilibrium through it.]
Otherwise, only worry about correct grounding if you're working inside it.

A: In general, this is not something you need to consider... if the shocks are distressing for you, or you're asking out of curiosity, please read on.

There are two major questions here.

*

*Are you a "normal user" who is just working with their computer, or are you working with bare electronics, exposed PCBs / ICs, etc...?

*Are you getting static shocks, and is this concerning / distressing for you?

For the first question, if you are a "normal user", then you shouldn't typically need to worry about it. If you open the computer to perform an upgrade (e.g: more RAM), then carefully ground yourself or match your potential to the computer's chassis by touching / holding the metalwork. But if you're just using the fully assembled equipment, then they are (or should be) designed in such a way to handle this properly.
For the second question, the shocks aren't typically problematic, but they can be very annoying and surprising. Higher energy shocks will present as an arc, possibly with a snapping / cracking sound. If you have a pacemaker or similar, then it might be sensible or more important to look into resolving this.

"Ground" is generally used as a good solid reference because it's so readily available, but it's not really the major factor - "potential difference" is (i.e: the difference in potential / voltage between two objects).
If you're in polyester socks, and polyester trousers, and shuffling around on your polyester carpet, etc... then you can work up quite a large static charge quite quickly. Touching something that is at a different potential can cause a shock regardless of whether one or other is technically "grounded". The arc or physical contact causes the potential difference between two objects to reduce.
As above, clothing and other materials can have a large impact on this effect - conductivity being the major consideration. However, other factors such as the humidity in your room can also have a large impact - low humidity (< 40%) reduces the conductivity of the air, and permits a larger buildup of static charge between two objects - conversely higher humididty will decrease the conductivity of the air, and that permits the charge to dissipate more quickly.

Do I need to feel the "shock" from touching something conductive to be grounded?

No. ESD mats are designed specifically to have a fairly high but well defined resistance. Touching one that is correctly setup for a period of a few seconds will disappate your built-up charge, but you won't feel a shock or get an arc (though you may feel it as the charge disappates - e.g: in your hairs).
The shock or arc is the problem for electronics - it is related to a rapid change in potential / transfer of energy, and can cause damage to electronics. A slower discharge brings things to the same potential, but without the damaging effects of a quick discharge.

Would I feel that shock from touching wood, and if not would I still be "grounded?"

A metal table that is directly connected to earth (e.g: via a socket) will have a low impedance path to ground. You are more likely to feel the discharge, and you are more likely to damage equipment.
A wooden table has a far higher resistance, and therefore you are quite unlikely to feel the discharge, even though it can / will still happen.

A final couple of points:

*

*Please do not play with mains sockets if you don't know what you're doing or have any doubts.

*Please do not connect a metal table directly to ground. A low impedance path will give shocks and can be just as damaging to equipment as a poor / non-ESD-safe environment.

Further response to your situation (upgrading components in your computer)... apologies if this is getting long and in-depth.
If it helps, try to think less about being "grounded" and more about the "potential difference" between objects. Everything is relative, so you can consider your workbench to be your reference point ("ground-ish"), and everything around it to be at some potential from that point. Placing equipment on the desk will allow the potential difference (i.e: static charge) between the desk and equipment to equalize over time - even if the desk isn't very conductive (e.g: wood).
Additionally, keep in mind that "static electricity" behaves differently to "current electricity" (ref). Static electricity is typically many thousands of volts and up.
Given that wood is (generally speaking) more conductive than air, a build up of static charge on your person will "dissipate into" the wooden desk more quickly than it will "dissipate into" the surrounding air - but it will likely be significantly slower than using a proper ESD-safe working environment.
I've quoted "dissipate into" above, because as I've said, what we really care about here is reducing or removing the potential difference between objects... "dissipate into" might not be the best way of thinking about this, but it seems to be common terminology for this effect. "Equalizing the potential difference" is really what we're interested in, and probably helps with mentally reasoning about this.
The rate of discharge (or rather, speed at which equilibrium is achieved) is an important factor when working with sensitive electronics. Discharging too fast is bad and potentially damaging (e.g: metal desk tied to ground), while discharging too slowly (e.g: wooden desk) can mean that the charge doesn't have an opportunity to fully dissipate before you let go and start work.
ESD mats and earthing points are designed with a non-zero resistance (typically about 1 MΩ for an earth bonding point). This is so ensure a controlled discharge over a period of time. They are all about dissipating the static charge (over time), not discharging it (quickly).
As above, the "potential difference" is by far the most important part. When working with electronics, it is the potential difference between your body (and thus fingers) and the sensitive components (i.e: ICs) which is the concern. Electronic devices with metal chassis (e.g: a PC) are often design with their "ground" / 0v / reference tied to the mains-ground and also connected to the chassis. By holding the metal chassis of the equipment, you will bring your body to the same potential, meaning that you are then able to safely handle the components inside. If you aren't wearing an ESD wristband, and you walk up and poke at a PCB directly (instead of touching the enclosure first), then that discharge can occur through the circuit board and/or chips... this may well cause damage.
With this conceptual view, your body can be considered a tiny capacitor (~100 pF) charged up to ~15 kV. You can model other objects the same way. With a low impedance path, the discharge can be fast (< 1 μs), which can result in a spark. There is little total energy here, but the voltage (aka: potential difference) is very significant and that small amount of energy transferred can still be damaging. If the path of that fast discharge is through sensitive electronics components (i.e: the ICs directly), then damage can definately occur.
So, in summary... if you're not working in an ESD-safe environment:

*

*Always touch the chassis / enclosure / metalwork before putting your hands into the equipment

*

*Every time you walk off and return

*After taking a top off (especially a fleece or similar)

*Periodically, as a matter of course

*Pick up components by the edge of the PCB wherever possible

*

*Don't grab for the board, placing your fingers on the ICs

*Maintaining a low potential difference between yourself and the equipment is more important

*The grounding of your workbench is less important

A:
I'm standing on carpet flooring and I suspect that will produce static
electricity overtime. Would a wood table and metal table have the same
grounding properties as long as they are on the floor I'm standing on?

(1) Wood is not conductive. Carpet is not conductive in general (some carpets have metal threads woven in to reduce static.
Working on a Wood Table standing on carpet will not protect your gear and static could damage it.
(2) Metal table is fine.  Make sure the metal table is grounded to your room ground (electrical ground). Attach a wire to the table and to the ground screw of an electrical outlet.
You can get a metal bracelet that you can attach to the table so when you work on your gear you and it will be safe.
You can also get a mat to stand on the will help control electrostatic discharge.
From your post, I assume you have the option of a wooden table (not at all conductive) and a metal table (will be conductive).

A: Ignore the type of table completely, and invest in an ESD mat, wrist-band and earth socket to ensure a proper ground. Otherwise, all bets are off.


text:
Q: How to catch http.get (SocketException) I'm new to Flutter & Dart, trying to complete my first app.
I can't catch (with try-catch block) http.get SocketException (which happens when you call API and WiFi turned off)
I tried everything on the internet without luck, I even tried (Dio) package to catch this exception, but no success.
How to reproduce: use bottom code...turn off phone's WiFi...call API...now the app crashes with (SocketException) in your IDE.
Image: https://imgur.com/bA0rKEN
here is my simple code (updated)
     RaisedButton(
              child: Text("Call API"),
              onPressed: () async {
                try {
                  http.Response response = await getLoginResponse();
                  //do something with response
                  print(response.body);
                } catch (e) {
                  print("Button onPressed Error: " + e.toString());
                }
              },
            )
//---------------------------------------------------------------
Future<http.Response> getLoginResponse() {
    return http.get(loginUrl).timeout(Duration(seconds: 10))
    .then((response) {
      return response;
    }, onError: (e) {
      print("onError: " + e.toString());
    }).catchError((err) {
      print("catchError: " + err.toString());
      return null;
    });
  }

A: You can catch several types of errors and handle each one separately
Example:
import 'dart:io' as Io;

http.Client client = http.Client();

try {
  response = await client.get(url).timeout(new Duration(seconds: 10));
} on Io.SocketException catch (_) {
  throw Exception('Not connected. Failed to load data');
} on TimeoutException catch (_) {
  throw Exception('Not connected. TimeOut Exception');
} catch (e) {
  // Default error handling;
}

A: if you want to get catch in RaisedButton's try-catch block, instead of return null in getLoginInfo() methods, you must return an Exception like this:
 Future<List<LoginObject>> getLoginInfo() async {
    try {
      List<LoginObject> loginObjectList = List<LoginObject>();
      http.Response loginResponse =
          await http.get(loginUrl).timeout(Duration(seconds: 10));
      if (loginResponse.statusCode == 200) {
        loginObjectList = loginObjectFromJson(loginResponse.body);
        return loginObjectList;
      } else {
        throw Exception('Authentication Error');
      }
    } catch (e) {
      print("Error: " + e.toString());
      return throw Exception('Connection Error');;
    }
  }

Note: If you want to handle each one of error response, you can create an custom ErrorModelClass and handle error state with it and finally return your ErrorModelClass.
 catch (error) {
      print(error);
      throw error is HttpResponseError ? error : HttpResponseError(0,"error connection");

HttpResponseError is my custom model class.


text:
Q: If triangle $DEF$ is the orthic triangle of triangle $ABC$, the symmedian points of triangles $AEF$, $BFD$, $CDE$ lie on the medians of $ABC$
If $\triangle DEF$ is the orthic triangle of $\triangle ABC$, show that the symmedian points of the triangles $\triangle AEF$, $\triangle BFD$, $\triangle CDE$ lie on the medians of $\triangle ABC$.

I found this in textbook called "College Geometry An Introduction to the Modern Geometry of the Triangle and the Circle", but the solution wasn't shown there. I only know that $\triangle AEF$, $\triangle BFD$, $\triangle CDE$, and $\triangle ABC$ are similar, but I don't know what to do next.

A:
$\mathrm{Fig.\space 1}$ shows the complete scenario described by your question. $\mathrm{Fig. \space 1}$ is reproduced in $\mathrm{Fig. \space 2}$ with all those lines unnecessary for our proof erased.  We work out the problem in three different steps to establish the proof we seek.
$\mathrm{\mathbf{\underline {Step\space 1}:}}$ Proving that the corner triangles $AH_CH_B$, $BH_AH_C$, and $CH_BH_A$ are inversely similar to the triangle $ABC$.
Let $\measuredangle CAB = \alpha$, $\measuredangle ABC = \beta$, and $\measuredangle BCA = \phi$.
Consider the two right-angle triangles $BCH_C$ and $BCH_B$.  They have a common hypotenuse $BC$. Therefore, $BCH_BH_C$ is a cyclic quadrilateral. As a consequence of this, $\measuredangle CH_BH_C = 180^0 – \beta$. Since $\measuredangle H_CH_BA$ is the supplement of $\measuredangle CH_BH_C$,
$$\measuredangle H_CH_BA = \beta = ABC.$$
In like manner, we can show $\measuredangle AH_CH_B = BCA$. Therefore, all three corresponding angles of the triangles $ABC$ and $AH_CH_B$ are equal, but described in the opposite rotational sense. Hence, they are inversely similar.
Similar reasoning yields that $BH_AH_C$ and $CH_BH_A$ are also inversely similar to $ABC$.
$\mathrm{\mathbf{\underline{Step\space 2}:}}$ Proving that $BP$ is one of the medians of the corner triangle $BH_AH_C$
Note that $BM_B$ is one of the medians of the triangle $ABC$.
Now, pay attention to the following construction of a pair of lines. First, the angle bisector $BQ$ of the angle $ABC$ is drawn to meet $AC$ at $Q$. Then, the line $BP$ is drawn to meet $H_CH_A$ at $P$, so that it and $BM_B$ make equal angles (i.e. $\theta$) with $BQ$. $BP$ is called the isogonal line of $BM_B$ and vice versa.
Consider the triangles $BCM_B$ and $BPH_C$. It is obvious from $\mathrm{Step\space 1}$ that $\measuredangle BCM_B = \measuredangle PH_CB$.  According to the construction, $\measuredangle M_BBC = \measuredangle H_CBP$. Therefore, the two triangles are inversely similar. Likewise, the two triangles $ABM_B$ and $PBH_A$ are also inversely similar. Now, we can write for the former pair of inversely similar triangles,
$$\frac{CM_B}{PH_C}=\frac{BM_B}{BP}$$
and for the later pair of inversely similar triangles,
$$\frac{AM_B}{PH_A}=\frac{BM_B}{BP}.$$
$$\therefore\space\space \frac{CM_B}{PH_C}=\frac{AM_B}{PH_A}.\space\space\space\space\space$$
Since $ CM_B  = AM_B $, $ PH_C = PH_A $. This means that $BP$ is a medians of the corner triangle $BH_AH_C$.
$\mathrm{\mathbf{\underline{Step\space 3}:}}$ Proving that the symmedian points of the corner triangles lie on the medians of the triangle $ABC$
We make use of the fact that the symmedian point of a triangle is the isogonal conjugate of its centroid and vice versa. This means that the median passing through a certain vertex of a triangle and the line joining its symmedian point to the same vertex are isogonal lines.
In our case, the centroid of the corner triangle $BH_AH_C$ lies on $BP$, which is a median (proved in $\mathrm{Step\space 2}$). Then, the symmedian point of the corner triangle $BH_AH_C$ must lie on the isogonal line of $BP$, which happened to be $BM_B$. By the way, $BM_B$ is a median of the triangle $ABC$.
It is possible to prove that the other two symmedian points lie on the medians of the triangle $ABC$ by using a similar sequence of arguments.

A: I am trying to give a compact, but still detailed proof. Let us fix the notation as in the following picture:

$\Delta DEF$ is the ortic triangle,
  $A'$ is the mid point of $BC$, $S$ is the mid point of $EF$.

Proof of the property claimed in the OP:

*

*$BCEF$ is cylic because of the right angles in $E,F$. This implies $\widehat{AFE}=\widehat{ECB}$ and $\widehat{AEF}=\widehat{FBC}$.

*We obtain the similarity of triangles $\Delta ABC\sim\Delta AEF$ (with these orders of vertices respectively). This gives the proportionality
$$
\color{blue}{
\frac{AF}{AC}}
=
\frac{AE}{AB}
=
\frac{EF}{BC}
=
\frac{EF/2}{BC/2}
=
\color{blue}{
\frac{FS}{A'C}
}
\ .
$$

*The equality of the blue proportions together with the equality of angles in $F$ and $C$ in the marked triangles $\Delta AFS$ and $ACA'$ show their similarity.
In particular the angles in $A$ in the two triangles are equal, so reflecting w.r.t. the angle bisector of $\widehat{BAC}$ the line $AS$ (supporting the median of $\Delta AEF$) we obtain the line $AA'$
(supporting the median of $\Delta ABC$).

*So the line $AA'$ supports the symmedian of $\Delta AEF$, and the median of $\Delta ABC$. We have similar properties for $BB'$, $CC'$ (using similar notations) instead of $AA'$.
$\square$


text:
Q: How to get object Prefix from string type of object name? I have following code to return prefix of any object based on API name of object passed as string. :
private static String  getObjectPrefixID(String objName){

        Schema.DescribeSObjectResult r = genericObject.sObjectType.getDescribe();
        String keyPrefix = r.getKeyPrefix();
        return keyPrefix;
    }

I am getting error as:

Initial term of field expression must be a concrete SObject: String

Not sure how to get the prefix ID in this case.

A: You can do something like
Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
system.debug('==>m is==>'+m);
Schema.SObjectType s = m.get('Account') ;
system.debug('==>Sobject Type is ==>'+s);
Schema.DescribeSObjectResult r = s.getDescribe() ;
String keyPrefix = r.getKeyPrefix();
return keyPrefix;

Replace Account with your Object API name.

A: The accepted answer (and the other existing alternative) relies on the use of Schema.getGlobalDescribe(). While this is quick, easy and obvious to code, it comes at a performance cost.
The first access to this from your org in a while (the describes get cached by Salesforce for a time it seems, or at least some of the underlying metadata does) this can cost over 700ms to return the map - timing testing on a scratch org using Datetime.now().getTime() before and after - only dropping to between 100 and 300ms thereafter on the same org. If you consider you have a maximum of 10 seconds CPU time for a given transaction against the server, this is a real waste. (It must be said, the Limits.getCpuTime method doesn't count the entire cost here, but it is still over 100ms from my testing.)
On the other hand, the following method takes between 2 and 15ms (and averaging around 5ms) to execute, giving the same result:
String typeName = ...; // E.g. 'Case' or 'Account' etc.
SObject instance = (SObject) Type.forName('Schema.' + typeName).newInstance();
String idPrefix = instance.getSObjectType().getDescribe().getKeyPrefix();

Getting the Type for a given typeName is fast and efficient. The modest overhead of creating an empty SObject from the Type has little impact on heap or CPU, and getting the describe for the instance is very fast.
Clearly, if your code needs many different ID prefixes in one transaction (e.g. more than 10-15 different objects' prefixes) it can become more efficient to use the global describes.
UPDATE:
If you go to the trouble of using the updated Schema.describeSObjects, ensuring that the SObjectDescribeOptions.DEFERRED option is applied, you can get even better performance. For example:
String typeName = ...;
List<Schema.DescribeSObjectResult> describes = Schema.describeSObjects(new String[] { typeName }, SObjectDescribeOptions.DEFERRED);
String idPrefix = describes[0].getKeyPrefix();

This, surprisingly, has better performance compared with the use of Type.forName. With my testing (on the same scratch org) I got real time timing of between 2 and 8 milliseconds (the latter actually not on first use of the org for a while, which was 5ms), and a CPU limit timing of between 1 and 3 milliseconds. This makes it the fastest and most repeatable way to access the schema to get the ID key prefix.

A: Pass the object name and you will get the prefix of the object
public static String getObjectKeyPrefix(String objName){
    /*objName ='Account';*/
    schema.sObjectType sObjType = Schema.getGlobalDescribe().get(objName);
    return (sObjType.getDescribe().getKeyPrefix());
}


text:
Q: Quando é recomendado usar índices decrescentes? Por default, os bancos de dados relacionais criam índices usando estruturas de árvores binárias ordenadas de forma crescente. Porém existe a possibilidade de criá-lo de forma decrescente também.
Minha dúvida é se (e quando) é recomendado usá-lo. Por exemplo:
SELECT nome
FROM pessoa
WHERE data_cadastro >= '2014-01-01'
ORDER BY data_cadastro DESC

No SQL acima, considerando o WHERE e ORDER BY, um índice decrescente na coluna data_cadastro melhoraria o desempenho?

A: Imagine um índice em uma coluna de uma tabela agrupada:
CREATE TABLE mytable (
   pk INT NOT NULL PRIMARY KEY,
   col1 INT NOT NULL
)
CREATE INDEX ix_mytable_col1 ON mytable (col1)

O índice em col1 mantém valores de col1 ordenados junto com as referências das linhas.
Uma vez que a tabela é agrupada, as referências às linhas são realmente os valores da pk. Eles também são ordenados dentro de cada valor de col1.
Isto significa que os índice estão ordenados em (col1, pk), e esta consulta:
SELECT  col1, pk
FROM    mytable
ORDER BY
    col1, pk

Não precisa de ordenação!
Se criarmos o índice da seguinte forma:
CREATE INDEX ix_mytable_col1_desc ON mytable (col1 DESC)

em seguida, os valores de col1 serão classificados descendente, mas os valores de pk dentro de cada valor de col1 serão classificados ascendente.
Isto significa que a seguinte consulta:
SELECT  col1, pk
FROM    mytable
ORDER BY
    col1, pk DESC

Pode ser servido por ix_mytable_col1_desc mas não por ix_mytable_col1.

A: Depende da sua necessidade.
Por default os índices são criados na ordem crescente porque, em geral, os valores (normalmente ids) são gerados de forma crescente. Desta forma os novos (maiores) valores vão para o fim da "lista". Isso diminui a chance de fragmentação do índice.
Exemplo:
Suponha que vc tem uma tabela onde o Id é autoident começando em 1 e acrescentando +1 a cada novo registro. Você define essa coluna como PK clustered mas muda a ordem do índice para decrescente.
Isso vai forçar page splits uma vez que cada novo registro vai forçar a reordenação da tabela.
Um cenário plausível para usar a ordenação decrescente poderia ser onde você faz poucos inserts mas costuma fazer muitos selects sobre os valores mais novos
Exemplo: Você tem um registro de reuniões em que vc compareceu e cria um índice ordenado pela data. Eventualmente uma nova reunião é inserida e você costuma apenas usar um select para retornar as reuniões da última semana.
Como sempre em SQL tudo depende. Na dúvida faça um acid teste. Experimente operações de select, insert, delete, update sobre a tabela em questão usando a ordenação das duas formas e tente medir as difereças de performance. Esse é realmente o único jeito de descobrir como melhorar a performance de um índice


text:
Q: Exchanging Linkedin JSAPI Oauth Token with Ruby I'm trying to exchange an Oauth2 token from the Linkedin JSAPI for an Oauth1 token and secret. As per the docs here.
I've made the request with the js library, logged in and receive the cookie with the Oauth2 token and signature.
{
    "signature_version": "1",
    "signature_method": "HMAC-SHA1",
    "signature_order": [
        "access_token",
        "member_id"
    ],
    "access_token": "j06JXCy1EB8plWmayCdUajMB6",
    "signature": "i0HmB5LQPf8NOz",
    "member_id": "hU7xxxxx"
}

Now I'm trying to exchange the access token for an Oauth1 token server side.
According to the docs, I can post the params to:
'https://api.linkedin.com/uas/oauth/accessToken'

Including the following params:
oauth_consumer_key
xoauth_oauth2_access_token parameter
signature_method
signature

I've done this with curl and get a message saying the signature is invalid. Which it's not, I've checked as per the instructions.
So, I've been trying with the oauth gem:
  consumer = OAuth::Consumer.new(
    key,
    consumer_secret,
    {
      :site => "https://api.linkedin.com",
      :http_method => :post,
      :request_token_path => "/uas/oauth/requestToken",
      :access_token_path => "/uas/oauth/accessToken",
      :authorize_path => "/uas/oauth/authorize",
    }
  )

request_token = consumer.get_request_token
access_token = request_token.get_access_token({}, {:xoauth_oauth2_access_token => token})

And again, that gives me the damn signature invalid error!
How on earth are you supposed to exchange these tokens? I've found limited advice online for the Ruby gem.

A: I do this
consumer = OAuth::Consumer.new("[API KEY]", "[SECRET KEY]", {
    :site => "https://api.linkedin.com",
    :authorize_path => "/uas/oauth/authorize",
    :request_token_path => "/uas/oauth/requestToken",
    :access_token_path => "/uas/oauth/accessToken"
})

Then:
client = OAuth::AccessToken.new(consumer, "[OAUTH USER TOKEN]", "[OAUTH USER SECRET]")

Then you make API calls like this:
response = JSON.parse(client.get(url, "x-li-format" => "json").body)

Let me know if it helps you.


text:
Q: Importing .TXT file into an SQLite database I have currently a big amount of data that i have to populate into my application database.
Those datas are stored as formatted .txt files, and it would be suicidal to store them into my database by hand.
Here is what my .txt file look like :
ID_MODELE,MODELE,MARQUE,CATEGORIE,GENRE,CARROSSERIE,CARBURANT,BOITE <--FIELDS NAME
1,MITO 1.4,ALFA ROMEO,1,VP,BERLINE,ESSENCE,MANUELLE                 <--VALUES
2,MITO 1.4 MAIR,ALFA ROMEO,1,VP,BERLINE,ESSENCE,MANUELLE            <-- ...

The target database is an SQLite database !
If someone has a clue about how to perform something like this, i would be grateful !

A: Not sure about SQLite, but databases like mysql have import functionality. The following is for mysql: Create the table with column names from text file, simply open the table view and you will find the import icon on the toolbar.


text:
Q: MVC.Net Open a file in a new window instead of downloading My requirement is to open a file in a new window/tab upon clicking the download link. The file is always downloaded despite setting the content disposition to 'inline' as suggested in the below post.
How to open PDF file in a new tab or window instead of downloading it (using asp.net)?
My HTTP response is
HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0
Content-Type: application/octet-stream
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 5.2
content-disposition: inline;filename=FileName.pdf
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 141954

My Controller Action is as below -
public async Task<FileContentResult> Index(string fileName)
    {
        byte[] document = await getFileContent("SomePathForTheFile");
        HttpContext.Response.AddHeader("content-disposition", "inline;filename=" + document.FileName);
        return File(document, "application/octet-stream");
    }

Suggestions to make the file open automatically in a new tab/window instead of just being downloaded would be of great help! Thanks!

A: Found the answer.
2 things have to be done for the file to open in a new window -
1.content-disposition must be set to inline
2.the content type should be set to the type corresponding to the file being downloaded -
application/pdf - for pdf files
application/xml  - for xml files
application/vnd.ms-excel - for xls files and so on.

A: Try the following code.
@Html.ActionLink("Home","Index",null,new { @target="_blank" })

Since we are returning to the view mode, there is no need to mention about header response
public async Task<FileContentResult> Index(string fileName)
    {
        byte[] document = await getFileContent("SomePathForTheFile");
        return File(document, "application/octet-stream");
    }


text:
Q: Separate stat_density for two density curves in ggplot2 I am trying to produce a ggplot that shows the histogram of the data as well as two density curves in which one has no adjust value and the other one has.
I tried the following code:
ggplot(df, aes_string(x=value))+
        geom_histogram(aes(y=..density..), colour="grey", fill="grey", alpha=.3)+
        geom_density(colour="red", fill="red", alpha=.3)+
        stat_density(bw="SJ", alpha=0)+
        geom_density(colour="blue", fill="blue", alpha=.3)+
        stat_density(bw="SJ", adjust=5, alpha=0)+
        theme_bw()

But this produces this graph with both curves overlapping 100%...

The .txt dataframe used is on my google drive
Thanks in advance!

A: Does adding a specific adjust argument to geom_density not do what you want?
ggplot(df, aes(x=value))+
        geom_histogram(aes(y=..density..), colour="grey", fill="grey", alpha=.3)+
        geom_density(colour="red", fill="red", alpha=.3, adjust = 1)+
        geom_density(colour="blue", fill="blue", alpha=.3, adjust = 2)+
        theme_bw()


text:
Q: Writing to text file with specific date and time in the file name I am trying to write all my data to a text file and it is working unless I put DateTime in the file name.
The current code looks like this:
string time = DateTime.Now.ToString("d");
string name = "MyName";
File.WriteAllText(time+name+"test.txt","HelloWorld");

I am getting this exception:

An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

But as far as I know, the File.WriteAllText() method should create a new file or overwrite already existed file.Any suggestions?

A: You might want to make sure that the path is valid and the datetime string does not contain invalid characters:
string time = DateTime.Now.ToString("yyyy-MM-dd");

  // specify your path here or leave this blank if you just use 'bin' folder
string path = String.Format(@"C:\{0}\YourFolderName\", time);

string filename = "test.txt";

// This checks that path is valid, directory exists and if not - creates one:
if(!string.IsNullOrWhiteSpace(path) && !Directory.Exist(path))
{
   Directory.Create(path);
}

And finally write you data to a file:
File.WriteAllText(path + filename,"HelloWorld");

A: According to the MSDN a DateTime.Now.ToString("d") looks like this: 6/15/2008(edit: depending on your local culture it could result in a valid filename)
Slashes are not valid in a filename.

A: replace
string time = DateTime.Now.ToString("d");
File.WriteAllText(time+name+"test.txt","HelloWorld");

with
string time = DateTime.Now.ToString("yyyyMMdd_HHmmss"); // clean, contains time and sortable
File.WriteAllText(@"C:\yourpath\" + time+name + "test.txt","HelloWorld");

you have to specify the whole path - not just the filename

A: This is because your name would be resolving to "7/29/2015MyNametest.txt" or something else which contains an invalid character depending on the culture of your machine. The example that I gave is obviously not a valid file path. We have to remove the slashes (/). They are not allowed in file name on Windows.
See this question as a comprehensive file naming guideline on Windows and Linux.


text:
Q: ansible-playbook doesn't work inside a bash script I am not sure what is going on and hence I enquiring here as well in hopes that some of you might.
I am trying to figure out why the same one-liner will successfully connect on my remote server
ansible-playbook initial.yml -u root -e 'host_key_checking=False'

but if I run this same one-liner from inside a shell script, then I will get:
fatal: [*********]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: root@*************: Permission denied (publickey).\r\n", "unreachable": true}

I have tried with sudo and without.
The shell script is inside the same directory.
Any thoughts?

A: When you run ansible-playbook while logged in, then ansible can use the connection to your ssh key agent to enable using ssh keys to login without entering a password or passphrase.
You don't specify how you are running the script containing the command, but more often than not the point of putting it in a script is so that it can be called easily from cron. However the runtime environment from cron has no connection to an ssh key agent, and hence the login to the remote host fails.
One workaround for this is to use an authorization key without a passphrase, but you have to realize the security implications! Anyone that gets their fingers on that private key can login anywhere the public key is installed. One way to mitigate this is to use a forced command with the public key, but that's a different topic.


text:
Q: JavaScript regex that finds all comments I'm trying to strip out all comments in a sample of JavaScript using regex in JavaScript.
The regex I have is as follows:
/((\/\*+)(\*|\s)*([^]*[\*]*)(\*|\s)*(\*+\/))/g

The sample I'm running it against is:
/*basic comment*/

console.log('turtle');

/*********************
Fancy liney comment
*********************/

console.log('turtle');

/****long basic comment ****/

console.log('turtle');

/*
 *
 * Oh look, it's one of these... great.
 *
 */

For your convenience, I've created a demo of this at regex101.com.
As you can see on regex101, if you are using pearly regex (PCRE), this all works perfectly, all four comments are found and registered as matches.  However, I'm doing this in JavaScript, if you select the JavaScript flavour on regex101, you'll see that the entire block is highlighted as one single match, meaning my lovely turtle logs are killed off when I go to delete the comments.  Any help would be greatly appreciated.

A: Just to explain what is going on: the ] in [^] is interpreted as match any character that is not nothing in JS, and in PCRE, it means match a non-] (as there is another unescaped ] later in the pattern). Thus, the character class in JS is [^], and in PCRE, the character class found by the regex engine is [^]*[\*].
All you need to do is escape the ] inside the character class:
/((\/\*+)(\*|\s)*([^\]*[\*]*)(\*|\s)*(\*+\/))/g
                    ^^

The thing is, a ] inside a character class in JS regex flavor should be escaped even when it is the first character in the class. In PCRE, and most other falvors, ] does not have to be escaped when it is the first character in the character class.
See the JS demo
However, the most efficient pattern to match multiline comments is
/\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//g

See the regex demo
It will work the same in almost any regex flavor.

A: https://regex101.com/r/kI8iH7/2
It looks like PCRE and Javascript regexps treat the [^] differently.  To be honest, I don't know what I would expect that to do.  Normally in a character class, ^ at the front means to negate the class, so the class actually matches all the characters not listed.  But if ^ is anything other than the first character in the class, it matches only itself.  It seems like there's a difference of opinion between PCRE and Javascript as to what to do if ^ is the only character in the class.
In your case, you seem to have wanted it to mean "match anything", so I simply replaced that with the far more common .*.  (I also got rid of the character class following it, as there's never a need for only one thing, to be in a class by itself.  Just match the actual token, no need to match a class only containing one token.)
((\/\*+)(\*|\s)*(.*\**)(\*|\s)*(\*+\/))


text:
Q: Equations on the free monoid?? While studying a bit of Joachim Lambek's calculus and some other applications of formal languages to the study of the structure of human language, I have come accross a reference to what authors like André Lentin has developed for the study of word combinations, namely, the so-called equations on the free monoid.
Could anyone explain me what those equations on the free monoid are?
Best regards and thanks in advance.

A: You can find the definition and a presentation of the main results in the Wikipedia entry Équation entre mots which apparently has not been translated in any other language.
Let $A$ be a finite set of constants and let $\Xi$ be a finite set of variables.
A word equation is a pair $(u, v)$ of words of $(A \cup \Xi)^*$. A solution is a
map $f:\Xi \to A^*$, which extends uniquely to a monoid homomorphism from $(A \cup \Xi)^*$ to $A^*$, such that $f(u) = f(v)$.
Quoting Wikipedia, the map $f(T) = bab$, $f(X) = abb$, $f(Y) = ab$, $f(Z) = ba$ is a solution of the equation
$$
XaTZaT=YZbXaabY
$$
since $(abb)a(bab)(ba)a(bab) = (ab)(ba)b(abb)aab(ab)$.
Makanin's theorem states that deciding whether a given equation has a solution is decidable.


text:
Q: replace cells with tuple How would I get a tuple consisting of both the index element and the current element itself:
With the following code:
import numpy as np
import pandas as pd
df = pd.DataFrame([[None, 'y', None], [None, None, 'x'], ['z', None, None]],
                  index=['a', 'b', 'c'],
                  columns=['X', 'Y', 'Z'])
print(f'\n{df.to_string()}')

I get:
      X     Y     Z
a  None     y  None
b  None  None     x
c     z  None  None

What I would like is the following:
      X     Y     Z
a  None  (a,y)  None
b  None  None  (b,x)
c  (c,z) None  None

A rather crude attempt to solve this results in an error about .name:
df2 = df.mask(pd.isnull, lambda x: (x,x.name))
print(f'\n{df2.to_string()}')

A: Try using df.agg and zip and dataframe slicing
df.agg(lambda x: list(zip(df.index, x)))[df.notna()]

Out[928]:
        X       Y       Z
a     NaN  (a, y)     NaN
b     NaN     NaN  (b, x)
c  (c, z)     NaN     NaN

Note: I think NaN representation is better than None, so I keep it as NaN


text:
Q: What will happen if I say to my boss, ""I'm not going to kiss your ring and I'm not going to kiss any other part of your anatomy."? I was a bit surprized to find the line which was delivered by the former Governor of Utah, Jon Huntsman in December 5th Time magazine. It reads:
"In Fox News interview, Utahan tweaks the Donald, charges the real-estate mogul typifies "what is wrong with politics" and says "if he had any courage at all, he would be running for President." Huntsman: "I'm not going to kiss his ring and I'm not going to kiss any other part of his anatomy."
If he said simply "I'm not going to kiss his ring," he is simply saying "I'm not fawning him." But by adding "I'm not going to kiss any other part of his anatomy" I think it comes to have a smack of "pervertedness."
Maybe I'm taking his word wrong way or too serious in interpreting. But in our country, if our politician delivers literally translated words like "I'm not going to kiss his (say, his opponent's) ring and I'm not going to kiss any other part of his anatomy," in TV, he'll be frowned by audience, particularly by sensitive women, or it can lead to losing his seat in the worst case.
Is this kind of "anatomy related" rhetoric used by dignitaries just casually, or day-to-day in public and granted as a matter of course in United State?
If I said "I'm not going to kiss your ring and I'm not going to kiss any other part of your anatomy" to my boss, say, president of the company, what would be his reaction? Does he just chuckle, or fire me?

A: I didn't even think of connecting "ring" to anus... I was assuming he was borrowing the term from that tradition of kissing the King's ring as a sign of homage. (King, Godfather, Pope).

A: I'm going to assume he didn't know where his sentences would end when he started. Otherwise, I'm sure he would have employed a more appropriate neither/nor structure.
My boss would not respond until he'd had a conversation with his lawyer. Then, he would draft a document for me to sign, certifying that he had not requested any of the kissing propositions implied in my statement of rejection.

A: My boss would probably just laugh, and say, "Have another drink."
The "kiss his ring" portion of Huntsman's statement, of course, evokes kissing the Pope's ring as a sign of respect.
The "kiss any other part of his anatomy" is just Huntsman's polite way of saying that he's not going to brownnose.
As Muad'Dib notes, your boss's reaction will really depend 1) on your boss, and 2) the context in which you make such a statement.
Edit: This kind of frankness and bluntness is rare in a politician, and is but one of the characteristics that makes Huntsman an outsider among potential Republican presidential candidates. In other public arenas (entertainment or business, for example), these sorts of statements are more common, but not an everyday occurrence, especially among those who are conscious of managing their image.

A: Refusing to kiss a ring implies that you do not feel that subservient to the ringholder. As pointed out by other posted answers, it is a reference to a time when people were subject to receiving and obeying commands from their superiors (kings, popes, etc.)
Refusing to kiss other parts implies that maybe you are subservient to someone, but you refuse to engage in demeaning or distasteful actions just to please that person.
I do not know you boss, so I have no idea what sort of response it might elicit, but for me, I would play it safe and leave these words in my mouth.


text:
Q: Orthogonal basis of a quadratic module I'm studying quadratic forms and I have to prove that every quadratic module $(V,Q)$ has an orthogonal basis, where $V$ is a vectorial space on $\mathbb{K}$ and $Q$ a quadratic form on $V$. I'm following Serre's proof in "A course in Arithmetic".
Assuming that $dim(V) \ge 1$, let $x$ be a non isotropic element of $V$ and let $H$ be the orthogonal complement of the subspace $\mathbb{K}x$. Then $Q$ is non degenerate on $\mathbb{K}x$ so $x \notin H$ and $\mathbb{K}x \cap H = \{0\}$. I need to say that $V=\mathbb{K}x \oplus H$, and I know this is true when $Q$ is nondegenerate on $V$ and on $\mathbb{K}x$, but in this case I don't assume that $V$ is non degenerate. So how can I say that $dim(V)=1+dim(H)$?
Thanks for help!

A: you can first suppose that $Q$ is degenerate. Then you can write $V=V^0 \hat{\oplus} U$ where $U$ is a supplementary subspace of $V^0$. By induction you know that $U$ have an orthogonal basis and $V^0$ also (by definition). The union of both is an orthogonal basis of $V$.
Then you can prove the case with $Q$ nondegenerate :) .


text:
Q: Using Sitecore Source value to populate droplink field using Sitecore I have created a data template
Person Gender
Text : Single Line Text
Key : Number
Then I created 2 new instances of this template in Global content tree:
Global/Gender
Text = Male
Key =0
Text = Female
Key=1
After all I've created a new Data Template, called: Person
Person
Name : Single Line
Gender: DropLink (Source: /sitecore/content/home/global/gender/*)
But in instances of Person, DropLink field dosen't show me Female and Male items to select.

A: Set Source of the Gender field to the parent path:
/sitecore/content/home/global/gender

Skip the /* at the end of it.


text:
Q: play random video on each page refresh

jQuery(document).ready(function() {
  jQuery('.popup-youtube1, .popup-vimeo, .popup-gmaps').magnificPopup({
    disableOn: 700,
    type: 'iframe',
    mainClass: 'mfp-fade',
    removalDelay: 160,
    preloader: false,
    fixedContentPos: false
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />

Anand Deshpande

hello, I am using magnific popup JQuery plugin to play Youtube video in popup. here i had added single video link of youtube. when I click on the thumbnail it will play the video related to given URL.but, i want to play different video on each page refresh.

A: create an array and add video links to array then generate a random index to get video link from array

A: I hope this will help. :)
<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="css/magnific-popup.css">

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css">

    RANDOM VIMEO VIDEOS

    RANDOM YOUTUBE VIDEOS


text:
Q: Cipher.doFinal() returning part of decrypted string for a long string I am experiencing an issue when decrypting a string using sunjce :
javax.crypto.Cipher cipher =
      javax.crypto.Cipher.getInstance("AES/GCM/NoPadding", new BouncyCastleProvider());
  GCMParameterSpec spec = new GCMParameterSpec(Constants.GCM_TAG_BYTES * 8, nonce);
  cipher.init(javax.crypto.Cipher.DECRYPT_MODE, dataKey, spec);

  cipher.update(ciphertext);

  return cipher.doFinal();

if I pass the whole ciphertext to doFinal it works correctly but if I call it correctly it only returns partial string. FOr instance for the input
String jsonExample = "{\"dataType\":\"STRING\",\"strValue\":\"000000\"}";

The decrypted bytes only contain "000000" but if I use
return cipher.doFinal(ciphertext);

and remove the update so it correctly prints the original string. What might be the reason? if I pass an empty byte array to doFinal after the update it also results in the same data loss. I want to know the logic behind it, it passes for small texts but for texts of this size it simply does not work.
this is my input
String jsonExample = "{\"dataType\":\"STRING\",\"strValue\":\"000000\"}";

This is how I am printing the decrypted string
String decryptedString = new String(decrypted, StandardCharsets.UTF_8);

This is how I am passing the input string as bytes to the encrypt function
text = jsonExample.getBytes(StandardCharsets.UTF_8)

this is how I am calling encrypt
GCMParameterSpec spec = new GCMParameterSpec(Constants.GCM_TAG_BYTES * 8, nonce);
try {
  cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, dek, spec);
  byte[] ciphertext = cipher.doFinal(text);

When I use cipher.update(ciphertext) during decryption followed by cipher.doFinal() or cipher.doFInal(new byte[0]) it only returns
"000000" after  I use the returned byte[] to String decryptedString = new String(decrypted, StandardCharsets.UTF_8);
But if I directly call cipher.doFInal(cipherText) during decryption the result string I get is the original string.

A: You're not using SunJCE, you're using the BouncyCastle provider. (You are using the Sun/Oracle API -- JCA, Java Crypto Architecture -- if that's what you meant to say, but not the provider SunJCE.)
Most Ciphers in JCA return partial data from each or any update call (in either encrypt or decrypt direction), thus in general if you use update you must concatenate that value (or those values if multiple calls) plus any value returned from doFinal before using the result for anything that needs it to be complete, such as decoding UTF8. (Typically the easiest way is to .write them all to a ByteArrayOutputStream, or .put them all to a ByteBuffer, but there are other options.) However the SunJCE provider does NOT do this for GCM, in the decryption direction only, apparently because the spec (SP800-38D) calls for the plaintext not to be released if the authentication fails, which can only be determined at .doFinal time, and then it returns all the plaintext.
The Bouncy provider does 'stream' GCM decryption, arguably in violation of the spec but consistent with usual and traditional JCA behavior, so most of the data is returned from the update call with only the last few bytes from doFinal and you need to concatenate these as above -- or, as you've found, just don't use update at all: if the data all fit in one buffer when encrypting, it should also fit when decrypting.
The Bouncy provider must buffer an amount of data equal to the tag so that it can remove and verify said tag; the "small texts" where your code works -- because decrypt .update returns nothing -- will be ones up to but not exceeding your tag size, which is apparently 8 bytes.


text:
Q: Unable to debug c++ program with class implementation I am trying to setup debugging environment in visual studio and I hope I was successful in doing it,because when I am trying to debug a normal math c++ program then my break point is hitting(or first line of code as default breakpoint) but when I am trying to debug the main program with class header file name included in the main program(i.e with class object or class implementation) then my breakpoint are not hitting. Any help where I am going wrong??
#include <iostream>
#include "Sales_item.h"
using namespace std;
int main()
{
 cout<<"hello";
 Sales_item item1, item2;
 cin >> item1 >> item2; // read a pair of transactions
 cout << item1 + item2 << endl; // print their sum
 return 0;
}

This is showing in cppdgb console:

C:\Users\admin\Documents\cpp>c:\Users\admin.vscode\extensions\ms-vscode.cpptools-0.26.1\debugAdapters\bin\WindowsDebugLauncher.exe
  --stdin=Microsoft-MIEngine-In-w2a4a5fw.4hb --stdout=Microsoft-MIEngine-Out-q2oc4jsv.b14 --stderr=Microsoft-MIEngine-Error-rlvf2qhl.2bw --pid=Microsoft-MIEngine-Pid-3fayxkbu.ji4 --dbgExe=C:\MinGW\bin\gdb.exe --interpreter=mi


text:
Q: JPA calling stored procedure with argument I have this procedure in my postgreSQL database:
CREATE OR REPLACE FUNCTION getItemsForCategory(categoryId integer)
  RETURNS SETOF ITEM AS $_$
DECLARE
  result ITEM;
BEGIN
  FOR result IN SELECT *
                FROM item it
                  JOIN item_category itcat ON it.id = itcat.item_id WHERE itcat.category_id = categoryId LOOP
    RETURN NEXT result;
  END LOOP;

END; $_$ LANGUAGE 'plpgsql';

which works excellent using terminal, but I have trouble with calling it using JPA. Here is my code snippet(4 is value of argument cateforyId):
 transactions.begin();
 final StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("getItemsForCategory");
 storedProcedureQuery.setParameter(1,4).execute();
 final List<ItemEntity> itemEntityList = (List<ItemEntity>) storedProcedureQuery.getResultList();
 transactions.commit();

after running code above I receive this error:
Exception in thread "main" java.lang.IllegalArgumentException:
You have attempted to set a parameter at position 1 which does not exist in this query string getItemsForCategory

Has anyone some idea how to set the value of argument correctly? I've also tried to set parameter using 0 instead of 1, calling setParameter with others datatypes of arguments (String,Object) but everytime I am receiving familiar kind of error like the one, which is shown there. Thank you very much

A: You need to register your parameters, before setting values.
spq.registerStoredProcedureParameter("categoryId", int.class, ParameterMode.IN);

See this link.