text:
Q: Laravel 8 redirect from old URL to New URL i'm planning to change all my website URls .. i made controller and model to save all old and new url in my DB
and add this in my web.php
Route::group(['namespace'=>'Redirections'],function(){
    $redirections=App\Models\Redirections::all();
    foreach($redirections as $r){
    Route::redirect($r->from,$r->to,$r->type, 301);
    }
});

my project link is https://www.website.com/new-laravel
old link https://www.website.com/new-laravel/old
new link https://www.website.com/new-laravel/old
my problem redirect send me to https://www.website.com/old
How i can fix this problem

A: I don't think putting your redirects into a database table is the best approach. You're going to have the overhead of a database call for each redirect vs just defining your redirects in the web.php route file.
If your redirects are as straight forward as your question is suggesting, adding new-laravel after your domain root, you could do the following in your web.php route file.
// catch all routes that don't contain 'new-laravel'
Route::any('{all}', function (Request $request) {
    return redirect(url('/new-laravel/' . $request->path()), 301);
})->where('all', '^((?!new-laravel).)*$');

// create a route group to wrap and catch all your old routes
Route::group('/new-laravel', function () {
  Route::get('/old', function () {
    ...
  });
});

So trying to access website.com/old will redirect to website.com/new-laravel/old without the overhead of a database call.


text:
Q: Move elements to the right Javascript I have an array with 5 values. I want to cycle through the array so that the values index all increase by one and the item in the final position moves to the front of the array. So for example:
[1,2,3,4,5]

Would become:
[5,1,2,3,4]

In python it is as simple as this:
lst = [1, 2, 3, 4, 5]
lst = lst[-1] + lst[:-1]

However I am not able to figure out how to do this in javascript
What is the correct syntax for performing this in javascript?

A: One way to do it would be like this:

const test = [1,2,3,4,5];

test.unshift(test.pop());

console.log(test)

A: You can use pop to get the last entry from the array, and unshift to push it on the front:
array.unshift(array.pop());

Live Example:

const array = [1,2,3,4,5];
console.log("before", array);
array.unshift(array.pop());
console.log("after", array);
.as-console-wrapper {
    max-height: 100% !important;
 }

Going the other way, shift shifts the array over and gives you the first entry, and push adds to the end.
array.push(array.shift());

Live Example:

const array = [5,1,2,3,4];
console.log("before", array);
array.push(array.shift());
console.log("after", array);
.as-console-wrapper {
    max-height: 100% !important;
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set bash next bash operation input equal to the output of the prvious operation? I believe it is really easy, but I didn't find anywhere an answer for me. What I'm trying to do is:
echo file.war | sed s/.war// | rm -rf ???

to pass to the rm -rf the output of the sed command.
Not sure if it is the right way to get this...
Thanks for your help in advance!

A: This is what 'xargs' does.
echo file.war | sed s/\.war$// | xargs rm -rf

And note my changes to your regex. It needs to be anchored and the '.' needs to be escaped.

A: Other possibilities, in bash:

*

*Use command substitution:
rm -rf $(echo file.war | sed 's/\.war$//')

*Use a variable and shell parameter expansion:
file=file.war
rm -rf "${file%.war}"

*Instead of the echo | sed, use a here-string (and the command substitution):
rm -rf $(sed 's/\.war$//' <<< "file.war")

This was in fact just to show you the command substitution $(...) thing (avoiding xargs that will fail miserably if you have file names containing funny symbols like spaces). Also to show you that in your case, sed is useless (thanks to the shell parameter expansion) and, if you really need sed, that the echo | sed thing can be avoided in bash.
I don't know what exactly you're trying to achieve. I could imagine:

*

*you're trying to delete all files file such that file.war exist in current directory. In this case, I would do:
for file in *.war; do
    rm -rf -- "${file%.war}"
done

*You have a file called filenames that contains lines like:
file1.war
file2.war
...
filen.war

and you want to delete all files file1, file2, …, filen. Then I would do:
while read -r file; do
    [[ ( $file = *.war ) && ( -f $file ) ]] || continue
    rm -rf -- "${file%.war}"
done < filenames

A: An alternative approach is
rm -rf `echo file.war | sed s/\.war$//`


text:
Q: I have 15 minutes to present ASP.NET MVC to my colleagues. What topics should I focus on? I've been using ASP.NET MVC for personal projects since before it hit RTM.
I am preparing a presentation for my colleagues to introduce them to basic concepts of ASP.NET MVC and show them how it could be used in our environment.
My presentation has a 15 minute limit. There is a lot of information to relay (especially if you factor in projects like MVCContrib and various blog posts).
What topics should I focus on?
Some context: I work for a digital agency. My colleagues are .NET developers with 3+ years of ASP.NET experience.
What's been suggested so far:

*

*Reasons for wanting to switch to ASP.NET MVC

*Routing

*ActionResults (ability to serve different responses)

*Request-Response internals

*Testability

*Scaffolding (T4 templates)

*Fine-grained control over HTML output

*Separation of concerns ()

*Differences between ASP.NET WebForms and ASP.NET MVC

A: You only have time for 2 or 3 main points.
The most important concept to grasp is that requests arrive at controllers then the controller chooses what view to present the results the controller has generated.
The next important concept is that MVC has its big win over the "classic" ASP.NET when you create unit tests for your controllers and the model.  Without this MVC is just another way to skin a cat.
For a final point I would focus on the structure of URLs not because its that important but because we like things that have a clean feel and MVC Urls can do that, this may help generate a positive response.
Avoid going on about there being no server controls (which isn't entirely true) since that is likely to elicite a negative response.  In general avoid mentioning what is doesn't do compared with ASP.NET forms (although there not being any need for Viewstate is worth mentioning in passing).  You know that the benefits out weigh the things that are missing (or unnecessary) but your audience does not.  Keep it positive.

A: *

*Routing

*The flexibility of ActionResults

*Hooking up different Views to the same Controller Action (i.e. a Mobile view)

The big Topic of Unit Testing may be too big for a 15 Minute meeting, but if your developers are already using TDD I would add it

A: I had to write report for my boss justifying why I wanted to use MVC over webforms/ Nettiers. I blogged my report http://ivida.co.uk/2011/05/11/mvc-nhibernate-vs-webforms-nettiers/
I realise you've only got a short time span but you may find some ideas from the list below....

*

*Benefits of MVC

ASP.MVC was written in response to criticisms of Web Forms in relation to other development platforms. Whilst Web Forms gives developers a Rapid Application Development framework and was written to 'mimic' the development methods used in Win Forms, it made it difficult to implement certain practices implemented in other platforms and seen as fundamental to good development.
1.1.Testable
MVC allows automated unit and integration tests to be written. This has a number of distinct advantages.
a)     Greatly reduces the need for manual testing; the upfront cost of creating unit tests is paid back downstream by significantly reducing the amount of manual testing.
b)     Can be run throughout the development; this is invaluable as it allows the developer to be sure they aren't introducing breaking changes to the code base.
c)     Gives the developer the confidence to implement changes to the code base as tests will show any bugs.
d)     Leads to a much more rigorous code base as the code has been testing numerous times throughout the development rather than that afforded by sporadic manual testing.
e)     Each test is a FUNCTIONAL requirement encapsulated in code. If there is a requirement that only users with role X can perform activity Y, the test is evidence that this requirement is being met. This becomes invaluable should a developer return to a code base after a period of time as the requirements are directly viewable by running the tests.
A developer can write as little or as much test code based upon the requirements of the project. If a project is exposed to changes in specification then having tests in place significantly speeds up the implementation of changes. For small lower impact developments, automated testing could be scaled back to cover mainly Create/ Update and Delete scenarios rather than Read scenarios.
Writing tests is an art in its own right and one that a developer becomes better at over time. Without writing any test code an experienced developer could create a project using MVC or Web Forms in a similar time. Writing tests would add perhaps 20% to development time, but reduce any time for system testing considerably.
Having tests in place also considerably reduces the time taken to implement changes and if a change is significant may actually allow that change to take place where it would otherwise be seen as either too risky or too time consuming.
1.2.Adheres to principles of good software design
ASP.MVC follows certain well trodden principles of designing good and maintainable software, such as:
"Don't Repeat Yourself (DRY)
"Separation of Concerns" (SoC)

Separation of concerns (not mixing UI logic with underlying behaviour) is a fundamental principle that exists to help developers deal with complexity. Mixing different responsibilities within the same object or files (like putting most of your logic in code behind files such as handling edit, cancel and edit post back events) invites maintenance problems and makes that code difficult to change and difficult to read. MVC prescribes where certain types of objects should be written making the resulting code base much cleaner and easier to follow.
1.3.MVC is prescriptive
Because MVC follows good software design principles it is prescriptive about where certain types of code should be developed. This is useful in a team environment in that it standardises project structures much more than in Web Forms. Once developers are familiar with an MVC project structure it becomes obvious where to look for certain types of code. This will make it easier to work on other developer's code; a) because of the prescription and b) because running the unit tests will ensure that additional developers aren't breaking existing functionality. It also helps developer make decisions about where certain types of code should be developed and how code should be separated to allow for easier maintenance. The prescriptive nature an MVC project has also proved useful by allowing the developers in this team to talk about issues and problems they face without having to know the detailed implementation of the project.
1.4.MVC enables easy integration with JavaScript frameworks
Since the launch of Google Suggest in 2004 there has been a sea change in client side web development. This change has been about the implementation of AJAX functionality. AJAX (shorthand for Asynchronous JavaScript and XML) is a group of related techniques used on the client side, to create rich interactive and responsive web applications. With AJAX, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behaviour of the existing page. AJAX uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with, the information presented.
This type of functionality used to be a fairly difficult to programme due to the varying implementation of standards compliance across browsers. This has now become less of an issue a) due to better standards compliance and b) more significantly due to the development of JavaScript frameworks such as JQuery that allow you write code that works on every browser.
The 'V' in MVC, stands for 'View' and deals only with the front end delivery of HTML and JavaScript. MVC allows the easy integration with JS frameworks such as JQuery and greatly simplifies the creation of rich client side experiences using such frameworks. (Note JQuery now ships as standard with ASP.NET 2010 and Microsoft are now actively and perhaps belatedly contributing to the JQuery code base).
This simplified integration makes it easier to develop user experiences that match the performance users expect on a modern web site. This is a subtle point but is one that I believe we shouldn't ignore. Our clients will increasingly develop implicit expectations about how they interact with websites based on their use of the wider internet. There are now very few commercial sites that don't implement AJAX functionality and the slick responsive interface that it affords. Not looking at developing rich front ends, will increasingly make our output compare disfavour-ably with our clients expectations.
1.5.Consumption of the web is changing (fast)
Morgan Stanley predicts that more people will access the web using mobile devices than using fixed internet / desktop by the middle of 2013 (i.e. within 2 1/2 years).
(http://gigaom.files.wordpress.com/2010/04/mobile-chart2.png)
What's this got to do with MVC? I believe that MVC is a better platform to deliver content to a variety of devices due to its easier implementation of JS libraries and the ease with which it allows the developer to control the contents of the HTTP response (explained in detail below).
1)     Easier implementation of AJAX – a 3G connection on a mobile device doesn't currently have bandwidth comparable with broadband. AJAX greatly improves the performance of pages over slower connections as you only return the required data (which is formatted by the browser) rather than the data and the entire page.
2)     MVC gives the developer much greater control over the data returned from a request. This is best seen with actual code examples but within two lines of code a developer can return an entire page (with Master Page etc), JSON (JavaScript Object Notation) which is the data format of choice in AJAX requests, XML or any other format required.
Code sample:
//Try doing this in webforms

If (IsJson)

{

return this.JSON(model);

}

Else if (IsXml)

{

return new XMLResult(model);

}

else

{

return View(model)l;

}

This level of control is much more difficult to achieve using Web Forms. Having tight control over what is returned in the HTTP response simplifies development of content for a range of devices such as for traditional browsers or Smart phone apps, or for applications that sit within other platforms such as SharePoint.
2.1.1.6.MVC uses RESTFul URL's
MVC gives the developer full control over the URL. With WebForms the URL matches the underlying file structure of the code. With MVC you have what's known as a 'Route Registrar' which is a file that matches URL's to the resources that will deal with the request.
There are two distinct advantages of having full control over the URL:
i)      If a project has a requirement for human readable URL's or search engine optimisation then URL control is a big advantage. Consider the following:
www.mywebapplication.com/users/alex.hardman  (i.e. Retrieve user with name alex.hardman)
as opposed to
www.mywebapplication/users/getuser.aspx (name passed in session) or www.mywebapplication/users/getuser.aspx?username =alex.hardman
The first URL (via MVC) is more human readable and search engine friendly (e.g. all things equal would be ranked higher by all the main search engines).
ii)     The second advantage with having full control over url's relates to the current drive in Digital Humanities research for data preservation. Without going into too much detail one aspect of data preservation involves the creation of "permanent url's" and "unique resource identifiers" (uri's).  The standard use of session variables and view state in web forms means that the same url can refer to a multiple items of data (where query parameters are input via view state). The result is that data accessed in this manor data doesn't have a unique resource identifier (i.e. a unique address on the web). This means data items can't be referenced as it doesn't have a unique address on the web and prevents its inclusion in Linked Data initiatives and other research initiatives requiring a URI.
The combination of URI and the ease at which a system can return computer readable data formats such as XML (see above) puts a developer at an advantage when it comes to best practice in Humanities data curation and preservation techniques. At the recent Oxford 'Research databases in the humanities – where next?' workshop there was a strong emphasis upon curating Humanities research data with uri's, and computer readable data formats. This is something that we could 'sell' as distinctly advantageous to our research clients.

A: Check out the ASP.NET MVC Training Kit.
It includes a pre-canned (albeit 60 minute) presentation that you can hack around with.
It focuses on:

*

*Seperation of Concerns

*Testability

*Control

I actually did something similar (although it was about 45 - 60 minutes including demo) just before this came out, and the key take home for us was really:

It gives you back control of the HTML mark-up.

The testability etc was fairly understood already, but that was seen as a key benefit over standard ASP.NET.

A: You've gotten all sorts of points - my question is, why do you think you want to use it in the first place, and how do you think it will help you and the rest of the development team in your environment?  The bullet points are useless if they don't apply to your situation.

A: Explain them that:

*

*There are no server controls anymore

*There is no event-mechanism anymore

*There is no ViewState anymore

*Now they won't get away with comfortable WebForms and will have to learn the basics of HTTP, HTML/CSS and JavaScript
Prepare some medicines for those who will faint.
(5). Now it is not about pages, but about resources (REST model). URL will not point to a physical file (.aspx) but to a controller action which may serve back different kinds of responses - a page to render, a short xml as an Ajax response etc.
P.S. If you have something like company-internal framework which facilitates many common operations and it is built with WebForms, you will likely not persuade them to adopt MVC since it means lots of work, dramatic changes in the thought patterns and likely a significant amount of time/costs.
EDIT: For those who asked for positive points...
(6). SEO-friendly Urls out of the box, without the need for third party utilities for Url rewriting.
(7). Complete control over your HTML output. No ViewState payload, no injection of auto-generated IDs => clean markup + smaller pages sizes => less traffic consumption + shorter response times.
(8). A possibility for a clean transparent design of an application (even with multiple layers). Instead of hacking with each control separately in code behind, you are in a better position now to design an architecture with understandable and traceable flow of data - from the database layer over business logic until it reaches the view. Much better compared to ubiquitous WebForms coding style when each control goes directly into the database to get some data to display. Not necessarily that you manage a clean design, but at least the MVC concept makes it cleaner for you now how to do it right.

A: I'd grab their attention with routing, that's the most obvious stuff (and it is not confined to MVC). I'd then look at the higher level view and talk about separation of concerns, testability and mockability.
If I were you I'd head over to ScottGu's blog and use his excellent material:-)

A: The best way to do this is follow ScottGuthries Sample Chapter in Professional ASP.NET MVC 1.0, where he's given a walkthrough of developing a full-fledged web application using ASP.NET MVC with all features. You can summarize that chapter in 20 minutes.

Download the Sample Chapter By Scott Guthrie Here!
LinkText: http://www.wrox.com/WileyCDA/Section/id-321793.html
Hope this helps.

A: If they have been using ASP.NET they might not be familiar with the MVC architecture to begin with and you might have to talk about that a little bit.
Since they are all developers and you have only 15 minutes, I would suggest you show them File > New for ASP.NET MVC project and briefly talk about the scaffolding. That's a big sell for MVC in that it works off the go and you are already set up for iterative development.
After that you could switch to a working demo of a simple application. For this I would step through the application with a debugger from routing in global.asax to controller action to model and eventually back up to the view. This will bring up interesting questions and explain the new application life cycle including SoC, MVC, L2S, etc. This will also implicitly highlight the differences between ASP.NET MVC and ASP.NET applications.
If you have wfetch (or Fiddler or Live HTTP Headers) then I would show the client side request as well and highlight the absence of view states and highligh the POST/GET verbs (PUT/DELETE if you are using wfetch). Maybe mention the usefulness of this in AJAX apps.
Anticipate questions on how to migrate the current app and what the value proposition is for your current use-case scenarios.

A: A blog in 15mins :-). Seriously, maybe focus on the seperation of concerns ?

A: Ofcourse the first and most important thing is separation of concepts, which gives:
1.More transparent design which is easier to understand and manage.
2.Convention over configuration. Which speeds up development and reduces coding/design practice differences among developers.
3.Development patern already weaven into application design itself:
You develop models, then controller, then views. Change and test them separately(maybe with dedicated developers).
But let me say if they given you only 15 minutes they really dont want to hear about it or use it for that matter ;)

A: I think that generally best approach when you want to present some new technology is to make a simple example that will explain some of the cool features.
You can create example of simple mvc application with 2 different views of the same page and 2 different controllers. One controller you can use for async operations and second for normal requesting. One view can be normal view, second view can be view optimized for mobile phones. It is few hours of work and with this example you can cover all of the cool features of asp.net mvc:
-routing
-testability
-flexibility and Separation of Concern
cheers

A: In reality 15mins isn't enough to really drill into any of the benefits you get out of MVC. I'm guessing the person you working with is most familiar with Asp.net Web Forms. Without digging too design patterns and why MVC is great, the most comprehensible thing to go over will be easy use of Ajax.
1. jQuery – Ajax
2.  Routing – SEO and No need for Custom URL rewriting
3.  Partial-View – showing tabular data and use server-side Ajax to sort and a client side example using jQuery

Most often when I go into shops that have been developing Web Forms the most common question is where are my controls; more specifically where is the repeater or datagrid? Putting together this type of demo would give as much as you can in 15mins and answer the more common questions.


text:
Q: saving file in alfresco with Version and Download the latest version I work with alfresco Community 4.0 and I used this jar alfresco-web-service-client-4.0.d.jar
using this code I can save my test.pdf file in alfresco :
File file = new File("C:/test.pdf");

  saveAttachement(file,"test.pdf", "/app:company_home/cm:MyFolder",
                        "admin", "admin")

                         public String saveAttachement(File file, String name, String folderName, String userName, String pwd)
        throws Exception {

        byte[] contentByte = IOUtils.toByteArray(new FileInputStream(file));

        // Start the session
        AuthenticationUtils.startSession(userName, pwd);

        try {
            // Create a reference to the parent where we want to create content
            Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
            ParentReference companyHomeParent = new ParentReference(storeRef, null, folderName, Constants.ASSOC_CONTAINS, null);

            // Assign name
            companyHomeParent.setChildName("cm:" + name);

            // Construct CML statement to create content node
            // Note: Assign "1" as a local id, so we can refer to it in subsequent
            //       CML statements within the same CML block
            NamedValue[] contentProps = new NamedValue[1];
            contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name);

            CMLCreate create = new CMLCreate("1", companyHomeParent, null, null, null, Constants.TYPE_CONTENT, contentProps);

            // Construct CML statement to add titled aspect
            NamedValue[] titledProps = new NamedValue[2];
            titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, name);
            titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, name);

            CMLAddAspect addAspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");

            // Construct CML Block
            CML cml = new CML();
            cml.setCreate(new CMLCreate[] { create });
            cml.setAddAspect(new CMLAddAspect[] { addAspect });

            // Issue CML statement via Repository Web Service and retrieve result
            // Note: Batching of multiple statements into a single web call
            UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
            Reference content = result[0].getDestination();

            // Write some content
            ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();

            //String text = "The quick brown fox jumps over the lazy dog";
            ContentFormat contentFormat = new ContentFormat("text/plain", "UTF-8");
            Content contentRef = contentService.write(content, Constants.PROP_CONTENT, contentByte, contentFormat);
            System.out.println("Document are created successfully. UID:= " + content.getUuid());

            return content.getUuid();
        } catch (Throwable e) {
            System.out.println(e.toString());
        } finally {
            // End the session
            AuthenticationUtils.endSession();

            //System.exit(0);
        }

        return null;
    }

after saving this file in alfresco I have this id d7633eff-8595-4d6c-8c18-a29a656607ba
it will be used later to download this file
This is the download code :
ContentResult contentResult = getContentsById("d7633eff-8595-4d6c-8c18-a29a656607ba", "admin", "admin");

       public ContentResult getContentsById(String contentId, String userName, String pwd)
        throws Exception {
        ContentResult contentResult = new ContentResult();

        // Start the session
        AuthenticationUtils.startSession(userName, pwd);

        try {
            Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
            ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();

            Reference contentReference = new Reference(storeRef, contentId, null);
            Content[] readResult = null;

            try {
                readResult = contentService.read(new Predicate(new Reference[] { contentReference }, storeRef, null), Constants.PROP_CONTENT);
            } catch (ContentFault e) {
                e.printStackTrace();
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            if ((readResult != null) && (readResult[0] != null)) {
                Content content = readResult[0];
                ContentFormat cnf = content.getFormat();
                Reference ref = content.getNode();

                String[] splitedUrl = content.getUrl().split("/");
                String name = splitedUrl[splitedUrl.length - 1];

                InputStream is = ContentUtils.getContentAsInputStream(content);
                byte[] contentByte = ConvertUtil.convertInputStreamToByte(is);

                contentResult.setName(name);
                contentResult.setMimetype(cnf.getMimetype());
                contentResult.setId(ref.getUuid());
                contentResult.setUrl(content.getUrl());
                contentResult.setPath(ref.getPath());
                contentResult.setContentByte(contentByte);
                System.out.println(" document has been retrieved");
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            // End the session
            AuthenticationUtils.endSession();

            // System.exit(0);
        }

        return contentResult;
    }

currently I change the test.pdf  file content  without changing the file name
        and I put it in another location in the disc.
This is the new file location.
C:/version/test.pdf
So in the disk I have two files with the same name but with different content.
my goal is to save the new file in alfresco but using versioning.
in my opinion I must use the old id  which is saving in alfresco : d7633eff-8595-4d6c-8c18-a29a656607ba
so I should develop a method that takes as a parameter the new file and the old id
like this
 File file = new File("C:/version/test.pdf");

  saveWithVersionAttachement(file,"d7633eff-8595-4d6c-8c18-a29a656607ba","test.pdf", "/app:company_home/cm:MyFolder",
                        "admin", "admin",)

                         public String saveWithVersionAttachement(File file,String oldId, String name, String folderName, String userName, String pwd)
        throws Exception {
 .............
 .............

in my opinion this method must save the new file in alfresco like this test_2.pdf or test_v2.pdf ..
so the two files are saved in alfresco and having the same id
and in the download method  I want to have the latest version.
so I must change the method getContentById ("d7633eff-8595-4d6c-8c18-a29a656607ba", "admin", "admin");
in order to return the latest version which is test_2.pdf or test_v2.pdf ...
I tried unsuccessfully to work with OpenCMIS using alfresco-OpenCMIS-extension-0.7.jar
I added this lines in Alfresco\tomcat\webapps\alfresco\WEB-INF\classes\alfresco\model\contentModel.xml
<mandatory-aspects>
<aspect>cm:versionable</aspect>
</mandatory-aspects>

also I added   this line version.store.enableAutoVersioning=true
in Alfresco\tomcat\shared\classes\alfresco-global.properties
is there anyone who can help me to solve my problem
UPDATED :
I work with CMIS :
I try with this code :
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.data.ContentStream;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.commons.io.IOUtils;

     public void saveVersioning(File file, String filename, String userName, String pwd, String docId)
            throws Exception {

            SessionFactory factory = SessionFactoryImpl.newInstance();
            Map<String, String> parameters = new HashMap<String, String>();

            // User credentials.
            parameters.put(SessionParameter.USER,userName);
            parameters.put(SessionParameter.PASSWORD, pwd);

            // Connection settings.
            parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
            parameters.put(SessionParameter.ATOMPUB_URL, "http://localhost:9080/alfresco/service/cmis"); // URL to your CMIS server.
            parameters.put(SessionParameter.AUTH_HTTP_BASIC, "true" );

            // Create session.
            // Alfresco only provides one repository.
            Repository repository = factory.getRepositories(parameters).get(0);

            Session session = repository.createSession();

             // Get the contents of the file
            Document doc = (Document) session.getObject(docId);
            ContentStream contentStream = doc.getContentStream(); // returns null if the document has no content
            if (contentStream != null) {

                    String mimetype = "text/plain; charset=UTF-8";
                    String content = "";

                    if (contentStream != null) {
                        filename = contentStream.getFileName();
                        mimetype = contentStream.getMimeType();
                        content = getContentAsString(contentStream);
                        System.out.println("file name "+filename);
                        System.out.println("minetype "+mimetype);
                        System.out.println("content "+content);
                    }

                    byte[] buf = IOUtils.toByteArray(new FileInputStream(file));
                    ByteArrayInputStream input = new ByteArrayInputStream(buf);

                    contentStream = session.getObjectFactory().createContentStream(
                            filename, buf.length, mimetype, input);

                    System.out.println("Document version history");
                    {
                        List<Document> versions = doc.getAllVersions();
                        for (Document version : versions) {
                            System.out.println("\tname: " + version.getName());
                            System.out.println("\tversion label: " + version.getVersionLabel());
                            System.out.println("\tversion series id: " + version.getVersionSeriesId());
                            System.out.println("\tchecked out by: "
                                    + version.getVersionSeriesCheckedOutBy());
                            System.out.println("\tchecked out id: "
                                    + version.getVersionSeriesCheckedOutId());
                            System.out.println("\tmajor version: " + version.isMajorVersion());
                            System.out.println("\tlatest version: " + version.isLatestVersion());
                            System.out.println("\tlatest major version: " + version.isLatestMajorVersion());
                            System.out.println("\tcheckin comment: " + version.getCheckinComment());
                            System.out.println("\tcontent length: " + version.getContentStreamLength()
                                    + "\n");
                        }
                    }
                }

        }

    private static String getContentAsString(ContentStream stream) throws IOException {
        StringBuilder sb = new StringBuilder();
        Reader reader = new InputStreamReader(stream.getStream(), "UTF-8");

        try {
            final char[] buffer = new char[4 * 1024];
            int b;
            while (true) {
                b = reader.read(buffer, 0, buffer.length);
                if (b > 0) {
                    sb.append(buffer, 0, b);
                } else if (b == -1) {
                    break;
                }
            }
        } finally {
            reader.close();
        }

        return sb.toString();
    }

I call this fonction using this code :
File file = new File("C:/version/test.pdf");

saveVersioning(file, "test.pdf","admin","admin","d7633eff-8595-4d6c-8c18-a29a656607ba");

I used this jar :
chemistry-opencmis-client-api-0.13.0.jar
chemistry-opencmis-client-bindings-0.13.0.jar
chemistry-opencmis-client-impl-0.13.0.jar
chemistry-opencmis-commons-api-0.13.0.jar
chemistry-opencmis-commons-impl-0.13.0.jar
commons-io-1.4.jar
slf4j-api-1.7.5.jar
stax2-api-3.1.4.jar
woodstox-core-asl-4.4.0.jar

but when I try to test  I have this error :
Caused by: java.lang.NoClassDefFoundError: org/apache/chemistry/opencmis/client/api/SessionFactory
.............
............
Caused by: java.lang.ClassNotFoundException: org.apache.chemistry.opencmis.client.api.SessionFactory
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    ... 124 more

A: The fastest and easiest way to achieve that is to leverage the RESTfull API
This will also ensure compatibility with new versions of alfresco.
Note that you need to provide the noderef for the document to update in the form property updatenoderef and that the property majorversion is a boolean flag to specify if the new version is a minor/major version of the document.
Here is a sample code that might help you with your usecase:
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost(<alfresco-service-uri>+"/api/upload?alf_ticket="+<al-ticket>);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("username", "<username>", ContentType.TEXT_PLAIN);
        builder.addTextBody("updatenoderef", <noderef>, ContentType.TEXT_PLAIN);
        builder.addTextBody("...", "...", ContentType.TEXT_PLAIN);
        builder.addBinaryBody("filedata", <InputStream>, ContentType.DEFAULT_BINARY, <filename>);
        HttpEntity multipart = builder.build();

        uploadFile.setEntity(multipart);

        CloseableHttpResponse response = httpClient.execute(uploadFile);

        String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        JSONObject responseJson = new JSONObject(responseString);
        if (response.getStatusLine().getStatusCode()!=200){
            throw new Exception("Couldn't upload file to the repository, webscript response :" + responseString );
        }

Note 1: You need to replace these tockens <*> with your own values/vars
Note 2: If you have problem retrieving a ticket, check this link, or this one

A: If you enable the versioning as you already did, you need only to update the document with the new binary and the new name. Alfresco will take care of the versioning. The get method will retrieve the last version.
This link describes how to update a document using CMIS
I do not think that you need to modify the get method.


text:
Q: Can't invoke git-svn from command line I just installed git on my linux machine (Kubuntu distro) by running the following command:
sudo apt-get install git-core git-doc gitweb git-gui gitk git-email git-svn

I would like to migrate a project which currently uses subversion to git. But if I run git-svn I get the message : git-svn: command not found
Any way to fix this?
Thank You.

A: sudo apt-get install git-svn

This command does it all in Ubuntu. Your distro (example yum install) can probably do it.

A: The (new) interface to run git-svn is actually:
$ git svn <command> [options] [arguments]

(notice the lack of -)


text:
Q: how can I list a certain user's activity in a branch Given a branch name  and a user id, I'd like to know what the guy have done to the files in the branch, how should I do ?
thanks.

A: You can use a query with find:
cleartool find . -user aUsername -type f -branch "brtype(aBranchName)" -print

Note: Fisheye has:

*

*only alpha support for ClearCase (since July 2009, see ticket 248)

*had no support before that (see this thread)

*requires large system resources which makes it impracticable for large Vobs.

A: Use a tool like Fisheye. It gives you all kinds of metrics on individual users.


text:
Q: CocoaAsyncSocket processing hex values I'm using CocoaAsyncSocket to process a fixed length header message. My node implementation is as follows
   var output = "\xA5\xA5" + jsonStr;
   socket.write(output);

I intend to read the header first (\xA5\xA5) and then process the body of the message.
The problem that I have is that I've noticed that A5 takes 4 bytes to be represented in iOS. So when I read 2 bytes I receive c2a5.
CocoaAsync reading code
socket?.readDataToLength(2, withTimeout: -1, tag: 1)

What am I doing wrong here ?. I would like to keep a fixed length header on my server side.
Any help is much appreciated.


text:
Q: How to export the virtual destructor in Xcode? I'm working on a sample project with two modules: A and B(which links to A), using Xcode 4.4.
In module A, the symbols are hidden by the compiler flag -fvisibility=hidden. I have a class whose destructor is virtual and exported:
class utx
{
    int mm;
public:
    __attribute__ ((visibility("default"))) utx(int m);
    __attribute__ ((visibility("default"))) virtual ~utx();
};

And it's implemented as:
utx::utx(int m) : mm(m) { }
utx::~utx() { }

In module B, MyUtx derives from utx as below:
class MyUtx : public utx
{
public:
    MyUtx() : utx(5) { }
    virtual ~MyUtx() { }
}Ins;

While, I always get below link error for module B:
Undefined symbols for architecture x86_x64:
    "typeinfo for utx", referenced from:
        typeinfo for MyUtx in main.o

If the utx's destructor is non-virtual, the problem goes away.

A: Have you tried:
class __attribute__ ((visibility("default"))) utx
{
  ...

According to http://gcc.gnu.org/wiki/Visibility typeinfo generation depends on whether your class has vfptr and adding virtual destructor can change that (if you have no other virtual functions).


text:
Q: Forbidding Use of Function Contained in Header File I have functions stored with a class in a header file that I #include in the header of my Source.cpp file. The header contains a date class, along with relevant constructors, overloaded operators, and methods.
I leverage these functions in some of my class' constructors (for instance, a function to convert a Gregorian calendar day into a Julian day number). However, I can't think of a valid reason to allow the use of a few of these functions outside of the header file: they're only useful to the class, after all.
Is there a way for me to make it impossible for these functions to be called outside of the header file, short of making them private methods of my class?
EDIT: Would the solution also apply to other entities in the class, like structs?

A: What you are trying to achieve is materially difficult given the nature of header files in C++.  Normally you hide internal details in a nested, anonymous namespace, however that would still be visible to callers who import your .h file.  Thus you only use this trick inside of your .cpp file to make private, non-exported symbols.
The correct thing to do is to place these private class implementations and the implementation of your constructor inside of your .cpp file.
// foo.h
namespace fooproject {

class Foo {
 public:
  Foo(::string s);

 private:
  int converted_s;  // Will be derived from constructor input
}

And then:
// foo.cpp
namespace {
  // Everything here is visible to this compilation unit only.

  int SecretMagicConverter(::string s) {
    // magic code
  }
}  // namespace

namespace foo_project {

Foo::Foo(::string s) {
  // Here we can plainly call the anonymous namespaced functions above.
  converted_s = SecretMagicConverter(s);
}

}  // namespace foo_project

Regarding your follow up, yes, anything in that anonymous namespace is 'normally' usable inside of that .cpp but hidden from any users of your .h file.


text:
Q: How can compiler optimizations affect code logic? When the same piece of code is compiled with optimizations fully disabled (g++ -O0) and then again with the optimizations fully enabled (g++ -O3), how can the logic of the source code itself be changed?
For example, compilers can

*

*unwind loops and

*do constant folding.

These two optimizations make the code perform faster without affecting the integrity of the original source code. Any code that runs without these optimizations will run with them enabled.
But, compiler optimizations can also affect code logic. Here are two examples that I know of:

*

*Removing copy constructors and assignment operators from temporaries may remove possible side-effects.

*Rearranging arithmetic containing floating point values may affect floating point error (hopefully requires -ffast-math argument).

I was very surprised, and lucky, to learn about these because they could become huge potential gotchas in the wrong situation.
So I want to know, are there any other cases where c++ compiler optimizations will affect code logic? I'm specifically looking for information about c++11 (without any undefined behaviour) under the g++ compiler, but tips for other compilers are welcome.

A: The "as-if" Rule:

An implementation is free to disregard any requirement of this
International Standard as long as the result is as if the requirement
had been obeyed, as far as can be determined from the observable
behavior of the program. For instance, an actual implementation need
not evaluate part of an expression if it can deduce that its value is
not used and that no side effects affecting the observable behavior of
the program are produced.

However, the standard mentions one optimization which is allowed, and which breaks the "as-if" rule:

When certain criteria are met, an implementation is allowed to omit
the copy/move construction of a class object, even if the copy/move
constructor and/or destructor for the object have side effects. In
such cases, the implementation treats the source and target of the
omitted copy/move operation as simply two different ways of referring
to the same object, and the destruction of that object occurs at the
later of the times when the two objects would have been destroyed
without the optimization.123 This elision of copy/move operations,
called copy elision, is permitted in the following circumstances
(which may be combined to eliminate multiple copies):
— in a return
statement in a function with a class return type, when the expression
is the name of a non-volatile automatic object (other than a function
or catch-clause parameter) with the same cvunqualified type as the
function return type, the copy/move operation can be omitted by
constructing the automatic object directly into the function's return
value
— in a throw-expression, when the operand is the name of a
non-volatile automatic object (other than a function or catch-clause
parameter) whose scope does not extend beyond the end of the innermost
enclosing try-block (if there is one), the copy/move operation from
the operand to the exception object (15.1) can be omitted by
constructing the automatic object directly into the exception object
—
when a temporary class object that has not been bound to a reference
(12.2) would be copied/moved to a class object with the same
cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the
omitted copy/move
— when the exception-declaration of an exception
handler (Clause 15) declares an object of the same type (except for
cv-qualification) as the exception object (15.1), the copy/move
operation can be omitted by treating the exception-declaration as an
alias for the exception object if the meaning of the program will be
unchanged except for the execution of constructors and destructors for
the object declared by the exception-declaration.

A: "Unspecified Behavior" is behavior where the implementation is free to choose any of the possible behaviors. In such cases, an optimizer may affect the choice made.
A simple example is the order in which arguments to a function are evaluated. Non-optimized builds could use Left-to-Right or Right-to-Left, whereas optimized builds may evaluate arguments in a "mixed" order. A good reason would be to maximize the opportunity for Common Subexpression Optimization amongst arguments.
If any of these arguments has noticeable side effects, the code logic would be altered, but whether that's a bug varies from case to case.


text:
Q: Interpretation of the monomorphism $H^2(\pi_1(X),\mathbb{Z}) \rightarrow H^2(X,\mathbb{Z})$ Let $X$ be a nice topological space and denote by $\pi_1(X)$ its fundamental group.
It is well-known that there is a well-defined map
$$
0 \rightarrow H^2(\pi_1(X),A) \rightarrow H^2(X,A),$$
where $A$ is an abelian group, seen as a trivial $\pi_1(X)$-module. I am looking for a concrete interpretation of this map.
For instance, for $A = \mathbb{Z}$, $H^2(\pi_1(X),A)$ classifies the central extensions by $\mathbb{Z}$ of $\pi_1(X)$, whereas $H^2(X,A)$ classifies the complex line bundles over $X$. I cannot see an obvious construction of a complex line bundle from a $\mathbb{Z}$-extension of the fundamental group...
Thank you very much!

A: First, let's see what is this map $H^2(\pi_1(X),A) \rightarrow H^2(X,A)$.
$\pi_1(X)$ is characterized by the following property: A set endowed with a left action of $\pi_1(X)$ is the same thing as a locally constant sheaves over $X$.
This mean in particular that there is a natural functor from $\pi_1(X)$-sets to the category $Sh(X)$ of sheaves of set over $X$. This functor is the pullback functor along a geometric morphism of toposes $X \rightarrow B\pi_1(X)$ (where $X$ denotes the topos of sheaves over $X$ and $B\pi_1(X)$ the topos of sets with action of $\pi_1(X)$.
The cohomology of the topos of sheaves is the ordinary cohomology of topological space and the cohomology of $B\pi_1(X)$ is ordinary group cohomology. So this map you are talking about is from this perspective just the natural action of a continuous map on cohomology.
Now, unless you are willing to use a description of element of $H^2(_,A)$ as sheaves of groupoid with a $BA$-action, a more explicit answer to your question is I think a bit more tricky... Indeed geometric description of cohomology class that are general enough to encompass those two kind of toposes are a bit complicated and not very easy to use in explicit situation. And the two explicit descriptions you want to use are of very different kind and uneasy to relate :

*

*The description of $H^2(X,\mathbb{Z})$ in terme of line bundle:
Let me denote by $\mathbb{C}^*, \mathbb{R}$ and $\mathbb{U}$ the sheaves of continuous function with value respectively in $\mathbb{C}^*$, $\mathbb{R}$ and $\mathbb{U}$ the group of complex numbers of module one.
This description then comes from the fact that line bundle are classified by $H^1(X,\mathbb{C}^*)$ and that when $X$ is para-compact you have $H^1(X,\mathbb{R})$ and $H^2(X,\mathbb{R})$ that are all trivial hence the exponential long exact sequence induce an isomorphism $H^2(X,\mathbb{Z}) \simeq H^1(X,\mathbb{U})$ and as $\mathbb{C}^* \simeq \mathbb{R} \times \mathbb{U}$ one has $H^1(X,\mathbb{U}) \simeq H^1(X,\mathbb{C}^*)$. All these identification are false for the topos of $\pi_1(X)$-sets so there is no way to use a similar description. Worst, the natural comparison map that always exist is in the direction $H^1(X,\mathbb{U}) \rightarrow H^2(X,\mathbb{Z})$ hence the wrong direction for associating line bundle to exact sequence... so we will at least need to use explicitly that $H^2(X,\mathbb{R})=0$.

*The description in terms of exact sequences... well there is probably dozens of way of explaining it, but anyway it boils down to very specific properties of the topos of $\pi_1(X)$-sets and there is no analogue for $Sh(X)$... except actually something like the construction of ACL's comment but that does not goes in the correct direction to answer the question.
So I don't think there an easy way to express this relation without going through a description of cohomology class that is common to the two toposes.
A first solution would be to replace the topos $B\pi_1(X)$ by a homotopy equivalent space for which the equivalence between line bundle and $H^2(Y,\mathbb{Z})$ holds, i.e. the Eilenberg Mac-lane space of $\pi_1(X)$, and this is exactly what Mathias Wendt proposed in his comment. But you will have to understand how an extension gives rises to a line bundle on the Eilenberg Mac-lane space anyway.
If one just want to compute this map, one can use a "cocycle" description:
Let $ 1 \rightarrow A \rightarrow T \rightarrow \pi_1(X) \rightarrow 1$ be a central extension.
Let $p: Y \rightarrow X$ be the universal cover of $X$ with its canonical (left) action of $\pi_1(X)$. let $(U_i)$ be an open covering of $X$ that trivialize the etale covering $Y \rightarrow X$ and for each $i$ let $V_i$ be an open subset of $Y$ such that $p$ induces an homomorphism from $V_i$ to $U_i$.
For each $i,j$ such that $U_i \wedge U_j$ is non empty there is a unique element $\gamma_{i,j} \in \pi_1(X)$ such that $\gamma_{i,j}$ induces an homomorphism between $V_i \wedge p^{-1}U_j$ and $V_j \wedge p^{-1}(U_i)$ above  $U_j \wedge U_i$. So, for example, $\gamma_{j,i} = \gamma{i,j}^{-1}$ and $\gamma_{j,k}\gamma_{i,j} = \gamma_{i,k}$ at least when $U_k \wedge U_i \wedge U_j$ is non-empty.
For each $i,j$ pick $\alpha_{i,j} \in T$ a lifting of $\gamma_{i,j}$,
And finally, for each $i,j,k$ such that $U_i \wedge U_j \wedge U_k \neq \emptyset$, let $V_{i,j,k} := \alpha_{k,i} \alpha_{j,k} \alpha{i,j}$. Then I claim that $V_{i,j,k}$ is in $A$ (its image in $\pi_1$ is trivial) and it defines a cocycle whose cohomology class does not depend on any of the choices done and is the one you are looking for (maybe up to a minus sign because I haven't been very careful).
For the special case $A = \mathbb{Z}$, whatever you do, you will need at some point to use that $H^2(X,\mathbb{R}) = 0$ in order to construct a line bundle. Maybe there is some simpler description in specific case, for example manifold, relying on specific existence results implying that $H^2(X,\mathbb{R})=0$.
Here it appears in the fact that in order to turn our $3$-cocycle with value in $\mathbb{Z}$ into a $2$-cocyle with value in $\mathbb{U}$ which will define a hermitian line bundle we need to construct first a trivialisation of it when seen as a cocycle with value in $\mathbb{R}$. This is done by using a partition of unity $\chi_i$ subordinate to the open cover $(U_i)$ we started with:
For any $i,j$ such that $U_i \wedge U_j \neq \emptyset$ let:
$$ \lambda_{i,j} = \exp\left( 2i\pi \sum_k \left( \chi_k V_{i,j,k} \right) \right) $$
give you the $2$-cocyle with value in $\mathbb{U}$ required for the construction of the line bundle.

A: If $X$ has a universal cover $\widetilde{X}$, then $\widetilde X$ is a prinicpal $\pi_1(X)$-bundle over $X$. Suppose
$$
A \to E \to \pi_1(X)
$$
is a central extension. Then, the corresponding class in $H^2(X,A)$ is the obstruction against a lift of the structure group of $\widetilde X$ from $\pi_1(X)$ to $E$.
To see this, suppose $\widetilde X$ has transition functions $g_{\alpha\beta}:U_{\alpha}\cap U_{\beta} \to \pi_1(X)$. If the open sets are small enough, they can always be lifted to $E$, but the lifts won't satisfy the cocycle condition. The error in the cocycle formula makes up a 3-cocycle $h_{\alpha\beta\gamma}: U_{\alpha}\cap U_{\beta} \cap U_{\gamma} \to A$.
Now, $h_{\alpha\beta\gamma}$ quite obviously represents the obstruction class in $H^2(X,A)$. On the other hand, above procedure takes, on the level of classifying maps, the composite
$$
X \to B\pi_1(X) \to BBA
$$
with the homotopy fibre of the central extension. And this (I assume) is your "well-known" map.
The obstruction class can be represented by a bundle gerbe, the so-called lifting bundle gerbe. The lifting bundle gerbe is a general thing: it represents the obstruction class for lifting the structure group of a bundle along a central extension.
Here, it has structure group (or band, if you like) $A$. It is constructed with the fibration $\widetilde X \to X$, and over the fibre product $\widetilde X \times_X \widetilde X$ its "transition bundle" is the pullback of $E \to \pi_1(X)$ along the difference map
$$
\delta: \widetilde X \times_X \widetilde X \to \pi_1(X).
$$
Bundle gerbes with structure group $A$ have characteristic classes in $H^2(X,A)$, and it is a little exercise to check that the class of the lifting gerbe is the obstruction to solving the lifting problem.


text:
Q: IBM Cloud COS: Using S3 API get-bucket-location returns bucket not found I'm using the S3 API for IBM Cloud COS and am getting unexpected bucket not found errors from get-bucket-location.
My bucket exists in the us-south region and shows up the s3 ls command, but getting the region is failing. I'm using the java AWS api, but can reproduce it with the aws cli.
[08:07] jwilliams:~ $ aws --profile ibm --endpoint-url https://s3-api.us-geo.objectstorage.softlayer.net s3api get-bucket-location --bucket s3-wzd-dv-integrationtest-so-1

An error occurred (NoSuchBucket) when calling the GetBucketLocation operation: The specified bucket does not exist.

[08:07] jwilliams:~ $ aws  --profile ibm --endpoint-url https://s3-api.us-geo.objectstorage.softlayer.net s3 ls
2018-12-05 10:06:00 s3-wzd-dv-integrationtest-ea-1
2018-12-05 10:04:51 s3-wzd-dv-integrationtest-so-1
2018-11-29 15:59:19 wzd-jw-bucket-1
2018-11-29 16:14:55 wzd-jw-bucket-2

A: This type of error occurs when you have created "Regional" bucket instead of "Cross-Region". You can verify the location of the bucket from the IBM Cloud console. Bucket -> Configuration would also provide you with the public URL you can use.
Depending on the region, try these:
aws  --profile ibm --endpoint-url https://s3.us-east.objectstorage.softlayer.net s3 ls

aws  --profile ibm --endpoint-url https://s3.us-south.objectstorage.softlayer.net s3 ls


text:
Q: Load NPAPI Plugin on Android device/emulator I compiled sample NPAPI Plugin which I got from this link http://code.google.com/p/npapi-sdk/
after compiling it using NDK, I got the .so file libs/armeabi/libBasicPlugin.so
after searching on Google I came across following suggestions:

*

*put .so file in /data/data/com.android.browser/app_plugins/

*put .so file in /data/data/com.android.browser/assets/plugins/

but none of that works on emulator (haven't tried on device)
I tried it on Gingerbread and ICS.

A: Plugin for webkit can't work anymore. There's a test in the PluginManager.java file (framework/core/java/webkit something like that) and allows only the plugin of flash to be loaded (only when ro.secure = 1). If you want to load the plugin you have to root your device.


text:
Q: Sorting a list of maps within before this while loop runs out(Java) A database call is made and result is a bunch of rows of two string columns of type A and B. e.g. (x_a, y_b), (x_a, y1_b), (x2_a,y_b)
The idea is to come up with a list of maps like {(x_a,{y_b,y1_b}), (x2_a,{y_b})} where the objects of type A are not repeated and to do this while pulling the results from a database.
Here's what I tried:
int i =0;
            List<String> type2 = new ArrayList<String>();
            Map<String,List<String>> type1_type2 = new HashMap<String,List<String>>();
            List<Map> list_type1_type2 = new ArrayList<Map>();

            String [] type1Array = new String[100];
            String [] type2Array = new String[100];
            int trackStart = 0;
while (res.next()){

                String type1 = res.getString(1);
                String type2 = res.getString(2);
                type1Array[i]=type1;
                type2Array[i] = type2;

                if(i>0 && !type1Array[i].equals(type2Array[i-1])){
                    int trackStop = i;
                    for(int j = trackStart; j<trackStop;j++){
                        type2.add(type2Array[j]);
                    }
                    type1_type2.put(type1Array[i-1], type2);
                    list_type1_type2.add(type1_type2);

                //debugging stuff
                 String x = list_type1_type2.toString();
         System.out.println(x);
System.out.println(" printing because "+ type1Array[i]+" is not equal to " + type1Array[i-1]);
        type2 = new ArrayList<String>();
     type1_type2 = new HashMap<String,List<String>>();
                     trackStart=i;
                     }

                     i++;

                }

This method does not work when the last type1 values of the result object are the same.
Is there a way to do this in the same spirit (within the while(res.next)) without first storing the results of the database call in separate arrays or adding an extra for loop outside the while loop to "patch it up"?

A: The simple way to do this is to use a Guava / Google Collections SetMultiMap.  This is essentially a mapping from a key (your 'A' objects) to a set of values (your 'B' objects).
[I'm not going to try to code it for you.  Your current code is too horrible to read ... unless you were paying me :-) ]
However, a better idea would be to get the database to do the collation.  If you can do that, you will reduce the amount of (redundant) data that gets send across the database connection ... assuming that you are using JDBC.

A: If you don't want duplicates like {x_a:[y_b, y_b]} then use a set as the value of your map:
Map<String,Set<String>> type1_type2;

I don't know what the other various list and arrays are for. You can probably just get by with the type1_type2 map. Process each (x, y) in pseudo-code:
Set s = type1_type2.get(x)
if s == null:
    s = new Set()
    type1_type2.put(x, s)
s.add(y)


text:
Q: how to display npx's executed binary path? I have a yarn-workspace with different packages installed different versions of the same cli tool.
assume it is called the-cli
then whe I do npx the-cli, what option can I add to make npx print out the path for executed the-cli, so I know if it is picking up the right version. kind of like which the-cli


text:
Q: can someone please explain to me the main role of claim in .net core in details and how to get information from claim? I created a policy and I need to check data in my handler,
for example userId and companyId ...
so from the claim principal named user, I need to get information from it so please how can I do that
addscraningHandler :
public class AddScreaningHandler : AuthorizationHandler<AddScreaning>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AddScreaning requirement)
    {

        var mvcContext = context.Resource as AuthorizationFilterContext;
        // get user infos
        var claims = context.User.Identities.First().Claims.ToList();
        var userCompanyId = context.User.HasClaim(u => u.Type == "id");
        throw new NotImplementedException();
    }
}

}
this is where I need the policy :
controller :
[Authorize(Policy = "AddScreaningHandler")]
        [HttpPost("newScreening")]
        public async Task<ActionResult<Screening>> createScreen(CreateScreeningDto createScreeningDto)
        {
            Screening screening = new Screening { creationDate = DateTime.Now, reflowId=Guid.NewGuid().ToString(), companyId = createScreeningDto.companyId, finished = false, lastUpdate = DateTime.Now, name = "", state = "screening-setup" };
            _context.Screenings.Add(screening);
            await _context.SaveChangesAsync();
            return Ok(screening);
        }

and this is the startup file  :
 services.AddAuthorization(options =>
            {
                options.AddPolicy("AddScreaningHandler", policy =>
                    policy.Requirements.Add(new AddScreaning()));
            });
            services.AddSingleton<IAuthorizationHandler, AddScreaningHandler>();
        }

I need to focus on my handler the addscreaninghandler and get the user information, how can I do that .
this is debugging result :
enter image description here
enter image description here


text:
Q: navigation button for second page appears on the home page I have BottomNavigationView in my android program, and even though the buttons work properly to direct to the related page, the second page appears on top of home page.
Does anyone knows what can be the possible problem?


text:
Q: @HTML extension I will keep things simple.
I have the following model :
public class Person
{
    public int Id { get; set; }
    public string FullName { get; set; }
}

I created this partial view for this model in ..\Shared\DisplayTemplates\Person.cshtml
@model BillSplitter.Classes.Person
<b>@Model.FullName</b>

In a view, the following code works great:
@Html.DisplayFor(model => model.PaidBy) //PaidBy is type of Person

Here's the extension I would like to create:
public static IHtmlString DisplayPersons(this HtmlHelper helper, IEnumerable<Person> model)
{
    string htmlString = "";
    foreach (Person p in model)
       string += helper.DisplayFor(p); //PROBLEM!

    return new HtmlString(htmlString);
}

The problem is helper does not expose the DisplayFor function.
What can I do to get the HtmlString from my partial view in this extension?

A: If you pass a collection of Person to @Html.DisplayFor, it will automatically iterate over it and display each Person using the right template :
@Html.DisplayFor(model => model.PersonList)

Assuming that PersonList is an IEnumerable<Person>, each Person will be displayed according to your DisplayTemplate, which is what you're trying to achieve with your custom HtmlHelper extension.


text:
Q: Grouping and sorting with traversal I have 2 types of nodes : City and Event
City can HOST many events, each event is hosted by only 1 city.
Events can be linked between them with a LINKED relationship (events linked can be .
I want to find for a given city, the events hosted in this city grouped by linked events.
For example :
Events happened in C1 : E1, E2, E3, E4
Events happened in C2 : Ew, Ex, Ey, Ez
Events happened in C3 : Ea, Eb, Ec, Ed

Links:
E1 -> Ew -> Ea -> E2 -> Ex -> Ey
E3 -> Eb -> E4 -> Ez -> Ec -> Ed

I'm looking for a way to return:
for C1 : [E1,E2], [E3,E4]
or for C2 : [Ew,Ex,Ey], [Ez]
or for C3 : [Eb,Ec,Ed], [Ea]

Could this be done by Traversal ?

A: Setup your sample dataset:
MERGE (E1:Event { id: "E1" })
MERGE (E2:Event { id: "E2" })
MERGE (E3:Event { id: "E3" })
MERGE (E4:Event { id: "E4" })
MERGE (Ew:Event { id: "Ew" })
MERGE (Ex:Event { id: "Ex" })
MERGE (Ey:Event { id: "Ey" })
MERGE (Ez:Event { id: "Ez" })
MERGE (Ea:Event { id: "Ea" })
MERGE (Eb:Event { id: "Eb" })
MERGE (Ec:Event { id: "Ec" })
MERGE (Ed:Event { id: "Ed" })
MERGE (C1:Location { city: "C1" })
MERGE (C2:Location { city: "C2" })
MERGE (C3:Location { city: "C3" })
MERGE (C1)<-[:HAPPENED_IN]-(E1)
MERGE (C1)<-[:HAPPENED_IN]-(E2)
MERGE (C1)<-[:HAPPENED_IN]-(E3)
MERGE (C1)<-[:HAPPENED_IN]-(E4)
MERGE (C2)<-[:HAPPENED_IN]-(Ew)
MERGE (C2)<-[:HAPPENED_IN]-(Ex)
MERGE (C2)<-[:HAPPENED_IN]-(Ey)
MERGE (C2)<-[:HAPPENED_IN]-(Ez)
MERGE (C3)<-[:HAPPENED_IN]-(Ea)
MERGE (C3)<-[:HAPPENED_IN]-(Eb)
MERGE (C3)<-[:HAPPENED_IN]-(Ec)
MERGE (C3)<-[:HAPPENED_IN]-(Ed)
CREATE (E1)-[:LINKED]->(Ew)-[:LINKED]->(Ea)
CREATE (Ea)-[:LINKED]->(E2)-[:LINKED]->(Ex)-[:LINKED]->(Ey)
CREATE (E3)-[:LINKED]->(Eb)-[:LINKED]->(E4)
CREATE (E4)-[:LINKED]->(Ez)-[:LINKED]->(Ec)-[:LINKED]->(Ed)

And here is the query to get the results:
MATCH (e:Event)-[:HAPPENED_IN]->(c:Location)
WHERE c.city = "C1"
MATCH p=(a)-[:LINKED*]->(e)-[:LINKED*]->(b)
WHERE NOT (a)<-[:LINKED]-() AND NOT (b)-[:LINKED]->()
WITH nodes(p) AS links, c
RETURN DISTINCT [event IN links WHERE
     (event)-[:HAPPENED_IN]-(c) | event.id] AS events

Results for C1:
+-------------+
| events      |
+-------------+
| ["E1","E2"] |
| ["E3","E4"] |
+-------------+
2 rows
34 ms

Results for C2:
+------------------+
| events           |
+------------------+
| ["Ew","Ex","Ey"] |
| ["Ez"]           |
+------------------+
2 rows
37 ms

Results for C3:
+------------------+
| events           |
+------------------+
| ["Ea"]           |
| ["Eb","Ec","Ed"] |
+------------------+
2 rows
38 ms

A: Perhaps you can add a visual graph model? In general if you want to start with the Java-API just use the basic methods like node.getRelationships() and then go from there.
What you would do,

*

*for each city

*get all events in that city, put them in a set

*take first event from the set

*check if there is a connection over multiple hops (e.g. using shortest-path) to the other events in the city, if so, put all connected ones into a group and remove all of those connected events from the original set (they are a cluster anyway and not connected to the other events)

*when set is empty, output the groups for the city, else continue with 3.


text:
Q: How can one model an unconditional decision in an activity diagram? For example, the user can perform action A, action B or action C in a tool. Whether they choose A, B or C, the order of these actions and how many times they are repeated is up to the user and the reason why they choose A,B or C and why they are chosen in a particular order isn't clear. Also any action can be repeated again after another action has been done by the user.
EDIT: A more concrete example would be the creation of an image. The user can draw a shape, choose a new shape, choose a new colour and save the image. While drawing these 4 actions can be performed intertwined in any random order and in any random quantity, only guided by the whims of the user.
There is also the choice of creating a new image from scratch or editing an existing image to create a new image.

A: When modelling anything using any notation, it is important to remember what the purpose of is in creating the model, and who is going to use it.
If you simply omit the guards on arcs, then the model has no information describing how the system behaves. It cannot guide another developer to create the software, it does not record the intent of the designer.
The user is outside the system boundary, so the decision as to what action to perform is elsewhere. The system behaviour should be modelled as a condition of its state, inputs or events - these are what the system can operate on, and what developers expect to find in the UML model to guide them.
The exact UML construct used will depend on how that choice is communicated across the system boundary - an activity diagram may well not be the best way of communicating that, or you might use multiple diagrams for each interaction
The software being modelled does not make an unconditional choice, and the information in the model should reflect that with enough detail to be useful to the next person viewing it.

A: Very simple solution to you question is below.

Please do not omit the guards after decision node if you don't want to have an undeterministic behaviour of your activity. Decision node offers a token to the first flow that have true guard whereas the order of evaluating of the guards is not defined.

A: Well, you just leave away the guard:

Now the path can take any way. However, since there is a choice, it's the user taking the action and choosing the path he likes.
Edit Thinking a bit about the "natural" control flow it seems obvious, that preceding the ConditionalNode you find an action like Offer choice (e.g. in the concrete example of the OP: "draw", "choose shape", "choose color", etc.). So the outcome of the ConditionalNode is one of the users choices which in turn should have an appropriate guard. So the above is merely a sketch and can be regarded as incomplete. However, presenting this sketch to a reader would either make him "aha" or ask the question that came up my mind after thinking a while. Regardless of this, there will be just one path been taken after the ConditionalNode.

A:
Normally a loop node should help you to solve your problem. If the flag isTestedFirst, the loop node is a while-do loop.

However this is not the easiest node of activity diagram.

It has three part : the setup part, the test part which is test at each iteration and the body part.
 Maybe this image extracted from sparx documentation may help you :

Hope this help and maybe someone else may provide more details.


text:
Q: Cross-origin-requests-are-only-supported-in-HTTP - On Accessing Sencha Touch Example I am new for cross platform mobile app development using HTML frameworks like Sencha. Today, I've downloaded Sencha Touch 2.3.1 and tried to open an index file in the examples folder came with the download package.
Surprisingly I couldn't see anything and my console log said
Cross-origin-requests-are-only-supported-in-HTTP

for bootstrap.json
I have seen the same error for some html files on lungo framework's examples. What could be the reason for this ?
I hope all these files will load correctly if I upload them on a server, but I will be wrapping the js file as package while building the app, so this will not work.
I am aware of the Cross Origin Policy which restricts JS to send request to different origin, but I don't understand why this is happening when I have these files locally. Please help me understand this and explain how to overcome this issue.

A: when you open the page with file:// protocol, the browser disables requests to other files. so when schena touch tries to load bootstrap.json, your browser throws that error. the solution is to host your site on a local webserver and access it through http://localhost/
I recommend appache server, wamp if you're on windows
Another answer explains


text:
Q: Using flamingo ribbon in e4 application
I just started an application using flaming ribbon technology (http://insubstantial.github.io/insubstantial/flamingo/) and it looks nice. Because the software package is growing very fast, I want to use a more flexible way to handle code and application. Looking around, I found that the e4 (eclipse rich client platform) would fit my needs. I like this plug-in technology and now I am wondering, if there is any way to integrate the flamingo ribbon technolgy into e4 applications.
I am not bounded to the eclipse rcp, but I need a plugin-framework, moveable and dockable windows and the flamingo ribbon bar. Does anyone have a recommendation or hints how to integrate flamingo into e4?
Cheers Carsten


text:
Q: Rails merge with empty relation is returning records I am trying to understand why the merge is adding more records instead of filtering the previous collection:
(byebug) ::Reporting::Entry.where(reporting_report_id: []).count
0
(byebug) ::Reporting::Entry.where(reporting_report_id: []).merge(report.entries).count
2

The actual behaviour of the merge should be to intersect. It is working correctly in this example:
(byebug) Reporting::Entry.none.merge(Reporting::Entry.all)
#<ActiveRecord::Relation []>

Here are the sql queries generated by my code:
(byebug) ::Reporting::Entry.where(reporting_report_id: []).to_sql
"SELECT \"reporting_entries\".* FROM \"reporting_entries\" WHERE 1=0"

(byebug) ::Reporting::Entry.where(reporting_report_id: []).merge(report.entries).to_sql
"SELECT \"reporting_entries\".* FROM \"reporting_entries\" WHERE \"reporting_entries\".\"type\" IN ('Reporting::IUE::ReportSection') AND \"reporting_entries\".\"reporting_report_id\" = 'df08179e-3ee9-47a5-89b4-17016d340db5' ORDER BY \"reporting_entries\".\"position\" ASC"

The policy is defined as:
If you look at the sql generated on the second query vs the first one, the merge part is causing the WHERE 1=0" to go away. Why?

A: It appears that "ActiveRecord fails to correctly merge scopes containing IN constraints on the same column."
There is an open issue on the rails repo. People are arguing about how it should behave but it hasn't gotten enough attention yet.
https://github.com/rails/rails/issues/33501
I changed my scope from:
::Reporting::Entry.where(reporting_report_id: []).merge(report.entries)
to:
::Reporting::Entry.where(reporting_report_id: []).where(report: report.entries)
and now it works as I intended, although merge should have done it.


text:
Q: I forgot my Ubuntu user login password, I reset it but have also forgotten the login for the key ring, everything else in inactive As per the original query…
I forgot my original password login for my existing user account, I reset the password in the grub root successfully but now it is asking for authentication required;
The password you use to log in to your computer no longer matches that of your login key ring.
Password:
Any help on how to reset this also?
I cannot access the terminal logged into the user as everything is inactive.
Much love to all
Ben


text:
Q: Processing videos through iMovie increases file size by 70x This is just a curiosity of mine. I screen recorded ~5hrs of video using Quicktime, split up into roughly 10-20 minute segments. The folder which I saved them to is 4.73 GB big.

However when I string those videos together using iMovie, add about 5 titles, and attempt to export a file at best quality, it estimates 332 GB!

The next step down is a lot better, but still nearly 10x bigger at 45.4 GB.

Even low quality is still more than 3x bigger than the original files
Where is all this extra data coming from?
EDIT: Even weirder, my screen recordings have no audio data, and I haven't added any in, so why is it still big when exporting audio only?

A: You have inadvertently wandered into the murky realm of video codecs.
The screen recording you made with Quicktime was initially saved using the extremely efficient H.264 compression algorithm.
H.264 is a codec optimised for distribution of video. It is designed to store video using the least possible amount of data at the cost of using a lot of CPU time to encode or decode.
If you have ~5hrs of video in 4.73GB of data, that must be encoded at ~2.1Mbit per second. This is extremely efficient compression! (for comparison, standard definition DVDs rarely pack more than 4hrs of video onto 7GB of space).
This efficiency is due to h.264 and that, unlike regular video footage, in screen recordings not much is typically changing between frames.
iMovie is optimised for working with video, not screen recordings, so the output options are tuned with that in mind.

*

*ProRes, is a close-to-uncompressed algorithm that is optimised for editing video (computationally light to decompress and scrub through at the cost of lots of disk space).

*High, will be a H.264 compression at approx 20Mbit/sec, this is a reasonable data rate for compressing HD video with good quality.
The audio option. AIFF is an uncompressed audio format. Thus it will use the same amount of data regardless of the content; even if your screen recording has no sound, it's still going to save 5hrs * 44.1 thousand zeros.


text:
Q: Populating 56 input fields in PHP / mySQL / JQuery environoment I have a form that takes 56 separate inputs and stores them across 6 tables in mySQL indexed by a unique ID generated when the form is generated.  That said, I have an edit mode that passes the UID to the form via the GET method (ie. index.php?editUID=5552d631220810).
My question is, what is the best way to assign all the values to each of the 56 inputs?  Currently I am using PHP to process a script line to assign each of the values which are set in the database like this:
<script type="text/javascript" language="javascript">
            $(function() {
            $("#salesPrice").val("7500000");
            });
</script>

But this seems like a cumbersome / not very efficient way to assign my values to their respective fields.  Is there a cleaner way to do this?  Also, if this is helpful, the names of my mySQL fields are the same as my inputs (ie. salesPrice is the name of the column in my database and the name of the index of my input field if that is useful).
Thanks for any ideas.

A: You could loop through the column names and the variables and output them to both the HTML and the Javascript
<?php

//MYSQL query goes here

for($results as $data) {

   ?>

$("#<?php echo $data->name; ?>").val("<?php echo $data->value; ?>");

<?php

}

?>

Or simply just use it with HTML and no javascript
<?php

//MYSQL query goes here

for($results as $data) {

   ?>

<input type="text" name="<?php echo $data->name; ?>" value="<?php echo $data->value; ?>">

<?php

}

?>


text:
Q: Turning off security messages for WPF XBAP applications in Internet Explorer I'm developing a WPF XBAP application. When i try to open it in Internet Explorer (9.0.8112.16421 Update version 9.0.9 KB2722913, Windows 7) every time security warning is popped up. Twice.

That's very annoying and acceptable only in developer environment, there is a need to turn them both off. Project configuration is as follows : Security - "Enable ClickOnce security settings" (when its disabled application won't run at all) - "This is a full trust application"; "Signing" - "Sign the ClickOne manifests" (with test certificate which is imported to Trusted Root Certification Authorities). In IE both internet and intranet zones have "WPF browsers applications" set to "Enable" (that may not have effect because *.xbap is loaded from file system). In case I don't have alternative ways to integrate WPF application into browser (Silverlight is not an option, there is a requirement about full .NET framework targeting) i'm looking for solution of above described problem. Thanks in advance.

A: Problem was solved via manual addition of assembly's certificate (*.pfx) to Trusted Root Certification Authorities and Trusted Publishers as described here : http://blogs.microsoft.co.il/blogs/maxim/archive/2008/03/05/wpf-xbap-as-full-trust-application.aspx


text:
Q: ESP different in /proc/pid/maps and binary I am debugging a crash and i see following behaviour -
When i attach GDb to the process and do info registers, i see the following value for esp -
esp            0xfd2475d0       0xfd2475d0
Upon doing a disassembly of code where it is crashing, i see the following -
81c886a:       c7 04 24 2c f9 8a 0c    movl   $0xc8af92c,(%esp)
and if i view maps file in /proc//maps, i see stack address range as -
fff39000-fff59000 rwxp 7ffffffde000 00:00 0                              [stack]
Clearly, value of ESP 0xfd2475d0 in GDB is not in sync with the stack address in maps file.
Can this be a reason for crash. I think it should be as i am getting SIGSEGV. Also, how do i resolve this issue?
Please assist

A: Yes, this is clearly a reason for a segmentation fault. It would be actually very unwise not to throw it, as the Intel architecture supports separate code, data and stack segments to be assigned -- and all memory access (with base register == ebp or esp) implicitly go through stack segment.
Because the compiler will use different base registers (and different implicit segment register) to read any other arbitrary pointer, this narrows the search for corruption of stack register.
The rarer possibility is stack smashing ie. accessing other stack elements than local variables in a current function scope -- in this particular case corrupting the caller's stack/frame pointer.
void foo(int *p) {
   int a[2];
   a[4] = p;
}

And the more likely option is over allocation.
 void foo() {
     double too_big[6000000];    // this would be located at 0xfd......
     int a;                      // this would be located at 0xfff3f000 ...
 }


text:
Q: Saving custom Word document using FilePicker in Windows Store app I am making a Windows Store application and I want to allow users that press an "Export To Word" button to have all the data that they have input into the app to be displayed in a Word document and saved to a desired location on their computer. The code below is a test segment of code that almost does what I am after, however after saving the document and opening it using Word rather than the app, it cannot open the file due to it being corrupted apparently. However when you open it in Notepad the text is displayed as I want.
private async void exportToWord_Click(object sender, RoutedEventArgs e)
{
    await ExportToWord();
}

private async Task ExportToWord()
{
    // Create the picker object and set options
    Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();

    savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;

    // Dropdown of file types the user can save the file as
    savePicker.FileTypeChoices.Add("Word", newList<string>{".docx"});

    // Default file name if the user does not type one in or select a file to replace
    savePicker.SuggestedFileName = "Test";

    Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

    MessageDialog mD;

    if (file != null)
    {
        // Prevent updates to the remote version of the file until we finish
        // making changes and call CompleteUpdatesAsync.
        Windows.Storage.CachedFileManager.DeferUpdates(file);

        // write to file
        await Windows.Storage.FileIO.WriteTextAsync(file, createContentsOfFile());

        // Let Windows know that we're finished changing the file so the other
        // app can update the remote version of the file.
        // Completing updates may require Windows to ask for user input.
        Windows.Storage.Provider.FileUpdateStatus updateStatus = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);

        if (updateStatus == Windows.Storage.Provider.FileUpdateStatus.Complete)
        {
            mD = newMessageDialog("Connect exported to:" + file, "Export Successful");
        }
        else
        {
            mD = newMessageDialog("Could not save file. Try again", "Export Unsuccessful");
        }
    }
    else
    {
        mD = newMessageDialog("Operation canceled because the file could not be found. Try  again", "Export Unsuccessful");
    }

    await mD.ShowAsync();
}

private string createContentsOfFile()
{
    return "Testing...";
}

I believe the issue is that I am outputting plain text to the Word document but it needs to be in a certain format to be output correctly and be displayed in a Word doc. Is there any way of doing this in Windows Store apps?
Any help would be appreciated.

A: I'm not aware of any Word doc components available for Windows Runtime apps (Microsoft doesn't provide one, but there could be a third party component I'm not aware of).
You can get documentation on the docx format and for simple text it may not be too complex (I'm not sure), or you can use another format which Word can open.
If you don't need formatting I'd probably stick with txt.
If you need small amounts of formatting then rtf is a good option. It is fairly simple to generate yourself or the RichEditBox can export RTF format text which you can then save into a .doc file and open in Word.


text:
Q: Stop python script aborting when there is no internet connection I have a python script running on a revPi which uses Azure IOT SDK. The script basically accepts a bunch of modbus registers from a .json file, adds a few properties and sends it to Azure IOT hub for analysis.
The script is currently too dependent on network connection and due to infrastructure limitations, the connectivity is unreliable and often causes the script to die/abort often. How can I make the script to function on this poor internet connection? The main libraries being used are pymodbus and iothub_client.

A: As per Checking network connection I'd suggest something like this;
   import urllib2

    if(internet_on())
        CallFunction()
    else
        internet_on()

    def internet_on():
        try:
            urllib2.urlopen('http://216.58.192.142', timeout=1)
            return True
        except urllib2.URLError as err:
            return False

"216.58.192.142" is a google address but you could use anything reliable such as Azure as this is where you are sending your data.
It may be more sensible to use a while loop or add a thread sleep to stop it checking so often.
Hope this helps.


text:
Q: Why aren't my nested SetTimeouts working with Internet Explorer 11? I currently have code that looks something like this:
import React from 'react';
import testimonials from './testimonials';
import {INTERVAL, FADE_OUT_ANIMATION_TIME, FADE_IN_ANIMATION_TIME} from './config';

class Carousel extends React.PureComponent {
  constructor(props) {
    super(props);
    this.startCarousel = this.startCarousel.bind(this);
    this.currentIdx = 0;
  }

  startCarousel = () => {
    this.intervalID = setInterval(() => {
      const {currentIdx, carouselContainer} = this;
      const testimonials = carouselContainer.children;
      const nextIdx = currentIdx + 1 !== testimonials.length ? currentIdx + 1 : 0;

      testimonials[currentIdx].classList.add('fadeOut');
      setTimeout(() => {
        testimonials[currentIdx].classList.add('hide');
        testimonials[currentIdx].classList.remove('fadeOut');

        testimonials[nextIdx].classList.remove('hide');
        testimonials[nextIdx].classList.add('fadeIn');
        setTimeout(() => testimonials[nextIdx].classList.remove('fadeIn'), FADE_IN_ANIMATION_TIME);
      }, FADE_OUT_ANIMATION_TIME);

      this.currentIdx = nextIdx;
    }, INTERVAL);
  }

  componentDidMount() {
    this.startCarousel();
  }

  componentWillUnmount() {
    clearInterval(this.intervalID);
  }

  render() {
    return (

 this.carouselContainer = ele} >
        {testimonials.map(renderTestimonials)}

    );
  }
}

export default Carousel;

All I'm doing is cycling through different elements being rendered inside of my carousel container, changing the classnames around every interval to trigger animations and hide/reveal elements. The interval and timeout times for reference:
export const INTERVAL = 8500;
export const FADE_OUT_ANIMATION_TIME = 800;
export const FADE_IN_ANIMATION_TIME = 1200;

This works on Chrome, Safari, Firefox, Edge, but not Internet Explorer 11. The carousel never cycles away from the first element. From what I can tell, this doesn't seem to be a CSS issue as the animations properly trigger and animate when I manually add the relevant classnames in the developer console. The [DOMElement].classList.add/remove methods seem to work fine as well. I tried manually recreating the above setInterval code in the IE11 console and it seems like there might be a problem with the nested setTimeouts in the setInterval?
From what I observed it seems like the fadeIn classname was correctly being added but the hide classname wasn't being removed except when it cycled back to the very first element in the container.
Anyone have any idea about what could be happening here? Any advice on how I could make this work as intended?

A: I think the issue is related to the currentIdx value setting, Please refer to the following code, it works well on my side:
export const INTERVAL = 8500;
export const FADE_OUT_ANIMATION_TIME = 800;
export const FADE_IN_ANIMATION_TIME = 1200;
var currentIdx =0;

  class Carousel extends React.PureComponent {
    constructor(props) {
      super(props);
    }

    startCarousel = () => {
      this.intervalID = setInterval(() => {
        const testimonials = document.getElementsByClassName("imagecontent");
        const nextIdx = currentIdx + 1 !== testimonials.length ? currentIdx + 1 : 0;

        testimonials[currentIdx].classList.add('fadeOut');
        setTimeout(function () {
          testimonials[currentIdx].classList.add('hide');
          testimonials[currentIdx].classList.add('fadeOut');

          testimonials[nextIdx].classList.remove('hide');
          testimonials[nextIdx].classList.add('fadeIn');
          setTimeout(function () {
              console.log("nested settimeout");
              return testimonials[nextIdx].classList.remove('fadeIn');
          }, FADE_IN_ANIMATION_TIME);
          currentIdx =  currentIdx + 1 !== testimonials.length ? currentIdx + 1 : 0;
      }, FADE_OUT_ANIMATION_TIME);
      }, INTERVAL);
    }

    render() {
      return (

            <input type="button" value="Start Carousel" onClick={ this.startCarousel} />

      );
    }
  }

The result as below:


text:
Q: Can't get Firefox extension logs to show up Following these instructions, I went to about:debugging -> This Firefox and clicked Inspect on my extension, which shows a console. But no logs show up there when I trigger my extension. Using the list-cookies example, I added the last two lines:
gettingAllCookies.then((cookies) => {

    //set the header of the panel
    var activeTabUrl = document.getElementById('header-title');
    var text = document.createTextNode("Cookies at: "+tab.title);
    var cookieList = document.getElementById('cookie-list');

    console.log('I can't see this log!');
    cookieList.parentNode.appendChild(document.createTextNode(Date()));

When I invoke the popup, I see the current date/time in the popup, but no log shows up in the console.
I tried setting extensions.sdk.console.logLevel and restarting as mentioned here (even though I think that's for older versions), but it didn't help.
I thought maybe there's a console permission or something I might need to add to the manifest, but didn't find any such thing.
Complete code for reference. I only changed the lines marked with +/-:
function showCookiesForTab(tabs) {
  //get the first tab object in the array
  let tab = tabs.pop();

  //get all cookies in the domain
  var gettingAllCookies = browser.cookies.getAll({url: tab.url});
  gettingAllCookies.then((cookies) => {

    //set the header of the panel
    var activeTabUrl = document.getElementById('header-title');
    var text = document.createTextNode("Cookies at: "+tab.title);
    var cookieList = document.getElementById('cookie-list');
-   activeTabUrl.appendChild(text);
+
+   console.log('I can't see this log!');
+   cookieList.parentNode.appendChild(document.createTextNode(Date())); // I see this updated even though I don't see the log

    if (cookies.length > 0) {
      //add an <li> item with the name and value of the cookie to the list
      for (let cookie of cookies) {
        let li = document.createElement("li");
        let content = document.createTextNode(cookie.name + ": "+ cookie.value);
        li.appendChild(content);
        cookieList.appendChild(li);
      }
    } else {
      let p = document.createElement("p");
      let content = document.createTextNode("No cookies in this tab.");
      let parent = cookieList.parentNode;

      p.appendChild(content);
      parent.appendChild(p);
    }
  });
}

//get active tab to run an callback function.
//it sends to our callback an array of tab objects
function getActiveTab() {
  return browser.tabs.query({currentWindow: true, active: true});
}
getActiveTab().then(showCookiesForTab);

A: Firefox console has been divided into different areas. The result of console.log() can be viewed in the relative area.

*

*Multiprocess Browser Console Ctrl+Shift+J
Mostly logs by Firefox itself

*Web Developer Tools Ctrl+Shift+I or F12
Logs by Tab/Webpage and Content scripts of addons

*Extension Toolbox about:debugging#/runtime/this-firefox ➜ XYZaddon ➜ Inspect
Logs by background scripts of XYZaddon

Update
Based on comments, here is a tested simplified code that you can work on. The log shows on Extension Toolbox.
async function showCookiesForTab() {
  // get the first tab object in the array
  const tabs = await browser.tabs.query({currentWindow: true, active: true});

  // get all cookies in the domain
  const cookies = await browser.cookies.getAll({url: tabs[0].url});
  console.log(cookies);
  // Array(6) [ {…}, {…}, {…}, {…}, {…}, {…} ]
}

showCookiesForTab();

A: I had a similar issue. I didn't figure out the cause, but I find a way to see the console.log in the Extension Toolbox.
I added a background script to handle most of the popup.js logic.
And since there is a background script running, I can see the log.
Still don't why I couldn't see the log in the first place.


text:
Q: Uniqueness of differential adjoint operator I wonder if someone can help me on what is, probably, a simple question but is baffling me at the moment!
In standard texts on functional analysis, something like the following is written
Let $L\colon X \to Y$  where $X$ and $Y$ are both Hilbert spaces. Then the adjoint operator $L^\dagger$ exists and is unique, where
 $L^\dagger \colon Y \to X$ and
$ (Lf,g)= (f,L^\dagger g)$ for all $f \in X$ and $g \in Y$.
However, I am having some trouble with this definition in practice. When dealing with differential operators, boundary conditions have to be taken into account and invariably instead of (e.g.) $L\colon L^2 \to L^2$, we have something like $L\colon A \to L^2$ where $A$ is the subset of $L^2$ that satisfies a certain linear boundary condition like $f(1) = 0$. Since $A$ is not a closed subset, it is not a Hilbert space in its own right and I can't see that it is immediate that we can apply the standard theorem as given above. Perhaps we can extend $A$ to $L^2$ somehow - or have I completely missed the point?


text:
Q: Getting "This browser does not support speech recognition" error I am enabling speech recognizer option in my bot.
In localhost I am not getting below error after adding speechrecognizer code.
But after publishing it in Azure, I am getting this error:
"This browser does not support speech recognition."

Getting above error in page load itself. I have tried different browsers but get the same error.
The same code with a different subscription Key is working fine in another Azure environment.
What could the reason be for this error?
speechOptions = {
    speechRecognizer: new CognitiveServices.SpeechRecognizer({
        subscriptionKey:
        '*****'
    }),
    speechSynthesizer: new CognitiveServices.SpeechSynthesizer({
        gender: CognitiveServices.SynthesisGender.Female,
        subscriptionKey: '*****',
        voiceName: 'Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)'
    })
};

A: I have resolved this issue.
This is not an issue with code:-)
Site has to be secured.
Changing http to https resolved this issue.