text:
Q: Open Office \ Microsoft Word compatibility problems with paragraph directions I'm trying to use Open Office (specifically, I tested LibreOffice 3.3) for writing documents, which should be shared with MS Word users.
This documents include Hebrew text, that uses right to left paragraphs (RTL).
both word processors support RTL, but when creating a document in Open Office, and opening it with MS Word (2007, 2010), the paragraph direction doesn't transfer well (some paragraph appear OK, some appear in the wrong direction).
The other direction works fine (Open Office reads correctly the paragraph direction specified by MS Word)
This happens both for docx (Word) documents, and for odt (Open Office) documents.
Any ideas \ workarounds?

A: Have you tried IBM's Symphony?


text:
Q: System.IndexOutOfRangeException error because of "material design lite" I want to use https://material.io/ in my asp.net web project. I put it in the style.bundle and i get an this error: System.IndexOutOfRangeException
I removed material.min.css in bundling after that page was working but the design was broken.
I wonder to know how can we use material.min.css in bundling. Is it possible? What we need to change?
Here is file: https://code.getmdl.io/1.3.0/material.indigo-pink.min.css

A: Okay, problem was style render is not working because of some unknown characters in material.min.css.
Solutions is upgrading web.optimization and webgrase packages in nuget.
I just upgraded WebGrase to 1.6 and problem solved.
I hope it helps to you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cakephp 2+ Image Resize and Crop while uploading the image Hi i need to implement image resize and crop the image while uploading to the server. Please help me out.

A: There are two plugins doing exactly what you want to:

*

*a component https://github.com/angelitomg/QimageComponent you have to actively trigger in your controller

*a behaviour https://github.com/josegonzalez/cakephp-upload which allows you to implement the resizing for a hole model(action independent) with a simple actsAs
The second one is developed by josegonzalez who is really active in #cakephp irc and the whole cakephp development... so this is most likely the better choice ;)

A: Try the image upload behavior
https://github.com/cakecoded/image-upload-behavior/blob/master/app/Model/Behavior/ImageUploadBehavior.php


text:
Q: jquery listeners not behaving properly I'm trying to figure out what's going on with my jquery animations and nothing i've tried has worked in terms of fixing the problem.
If you go here you'll see the issue:
http://mikeheavers.com/clients/niko/

*

*when you roll over one of the thumbnails, it will sometimes hide and show itself in rapid succession. If I try to make sure it is not animated before animating, then sometimes the titles just stick and never animate out. Same thing with using a callback. Here's my current code:

HTML:

Hunter Douglas

JS
    $('.thumb').mouseover(function(){

        if ($chosenThumb != null){
            $lastThumb = $chosenThumb;
        }

        $chosenThumb = $(this);

        console.log($lastThumb + "|" + $chosenThumb + "|" + ($lastThumb == $chosenThumb)); //THIS NEVER EVALUATES AS TRUE - WHAT'S UP WITH THAT?

        if ($lastThumb != $chosenThumb && $lastThumb != null){
            $lastThumb.children('.thumb_overlay').animate({ 'height' : '0px'}, 200);
            $lastThumb.children('.thumb_plus').animate({'height' :'0px', 'width' : '0px' },200);
        }

    if ($chosenThumb != $lastThumb){
        $chosenThumb.children('.thumb_overlay').animate({ 'height' : '30px'}, 200);
        $chosenThumb.children('.thumb_plus').animate({'height' :'31px', 'width' : '31px' },200);
    }
});

What do I need to do to get this working properly?

A: Your problem is that your mouseover event is on the container.  When an element moves over the element you're mousing over it blocks the mouse from the element with the mouseover event triggering a mouseout event.
The solution is to create an element that transparently blocks the whole thumb that can intercept the event without triggering a mouseout.

Hunter Douglas

If you put your events on .block_thumb and you make block_thumb have absolute positioning and height and width equal to the .thumb height and width you should be fine.

A: Put a stop() in before your animation. Example:
$lastThumb.children('.thumb_overlay').stop().animate({ 'height' : '0px'}, 200);

A: You must stop the current animation before starting another on the same object because they are queued..
change your ifs to
if ($lastThumb != $chosenThumb && $lastThumb != null){
    $lastThumb.children('.thumb_overlay').stop().animate({ 'height' : '0px'}, 200);
    $lastThumb.children('.thumb_plus').stop().animate({'height' :'0px', 'width' : '0px' },200);
}

if ($chosenThumb != $lastThumb){
    $chosenThumb.children('.thumb_overlay').stop().animate({ 'height' : '30px'}, 200);
    $chosenThumb.children('.thumb_plus').stop().animate({'height' :'31px', 'width' : '31px' },200);
}

A: if the problem is that the mouseover is firing multiple times, then add a conditional in there to make sure it doesn't happen
for example, try this code instead (see the "is-animating" lines):
$('.thumb').mouseover(function(){

        // is this already animating?
        var $this=$(this);
        if ($this.data('is-animating')) {
            return;
        }

        if ($chosenThumb != null){
            $lastThumb = $chosenThumb;
        }

        $chosenThumb = $this;

        // mark this so future events know it's already animating
        $this.data('is-animating', true);

        console.log($lastThumb + "|" + $chosenThumb + "|" + ($lastThumb == $chosenThumb)); //THIS NEVER EVALUATES AS TRUE - WHAT'S UP WITH THAT?

        if ($lastThumb != $chosenThumb && $lastThumb != null){
            $lastThumb.children('.thumb_overlay').animate({ 'height' : '0px'}, 200);
            $lastThumb.children('.thumb_plus').animate({'height' :'0px', 'width' : '0px' },200);
        }

    if ($chosenThumb != $lastThumb){
        $chosenThumb.children('.thumb_overlay').animate({ 'height' : '30px'}, 200);
        $chosenThumb.children('.thumb_plus').animate({'height' :'31px', 'width' : '31px' },200);
    }

    // unmark it after the animation's finished
    setTimeout(function() {
        $this.data('is-animating', false);
    }, 200);

});


text:
Q: Short story about aliens who use terrifying dreams/visions to conquer other species I read this story many years ago so I've forgotten most of the details.  I think it was told from the point of view of a narrator going through the experience.
People all over the world began having terrifying dreams and/or visions about some impending disaster.  (I think it was an alien invasion, but it might have been some other sort of calamity.)  All the people of Earth were going to suffer horribly before being wiped out.  Everyone became convinced that it was really going to happen and that it could not be avoided.  So the whole world collectively decided to commit suicide to avoid the suffering.  I believe they planned first to painlessly euthanize all the children, and then the adults would kill themselves.
It was revealed (too late) at the end of the story that there really was an alien invasion, but the aliens had only one weapon: the ability to telepathically project images of suffering and death into the minds of other species in order to frighten them into destroying themselves.


text:
Q: csv stream parser ( papaparse ) is blocking render? I'm using papa parse to retrieve csv streams from my backend for data visualization , however I noticed that even though it is calling the callback for the data chunks properly it is also blocking render. I'm trying to add new data to my graphs as it comes it but it doesn't seem to be able to do so.
Anyone have experience with this? Or perhaps know what is blocking the render?

A: The default behaviour in PapaParse is to run the parsing job in the main thread (also the UI thread) of the browser. But there's an option to avoid this.
In the PapaParse configuration enable 'workers'
http://papaparse.com/docs#config
That will run the parsing job in another thread using the WebWorkers API available in modern browsers, and will not block the UI thread.
More information about PapaParse workers here: http://papaparse.com/faq#workers


text:
Q: How to create mail using Mail::Outlook with Outlook 2007 I am trying to create a mail using Mail::Outlook. I followed this answers I believe is correct:
Sending email using Perl
Mail::Outlook CPAN
I created a simple code based from the tutorials:
use strict;
use warnings;

use Mail::Outlook;
use Data::Dumper;

my $outlook = new Mail::Outlook();
print Dumper($outlook);
print Dumper(Win32::OLE->LastError()); #added in response to comment

my $message = $outlook->create();

$message->To('sample@gmail.com');
$message->Cc('another@gmail.com');

$message->Subject('Testing sending mail from perl');
$message->Body('Hi, This is the body! wahahah!');

$message->save();

1;

The emails I used are real but I replaced it here for privacy's sake..
When I run the script, an error appeared:
$VAR1 = undef;
Can't call method "create" on an undefined value at send_mail.pl line 14.

It seems that the variable $outlook did not initialized during new Mail::Outlook(). The module Mail::Outlook returns undef if initiating a new object failed.. Now, I wonder why this happened.. I am thinking it was because of security issues of outlook but I don't know how to tweak that. Please perl masters out there, if anyone has the same experience or have encountered this, it would be helpful..
I am using Microsoft Outlook 2007 in windows 7 and I installed ppm install Mail-Outlook.
My main question is: How can I create a mail using Mail::Outlook in Outlook 2007
UPDATE
I tried using print Dumper(Win32::OLE->LastError()); and it printed this error:
$VAR1 = 'Win32::OLE(0.1709) error 0x80080005: "Server execution failed"';

A: After following what Tim Tom has instructed, with a little search, I saw an article about the error Win32::OLE(0.1709) error 0x80080005: "Server execution failed"
COM Process Elevation Mismatching
It says that the access level of the outlook application and perl script must be the same:

To make a long (and frustrating) story short, the problem was that I was running the script from a CMD.EXE window which was elevated ("Run as Administrator"). When I would run Outlook from a non elevated process (as a normal user would) there appeared to be a process elevation mismatch.

this is the same in my case.. I was running my cmd as Administrator while my outlook was running normally..
MSDN has a say to this:

COM security is aware of integrity levels and does not allow lower-integrity clients to bind to class instances running at a higher integrity level.

after changing my command line with the same elevation level as the outlook app, the perl script worked perfectly!
Note: perl crashes while using print Dumper(Win32::OLE->LastError()); if it has no errors..


text:
Q: App is crashing when I try to navigate between screens - Expo My App is crashing with no error logs on the console when I'm trying to navigate between screens based on the onAuthStateChanged() method.
Navigation Packages used :
"@react-navigation/native": "^6.0.6",
"@react-navigation/stack": "^6.0.11",
can somebody help me?
Loading.js
import React, { useEffect } from "react";
import firebase from '../config/firebase';
import { View, StyleSheet, ActivityIndicator, StatusBar } from "react-native";
import { CommonActions } from '@react-navigation/native';

export default function Loading({ navigation }) {
  StatusBar.setBarStyle('dark-content');

  useEffect(() => {
    console.log('from useEffect');
    firebase.auth().onAuthStateChanged((user)=>{
      if(user!=null ){
        navigation.dispatch(
          CommonActions.reset({
            index: 1,
            routes: [
              { name: 'HomeRoute' },
            ],
          })
        )
        // navigation.navigate('HomeRoute')
      }else{
        navigation.dispatch(
          CommonActions.reset({
            index: 1,
            routes: [
              { name: 'LoginRoute' },
            ],
          })
        )
        // navigation.navigate('LoginRoute');
      }
    })
  })

  return (
    <View style={styles.container}>
      <ActivityIndicator size='large' color='#333333' style={styles.indicator}  ></ActivityIndicator>
    </View>
  );
}

App.JS
import Login from './screens/Login';
import Home from './screens/Home';
import Loading from './screens/Loading';
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName='LoadingRoute' screenOptions={{headerShown: false}}>
        <Stack.Screen name='LoginRoute' component={Login} />
        <Stack.Screen name='HomeRoute' component={Home} />
        <Stack.Screen name='LoadingRoute' component={Loading} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

A: You got dispatch action a bit off.
You are passing in an index: 1 which is telling the navigation to focus the route at index 1 once the navigation is finished.
The problem is you have only a single route inside routes, so you should tell the navigation to focus route at index 0 like so
navigation.dispatch(
  CommonActions.reset({
    index: 0,
    routes: [{ name: "LoginRoute" }],
  })
);

I would also highly advise reading the official docs on how to set up your authentication flow with react-navigation.
TLDR: What you should do basically is conditionally render the routes based on the user login state and let react-navigation handle the rest for you.


text:
Q: Installing Zest 2 from GEF4 I need to move to Zest 2 from GEF4. I got Zest2 from the Eclipse market place. However when I run a program that utilizes it, I get the following error
Caused by: java.lang.ClassNotFoundException: org.eclipse.gef4.geometry.planar.Rectangle
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 8 more

I'm assuming this means that I need the GEF4 Geometry pack as well so I try to download that from gef4 - http://download.eclipse.org/tools/gef/gef4/updates/integration
 However that isn't allowed since it says I am missing package javafx.collections.
Cannot complete the install because one or more required items could not be found.
  Software being installed: GEF4 Geometry JavaFX Conversion 0.1.0.201407251903 (org.eclipse.gef4.geometry.convert.fx.feature.group 0.1.0.201407251903)
  Missing requirement: GEF4 Geometry JavaFX Conversions 0.1.0.201407251903 (org.eclipse.gef4.geometry.convert.fx 0.1.0.201407251903) requires 'package javafx.collections [2.0.0,3.0.0)' but it could not be found
  Cannot satisfy dependency:
    From: GEF4 Geometry JavaFX Conversion 0.1.0.201407251903 (org.eclipse.gef4.geometry.convert.fx.feature.group 0.1.0.201407251903)
    To: org.eclipse.gef4.geometry.convert.fx [0.1.0.201407251903]

Can someone please advise me on how I can fix this? Thanks.

A: I believe the GEF4 zest plugins are broken at the moment. The framework is still under development and things got broken/changed from time to time.
I also received the JAVAFX issue during update about 2 weeks ago. Today I updated again and the issue is gone. However, when I run some application based on recent zest 2 code, I am getting the same class not found error for classes in org.eclipse.gef4.geometry.planar package.
It seems many packages in geometry plugin are marked as "export only to ..." option and the allowed downstream plugin list is empty.

A: The problem you have reported is related to missing JavaFX dependencies. These are contributed by e(fx)clipse, so this has to be included in your target. You can refer to the GEF contributor guide at http://wiki.eclipse.org/GEF/Contributor_Guide to get guidance on how to set up your workspace (and target) to work with GEF4. The guide also describes our policy with respect to limited exposing of (provisional API) packages.
In general, let me add that we are currently rewriting Zest2 based on GEF4 MVC.FX, using JavaFX for visualization. That is, the org.eclipse.gef4.zest.core, org.eclipse.gef4.zest.jface, and org.eclipse .gef4.zest.ui bundles are deprecated and will be removed in the Mars timeframe. You can find details here: https://bugs.eclipse.org/bugs/show_bug.cgi?id=372365.


text:
Q: How to import a Chrome extension's files from 6 years ago (I have the session data!) In 2016, I would backup all my Chrome extension's current session data (the directory looks like this). I copy-pasted these files for few computer transfers and it worked every time - it got my extensions up and running fine. It meant I could transfer extension settings and other local data without losing or have to recreate the old settings (think Reddit Enhancement Suite and how you lose your username tags, upvote tallies, and toggled settings every time you move computers).
I haven't tried doing an Extension transfer for a few years, but wanted to transfer the 2016 session data of an extension onto my new Chrome install. Unfortunately I can see that Chrome has actually changed the way they save local extension files.
The old way to replace Chrome session data comprised of replacing just two files (a .localstorage and .localstorage-journal file) and the steps were the following:

*

*Open Windows Explorer

*Go to: %localappdata%\google\chrome\user data\default\Local Storage

*Replace the "chrome-extension_[extension key].localstorage" and "chrome-extension_[extension key].localstorage-journal" files

*Open Chrome again and extensions have old session data transferred

Now instead of just two files saved locally for current session data, there's a maze of multiple folders and I can't find the .localstorage and .localstorage-journal files anywhere. It seems that somewhere down the line (around 2019?) Chrome converted these .localstorage files into maybe .json or other files?
Is there a way to convert the data from these old file extensions into whatever the new format is?
Let me know if none of this makes sense or if you need elaboration. The specific extension data I want is from a Chrome extension called Sidewise, and I had a lot of cool windows and tabs saved in the local data.


text:
Q: Can you create object property names using template literals in javascript? I'm attempting to write a function that takes an array of Strings as its input. The function should return an object with (1) key, value pair. The first element of the array should be the property name and the last element of the array should be its key.
function transformFirstAndLast(array){
    return {`${array[0]}`: array[length-1];}
}

The above gives me an error. Can someone provide a detailed explanation why this isn't working? I'd like to avoid creating separate variables to store the values from the first and last array indices.

A: Your question really boils down to, "Can I use expressions as keys in object literals?"
The answer is yes (since es6):

function yell(template, ...parts) {
  return parts[0] + '!';
}

function foo() {
    return 'bar';
}

class Person {
    constructor(first, last) {
        this.first = first;
        this.last = last;
    }

    toString() {
        return `${this.first} ${this.last}`;
    }
}

let names = ['Abe'];

let my_obj = {
    [3+5]: 'some_value',
    [yell `${foo()}`]: foo(),
    [names[0]]: 64,
    [new Person('Rafael', 'Cepeda')]: 25
};

console.log(my_obj);

As long as the expression evaluates to a string, all is fair.

A: You are missing the { and you can't use a template strings as a key. To use a "variable" as a key in an object, you should use the brakets around the variable. Here's the working code.
function transformFirstAndLast(array){
    return {[array[0]]: array[array.length-1]};
}

A: I guess template literal is unnecessary here simply try like this way after fixing this line array[length-1] because its wrong, correct one is array[array.length-1]. I've added more verbose code but you can also do the shorthand version like return {[array[0]]: array[array.length-1]}; on your transformFirstAndLast(array) function.

function transformFirstAndLast(array){
    const result = {};
    result[array[0]] = array[array.length-1];
    return result;
}

console.log(transformFirstAndLast(['a','b','c','d','e']))

A: yes you can use string literals as key. But the thing is that they are calculated in the run time. So you need to treat them as expressions. And to have variables/expressions as your keys you need to wrap them inside []
let a = {
  `key`: value
} // is not allowed

let a = {
  [`key`]: value
} // is allowed since you have wrapp

for your case
return {[`${array[0]}`]: array[array.length-1]};

Now since you have wrapped the array[0] item inside a string literal, you will get string values for your zero'th item. If your array[0] is to be a object this would not work as well. It needs to be either string or number. Or else you would get "[object Object]" as your key

A:

var input = ["name", "fname", "lname", "stackOverflow"];

function transformFirstAndLast(array){
    return {[array[0]]: array.pop()}
}

responseObject = transformFirstAndLast(input)
console.log(responseObject)


text:
Q: Static and dynamic types I am preparing for an exam in java. Please have a look at the following two exercises .(I have solutions, but the solutions are without explanations) so If anybody could check my explanations, that would be greatly appreciated.
1)
public interface Sale{}
public abstract class Clothing{}
public class Jacket extends Clothing implements Sale{}
public class LeatherJacket extends Jacket{}

Which of the following are possible:
Sale var1 = new LeatherJacket();

is possible, since LeatherJacket is a subclass of Jacket and Jacket implements sale? (I'm just guessing here).
Sale var2 = new Sale();

impossible. You cannot create an object of an interface type.
Clothing var3 = new Clothing();

impossible. You cannot create an object of an abstract class.
Clothing var4 = new LeatherJacket();

possible, but why?
Jacket var5 = new LeatherJacket();

possible, but why exactly?
LeatherJacket var6  = new Object();

not possible, but why not?

A:
Clothing var4 = new LeatherJacket();

possible, but why?

This is allowed because LeatherJacket is a derived class of Clothing. It is not instantiating through the abstract class Clothing. It wrote new LeatherJacket() and not new Clothing().

Jacket var5 = new LeatherJacket();

possible, but why exactly?

This is allowed because all leather jackets are Jacket. But the reverse is untrue. It is like all Lions are animals, then you can write it as:
Animal lion = new Lion();  //where Lion extends Animal

But you can't write it as:
Lion lion = new Animal();  //not all animals are lions

LeatherJacket var6  = new Object();

not possible, but why not?

The reason is same as the previous explanation. Object is at the highest hierarchy in Java, every class is a subclass of class Object. Hence being at the top of the hierarchy, this will not be allowed. However, this will be allowed:
Object var6 = new LeatherJacket();  //allowed (all leather jackets are objects)
LeatherJacket var 6 = new Object(); //not allowed (not all objects are leather jackets)

A: Clothing var4 = new LeatherJacket();

LeatherJacket extends Jacket that extend Clothing.
Jacket var5 = new LeatherJacket();

LeatherJacket extends Jacket
LeatherJacket var6  = new Object();

Object is the superClass of all. You can't do it but viceversa yes  Object o= new LeatherJacket();

A: When you have a hierarchy like this, you can perceived it via a venn diagram:

The following should give you a very good clue what is allowed and not allowed:
Object o = new Clothing();        //not allowed (Clothing is abstract!)
Object o = new Jacket();          //allowed (jacket is a subset of object)
OBject o = new LaatherJacket();   //allowed (leather jacket is a subset of object)

Clothing c = new Object();        //not allowed (Object is not a subset of clothing, cannot assume object is definitely a Clothing)
Clothing c = new Jacket();        //allowed (jacket is a subset of Clothing)
Clothing c = new LaatherJacket(); //allowed (leather jacket is a subset of Clothing)

Jacket j = new Object();          //not allowed (Object is not a subset of jacket, cannot assume object is definitely a jacket)
Jacket j = new Clothing();        //not allowed (Clothing is abstract!)
Jacket j = new LeatherJacket();   //allowed (leather jacket is a subset of jacket)

LeatherJacket j = new Object;     //not allowed (Object is not a subset of jacket, cannot assume object is definitely a leather jacket)
LeatherJacket j = new Clothing(); //not allowed (Clothing is abstract!)
LeatherJacket j = new Jacket();   //not allowed (Jacket is not a subset of jacket, cannot assume jacket is definitely a leatherjacket)


text:
Q: regexp - Match whole string if it doesn't contain another string What I need to do is to get the whole input string, if it doesn't contain another string.
To be more clear (php code, doesn't really matter, the regexp is important):
Let's say the string we want to negate is "home".
 preg_match($unknownReg, "This is a home bla bla", $part);
 echo $part; // I need to echo "";

 preg_match($unknownReg, "This is a car", $part);
 echo $part; // I need to echo "This is a car"

I'm aware of solutions like strpos (for php), but I'd like a reg for it (because not knowing it burns be from inside :)) ).

A: You could try this pattern:
^.*(?<!home.*)$

Or this one:
^(?!.*home).*$

Both patterns will match any sequence of characters as long as it doesn't contain home anywhere in the string. For example:
"This is a home bla bla" // no match
"This is a car"          // match

You can test the second pattern here.

A: Pure negation? To be or !(to be):
!preg_match("#home#", "This is a home bla bla", $part);


text:
Q: What is the purpose of Django's request._cached_user? New to Django and really trying to build a solid grasp of its built-in authentication and session mechanisms. Looking in the current (v1.8) source code, I see this:
django/contrib/auth/middleware.py
def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user

class AuthenticationMiddleware(object):
    def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(lambda: get_user(request))

When I grep through the Django code, I don't see anywhere else that request._cached_user is referenced, and nowhere else that this particular get_user() is called besides the lambda in the auth middleware. Unless I don't understand middleware, the process_request() is only called once per request.
Am I missing an obvious reason why Django is storing _cached_user in request, never to reference it again?

A: As part of the general Django MVC pattern, Views are passed Requests (not logged in users).
However accessing the authenticated User model is a frequent operation in any Django apps that use login/authentication.
The framework (and in particular the AuthenticationMiddleware) assumes that the authenticated User associated with a Request will not change during the handling of each web request.
For performance reasons, the get_user function retains a reference the associated User and thus avoids repeat database queries for the associated User.

A: Just interpreting Dwight's answer:
I guess get_user() function is being called in different places and multiple times in a single request-response cycle. Given request being the "global" (not technically global scope) variable gets passed around it makes sense to set the user object as a request attribute.


text:
Q: Replace li text using jquery without changing other elements I am trying to replace the content of li and  tags.
Tried below code.

   Sample

    <input type="checkbox" class="layer-input-filter" name="testname">Test 5

    <input type="checkbox" class="layer-input-filter" name="testname1">Test1 10

Mixed assessment guidelines

Specimen

Plagiarism

Download

Qualification update

Specimen

Exam guide update

Guide

I need to replace the text of every li inside the body. so used above jquery for it. But it is not working.
Example :

Plagiarism

Should replace as

PlagiarismPlag

First four characters of each li text. That is Plag in the above example
Can anyone help me with this, please?

A: Rather than cloning, try replacing the li > a's text directly. No need to test if the string is empty first, because if it is empty, the existing text (empty string) won't change:

var value = 0.4;
$("body").find('li > a').each(function(index) {
  const text = $(this).text();
  const newText = text + text.slice(0, Math.floor(text.length * value));
  $(this).text(newText);
});

<input type="checkbox" class="layer-input-filter" name="testname">Test 5

<input type="checkbox" class="layer-input-filter" name="testname1">Test1 10

Mixed assessment guidelines

Specimen

Plagiarism

Download

Qualification update

Specimen

Exam guide update

Guide

A:

$(document).ready(function($) {
  $('li>a').each(function(index, element) {
    var b = "Plag"
    var data = $(this).text(); // it will give 1,2,3
    var position = (data.substring(0, 4))
    var output = [data, position].join('');
    $(this).empty().append("" + output);
    return index < 3;
  });
})

<input type="checkbox" class="layer-input-filter" name="testname">Test 5

<input type="checkbox" class="layer-input-filter" name="testname1">Test1 10

Mixed assessment guidelines

Specimen

Plagiarism

Download

Qualification update

Specimen

Exam guide update

Guide

A: In your Case You can use like this. Try This

$(document).ready(function($) {

    $("body").find('li').each(function (e) {
        if ($(this).text() != '') {

            var str = $(this).text();
            var newstring =  str.substring(0, 4) + str;
            $(this).children('a')[0].innerHTML = newstring;
        }
    });

});

<input type="checkbox" class="layer-input-filter" name="testname">Test 5

    <input type="checkbox" class="layer-input-filter" name="testname1">Test1 10

Mixed assessment guidelines

Specimen

Plagiarism

Download

Qualification update

Specimen

Exam guide update

Guide

A: I hope to help you with this code :
    var str = $(this).find('a').text();
    var newStr = str + str.substr(0, 4);
    $(this).find('a').text(newStr)

sample code : https://jsfiddle.net/3w4j8q16/1/


text:
Q: Calling AWS Cognito Form Lambda I have a publicly exposed lambda that allows users to sign up with my site backed by AWS Cognito; or at least I'm trying to.
func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    req := Request{}
    err := json.Unmarshal([]byte(request.Body), &req)
    if err != nil {
        return events.APIGatewayProxyResponse{StatusCode: 400}, UserErrResponse
    }

    session := session2.Must(session2.NewSessionWithOptions(session2.Options{Profile: "default"}))

    svc := cognitoidentityprovider.New(session, aws.NewConfig().WithRegion("us-east-1"))

    input := &cognitoidentityprovider.SignUpInput{
        Password: aws.String(req.Password),
        Username: aws.String(req.Email),
        ClientId: aws.String("**myclientid**"),
    }

    _, err = svc.SignUp(input)

    if err != nil {
        log.Printf("unable to sign up user with err=%v", err.Error())
        return events.APIGatewayProxyResponse{StatusCode: 500}, UserErrResponse
    }

    return events.APIGatewayProxyResponse{StatusCode: 200}, nil
}

This lambda hangs and eventually times out on the "svc.SignUp(input)" line. No error. No feedback. No nothing.
My initial thought was that the lambda does not have permission to connect to Cognito so I gave it all permission as a first debugging measure:
resource "aws_iam_policy" "cognito_sign_in" {
  name   = "${local.name_prefix}LambdaCogntioPolicy"
  policy = jsonencode({
    Version   = "2012-10-17"
    Statement = [
      {
        Action   = [
          "cognito-identity:*",
          "cognito-idp:*",
          "cognito-sync:*",

        ]
        Effect   = "Allow",
        Resource = "*"
      },
    ]
  })
}

This did not help. Still hangs. What am I missing here?
The goal is to write my own lambda's for signing users up, signing users in, and resetting passwords; all backed by Cognito.


text: Q: I am trying to define a dictionary in which Name, Port No, Manufacture's part number, Serial No, Product Id are to be fetched from a list server side response : ['fc1/1 sfp is present', '    Name is CISCO-FINISAR', "    Manufacturer's part number is FTLF8524P2BNL-C2", '    Revision is D', '    Serial number is FNS190500CN', '    Nominal bit rate is 4300 Mb/s', '    FC Transmitter type is short wave laser w/o OFC (SN)', '    FC Transmitter supports intermediate distance link length', '    Transmission medium is multimode laser with 62.5 um aperture (M6)', '    Supported speeds are - Min speed: 1000 Mb/s, Max speed: 4000 Mb/s', '    Cisco extended id is unknown (0x0)', '    Cisco part number is 10-2195-01', '    Cisco pid is DS-SFP-FC4G-SW', '', '    No tx fault, no rx loss, in sync state, diagnostic monitoring type is 0x68', '    SFP Diagnostics Information:', '       Temperature           :  29.90 C    ', '        Voltage               :   3.29 V       ', '        Current               :   9.15 mA         ', '        Optical Tx Power      :  -4.06 dBm        ', '        Optical Rx Power      :  -2.53 dBm        ', '        Tx Fault count  : 0', '    Note: ++  high-alarm; +  high-warning; --  low-alarm; -low-warning', '', 'fc1/2 sfp is present', '    Name is CISCO-AVAGO', "    Manufacturer's part number is SFBR-5780AMZ-CS1", '    Revision is G4.1', '    Serial number is AVD1745B4WL', '    Nominal bit rate is 8500 Mb/s', '    Link length supported for 50/125um OM2 fiber is 50 m', '    Link length supported for 62.5/125um fiber is 21 m', '    Link length supported for 50/125um OM3 fiber is 150 m', '    FC Transmitter type is short wave laser w/o OFC (SN)', '    FC Transmitter supports short distance link length', '    Transmission medium is multimode laser with 62.5 um aperture (M6)', '    Supported speeds are - Min speed: 2000 Mb/s, Max speed: 8000 Mb/s', '    Cisco extended id is unknown (0x0)', '    Cisco part number is 10-2418-01', '    Cisco pid is DS-SFP-FC8G-SW', '', '    No tx fault, no rx loss, in sync state, diagnostic monitoring type is 0x68', '    SFP Diagnostics Information:', '       Temperature           :  34.16 C    ', '        Voltage               :   3.30 V       ', '        Current               :   6.20 mA         ', '        Optical Tx Power      :  -2.51 dBm        ', '        Optical Rx Power      :  -4.41 dBm        ', '        Tx Fault count  : 0', '    Note: ++  high-alarm; +  high-warning; --  low-alarm; -low-warning', '', 'fc1/3 sfp is present', '    Name is CISCO-FINISAR', "    Manufacturer's part number is FTLF8524P2BNL-C2", '    Revision is D', '    Serial number is FNS190506K6', '    Nominal bit rate is 4300 Mb/s', '    FC Transmitter type is short wave laser w/o OFC (SN)', '    FC Transmitter supports intermediate distance link length', '    Transmission medium is multimode laser with 62.5 um aperture (M6)', '    Supported speeds are - Min speed: 1000 Mb/s, Max speed: 4000 Mb/s', '    Cisco extended id is unknown (0x0)', '    Cisco part number is 10-2195-01', '    Cisco pid is DS-SFP-FC4G-SW', '', '    No tx fault, no rx loss, in sync state, diagnostic monitoring type is 0x68', '    SFP Diagnostics Information:', '       Temperature           :  29.58 C    ', '        Voltage               :   3.29 V       ', '        Current               :   6.79 mA         ', '        Optical Tx Power      :  -4.03 dBm        ', '        Optical Rx Power      :  -2.52 dBm        ', '        Tx Fault count  : 0', '    Note: ++  high-alarm; +  high-warning; --  low-alarm; -low-warning', '', 'fc1/4 sfp is present', '    Name is CISCO-FINISAR', "    Manufacturer's part number is FTLF8524P2BNL-C2", '    Revision is D', '    Serial number is FNS19050AWE', '    Nominal bit rate is 4300 Mb/s', '    FC Transmitter type is short wave laser w/o OFC (SN)', '    FC Transmitter supports intermediate distance link length', '    Transmission medium is multimode laser with 62.5 um aperture (M6)', '    Supported speeds are - Min speed: 1000 Mb/s, Max speed: 4000 Mb/s', '    Cisco extended id is unknown (0x0)', '    Cisco part number is 10-2195-01', '    Cisco pid is DS-SFP-FC4G-SW', '', '    No tx fault, no rx loss, in sync state, diagnostic monitoring type is 0x68', '    SFP Diagnostics Information:', '       Temperature           :  33.85 C    ', '        Voltage               :   3.30 V       ', '        Current               :   8.18 mA         ', '        Optical Tx Power      :  -4.05 dBm        ', '        Optical Rx Power      :  -2.87 dBm        ', '        Tx Fault count  : 0', '    Note: ++  high-alarm; +  high-warning; --  low-alarm; -low-warning', '', 'fc1/5 sfp is present', '    Name is CISCO-FINISAR', "    Manufacturer's part number is FTLF8524P2BNL-C2", '    Revision is D', '    Serial number is FNS19200WNK', '    Nominal bit rate is 4300 Mb/s', '    FC Transmitter type is short wave laser w/o OFC (SN)', '    FC Transmitter supports intermediate distance link length', '    Transmission medium is multimode laser with 62.5 um aperture (M6)', '    Supported speeds are - Min speed: 1000 Mb/s, Max speed: 4000 Mb/s', '    Cisco extended id is unknown (0x0)', '    Cisco part number is 10-2195-01', '    Cisco pid is DS-SFP-FC4G-SW', '', '    No tx fault, no rx loss, in sync state, diagnostic monitoring type is 0x68', '    SFP Diagnostics Information:', '       Temperature           :  27.45 C    ', '        Voltage               :   3.31 V       ', '        Current               :   7.30 mA         ', '        Optical Tx Power      :  -4.08 dBm        ', '        Optical Rx Power      :  -3.21 dBm        ', '        Tx Fault count  : 0', '    Note: ++  high-alarm; +  high-warning; --  low-alarm; -low-warning', '', 'fc1/6 sfp not present', 'fc1/7 sfp not present', 'fc1/8 sfp not present', 'fc1/9 sfp not present', 'fc1/10 sfp not present', 'fc1/11 sfp not present', 'fc1/12 sfp not present', 'fc1/13 sfp not present', 'fc1/14 sfp not present', 'fc1/15 sfp not present', 'fc1/16 sfp not present', 'fc1/17 sfp not present', 'fc1/18 sfp not present', 'fc1/19 sfp not present', 'fc1/20 sfp not present', 'fc1/21 sfp not present', 'fc1/22 sfp not present', 'fc1/23 sfp not present', 'fc1/24 sfp not present', 'fc1/25 sfp not present', 'fc1/26 sfp not present', 'fc1/27 sfp not present', 'fc1/28 sfp not present', 'fc1/29 sfp not present', 'fc1/30 sfp not present', 'fc1/31 sfp not present', 'fc1/32 sfp not present', 'fc1/33 sfp not present', 'fc1/34 sfp not present', 'fc1/35 sfp not present', 'fc1/36 sfp not present', 'fc1/37 sfp not present', 'fc1/38 sfp not present', 'fc1/39 sfp not present', 'fc1/40 sfp not present', 'fc1/41 sfp not present', 'fc1/42 sfp not present', 'fc1/43 sfp not present', 'fc1/44 sfp not present', 'fc1/45 sfp not present', 'fc1/46 sfp not present', 'fc1/47 sfp not present', 'fc1/48 sfp not present']


text:
Q: WPF, finding control inside itemtemplates datatemplate How do I programmatically find a control inside an ItemTemplate's DataTemplate, e.g. how do I find the CheckBox inside the following code:
<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox x:Name="KontoFeltCheckBox"
                  Checked="KontoFeltCheckBox_Checked" />
    </DataTemplate>
</ListBox.ItemTemplate>


text:
Q: Can I install binaries into the GAC via a VSIX installer? I've got a hybrid installer which drops binaries on the target machine (WIX) as well as installs templates into Visual Studo (VSIX).  The VSIX is stored as a binary in the installer and is installed via a custom action when the installation is finalized.
It works, but there are a few issues.  I could get around those issues if I could skip WIX altogether and install everything via the VSIX.
The problem is that I have to drop some binaries in the GAC.  If I can drop a binary in the GAC in the VSIX, then everything would be cool.  But I can't seem to find any information on how to do this.
Alternatively, can I install binaries to a specific location on a target machine using VSIX?
Is any of this possible?

A: No. VSIX can't put files into the GAC and nor can it add registry entries for you. Exe or MSI install is what you'll need. Your users will lose the ability to enable/disable from within Extension Manager though, which is sad.
https://msdn.microsoft.com/en-us/library/vstudio/dd393694(v=vs.100).aspx
 summarizes your deployment choices and confirms the no-GAC thing.


text:
Q: Create a thumbnail from an UIViewController without it showing I'm making an Ipad application that consists of some 100 different views that represent projects. To be able to scroll fast between projects I am trying to create a thumbnail view.
The problem is that I have to make the thumbnail images before the UIViewController itself is shown on screen.
Currently I'm using this code:
ProjectViewController2 * page2 = [[ProjectViewController2 alloc]initWithNibName:@"ProjectViewController2" bundle:nil displayRightArrow:FALSE media:nil];
[page2 setMyMedia:media];
[page2 configurePage];
CGSize size = [page2.view bounds].size;
UIGraphicsBeginImageContext(size);
[[page2.view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
NSString * filePath= [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project/%@", [media fileName]];
[UIImageJPEGRepresentation(newImage, 1.0) writeToFile:filePath atomically:TRUE];
UIGraphicsEndImageContext();

This works, I get a screenshot from the UIViewController, but without the main images. These images are not being set in the NIB file, but in the configurePage function. The background color and menubar, that are being set in the NIB file, are visible in the thumbnail.
I suspect that I don't see the images because the UIViewController is not being shown on screen and thus some kind of draw function is not being called.
Any help is really appreciated!!!
Stijn

A: When is the configurePage method being called? On ViewDidLoad?Where as the ProjectViewController is initialised with initWithNibName, hence probably why the nib elements are showing and you can get a image representation of them. My guess is write a custom initiailiser which has the project image as part of the initialisation sequence, or perhaps test moving the configurePage code to one of the other viewController methods such as viewWillAppear. Just a thought.


text:
Q: How to make Firebase App Check work when using Angularfire? I'm trying to make Firebase App Check work but I'm struggling to find a way to do so using Angularfire as there seem to be no docs on it from what I can find.
...
import { getFirestore, provideFirestore } from '@angular/fire/firestore';
import { AngularFireModule } from '@angular/fire/compat';
import { AngularFireStorageModule } from '@angular/fire/compat/storage';
import { initializeAppCheck, provideAppCheck, ReCaptchaV3Provider } from '@angular/fire/app-check';
import { FirebaseApps, getApp } from '@angular/fire/app';

@NgModule({
  ...
  imports: [
    ...
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule.enablePersistence(),
    AngularFireStorageModule,
    provideFirestore(() => getFirestore()),
    provideAppCheck(() => initializeAppCheck(getApp(), { provider: new ReCaptchaV3Provider(environment.recaptchaSiteKey), isTokenAutoRefreshEnabled: true })),
  ],
})
export class AppModule {}

With this I get this error when I run the app:

NullInjectorError: R3InjectorError(AppModule)[AngularFireAuthGuard -> AngularFireAuth -> AppCheckInstances -> InjectionToken angularfire2.app-check-instances -> [object Object] -> FirebaseApps -> FirebaseApps -> FirebaseApps]:
NullInjectorError: No provider for FirebaseApps!

And if I add FirebaseApps directly to providers like:
providers: [
  FirebaseApps,
]

I get this error instead:

FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

What's the correct way of doing this?

A: So managed to solve this by ditching AngularFireModule and using this instead:
 provideFirebaseApp(() => initializeApp(environment.firebase)),

Also had to add:
{ provide: FIREBASE_OPTIONS, useValue: environment.firebase },

to providers.
After that I also had to add the "App Check debug token" that is logged by the SDK in the browser console to debug tokens in the Firebase Console under the "App Check" section. Failed to do so will make your requests fail with a 403 status.


text:
Q: Matlab sum: The expression to the left of the equals sign is not a valid target for an assignment When I try to run this code, this error message keeps showing up in matlab:

The expression to the left of the equals sign is not a valid target
  for an assignment.

a_k and b_k are meant to be row vectors of size (1,m). I can't use the command symsum because it doesn't let me index these vectors within the symsum. The resulting sum has to involve the dirac and heaviside functions. Ideas? :)
prompt = 'Enter m';
m = input(prompt);
prompt = 'Enter x-coordinates of dislocations';
a_k = input(prompt);
prompt = 'Enter y-coordinates of dislocations';
b_k = input(prompt);

syms x_1 x_2 y_1 y_2

F_1(y_1,y_2) = sum(heaviside(y_1-a_k(1,i))*dirac(1,y_2-b_k(1,i)), i=1:m);

A: You are using an invalid sum syntax, i.e. i=1:m.
sum calculates the sum of all the elements in an array. So, you need to rewrite your formula in vectorised way using elementwise operations as follows:
F_1(y_1, y_2) = sum(heaviside(y_1-a_k(1,1:m)).*dirac(1,y_2-b_k(1,1:m)));


text:
Q: how to databind to DevExpress TreeList i want to databind hierarchical data from plain data to the ASPxTreeList, i checked the documentation online for the the databinding, this is the code i found:
 Imports Microsoft.VisualBasic
 Imports System

 Partial Public Class Data_Hierarchical
     Inherits BasePage
     Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
         If (Not IsPostBack) Then
             DataBind()
             treeList.ExpandToLevel(1)
         End If
     End Sub
 End Class

but how DataBind() is implemented?

A: The DataBind is a method of the System.Web.UI.Control class and it is described in MSDN:
Control.DataBind
In fact, we override this method in our code the way similar to the one described in the MSDN.


text:
Q: Geometric intuition of an invariant set, positively invariant and negatively invariant
Definition:
Invariant set
A set $S \subseteq \mathbb{M}$ is invariant if $\Psi_{t}\left ( S \right )\subseteq S,\forall t$
-if $\forall x \in S$, $\Psi_{t}\left ( x \right )\subseteq S,\forall t$
-if $\forall x\in S,q\left ( t,x \right )\subseteq S,\forall t$
Definition: Positively invariant
A set $S\subseteq \mathbb{M}$ is positively invariant if $\Psi_{t}\left ( S \right )\subseteq S,t \geq 0$
Definition: Negatively invariant
A set $S\subseteq \mathbb{M}$ is negatively invariant if $\Psi_{t}\left ( S \right ) \subseteq S,t\leq 0$

The first definition seems to be saying that for any elements of a set S, the map of elements of a set S under a trajectory results in the image being in the set S-an onto map?
A couple of definitions came up on my notes and I hope to gain a geometric intuition for it. Could someone kindly assists me?
Thanks in advance.

A: In my opinion, the most intuitive definition of an invariant set is that it does not change when the flow $Ψ$ is applied (pointwise), i.e., $S$ is invariant, iff $Ψ_t(S) = S~ ∀ t$. With other words, trajectories may not leave or enter the set, i.e., for any point $x∈S$, the trajectory passing through that point is entirely in $S$ – for the entire past and future. It suffices to only require $Ψ_t(S)⊆S$ in the definition as this directly yields that $Ψ_t(S)⊆Ψ_{-t}(Ψ_t(S))=S$.
A classical example is are the state-space trajectories of a frictionless pendulum. All states corresponding to a given total energy of the pendulum form an invariant set (and so do all unions of such sets). Trajectories leading into or out of this set would correspond to the pendulum losing or gaining energy, which is impossible. If we add friction to the scenario and this friction is such that the pendulum, the only possible invariant set contains only the rest state of the pendulum. However, this point is only an invariant set if the friction is such that a pendulum in motion never reaches total standstill, but only moves slower and slower.
If the set is only positively invariant, trajectories may enter it but not leave it. For the pendulum with friction, all states with less than a given energy form a positively invariant set: Trajectories leaving the set would correspond to the pendulum gaining energy, which is impossible.
Finally, a negatively invariant set may not be entered by trajectories. In the pendulum with friction, all states with an energy higher than a given energy would comprise a negatively invariant set.


text:
Q: Why does some android code have public fields? There are many questions and answers about using public fields in Object Oriented Programming, and most of them recommend not to use public fields for many reasons.
But when I looked into Android's code I found some classes are using public fields. For example Android.view.View has public fields mCachingFailed and mAttributes.
Why are they public? It is hard to think this is a mistake on Google and AOSP's part.

A: Check out this section from developer.android.com:

In native languages like C++ it's common practice to use getters (i =
  getCount()) instead of accessing the field directly (i = mCount). This
  is an excellent habit for C++ and is often practiced in other object
  oriented languages like C# and Java, because the compiler can usually
  inline the access, and if you need to restrict or debug field access
  you can add the code at any time.
However, this is a bad idea on Android. Virtual method calls are
  expensive, much more so than instance field lookups. It's reasonable
  to follow common object-oriented programming practices and have
  getters and setters in the public interface, but within a class you
  should always access fields directly.
Without a JIT, direct field access is about 3x faster than invoking a
  trivial getter. With the JIT (where direct field access is as cheap as
  accessing a local), direct field access is about 7x faster than
  invoking a trivial getter.
Note that if you're using ProGuard, you can have the best of both
  worlds because ProGuard can inline accessors for you

http://developer.android.com/training/articles/perf-tips.html#GettersSetters
Most likely, this is the reason you see public fields in AOSP.

A: It isn't inherently a mistake to have public fields.  It is not, as the bounty note suggests, an "OOP-fundamental-violation".  After all these two classes are (for most purposes) identical:
public class DemoA {
  public int field;
}

public class DemoB {
  private int field;

  public int getField() { return field; }
  public void setField(int value) { field = value; }
}

That is to say, if you intend for callers to have direct read and write access to a field adding a getter and setter may just be extra boiler-plate.
The benefit of getters and setters, even if they do no other work than reading and writing to fields, is that they abstract the fact that the data is stored in a field at all. It could be stored in an external data source, or computed on the fly, or whatever you'd like, and callers don't have to worry about how the behavior is implemented.  This is definitely a good practice in general because it separates the callers concerns (the API) from your concerns (the implementation).
However sometimes it's just overkill, and it's perfectly reasonable to expose public fields if that's the best way to provide the behavior your callers need.  Most often, this is done for value types, classes that exist solely to group a number of fields together.  There's little benefit to writing out scores of getters and setters when everything you need a class to do can be accomplished by simply making the fields public.
As a practical matter, Android has an additional concern. Method calls are expensive and the number of methods an app can (easily) define is limited to ~65k. For cases where it's safe to do so, exposing a field directly reduces the method overhead by two and saves valuable CPU time.  That might not seem like a lot, but it adds up quickly.


text:
Q: How to send bytes over a socket in python? so I need to send a bunch of escaped hex to a server but I need to know which a causing problems. I tried the code below but I cant get it to send raw bytes. It keeps outputting the string. Im new to programming in general so am I missing something basic? I searched it but nothing helpful.
`ops = ''.join('\\x%02x' % i for i in range(256))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((127.0.0.1,8888))
s.send(ops)
s.close()`

A: What is an escaped hex? You either want to send bytes or strings. Byte is a byte, it's a number:
ops = bytearray(i for i in range(256))


text:
Q: Back button is gone in split view After embedding the UISplitViewController inside a UITabViewController, back button on navigation bar is turned into a full screen icon:

It's the segue preparation code:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDrugDetails" {
        //foo
        controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
        controller.navigationItem.leftItemsSupplementBackButton =
    }
}

How can I get back the back button? (everything works fine on iPhone)
Edit: Storyboard


text:
Q: Environment.getExternalStorageDirectory() fiel Why return null? I'm trying to get the music(mp3,wav) file name of an Android Device, but the
ArrayList<File> mySongs=findSong(Environment.getExternalStorageDirectory());

field returns null.
Any ideas?
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    public ArrayList<File> findSong(File file){
        ArrayList<File>arrayList=new ArrayList<>();
        File[] files= file.listFiles();

        for(File singleFile: files){
            if(singleFile.isDirectory()&&!singleFile.isHidden()){
                arrayList.addAll(findSong(singleFile));
            }
            else{
                if(singleFile.getName().endsWith(".mp3")||singleFile.getName().endsWith(".wav")){
                    arrayList.add(singleFile);
                }
            }
        }
        return arrayList;
    }

  void displaySongs(){
        final ArrayList<File> mySongs=findSong(Environment.getExternalStorageDirectory());

        items=new String[mySongs.size()];
        for(int i=0;i<mySongs.size();i++){
            items[i]=mySongs.get(i).getName().toString().replace(".mp4","").replace(".wav","");
        }

        customAdapter customAdapter=new customAdapter();
        listView.setAdapter(customAdapter);
    }

A: If you are calling Environment.getExternalStorageDirectory() in field initialization, then you are likely making this call before your application is 'starting'. You should try assigning this field within the onCreate() method in your Application class (docs) as follows:
@Override
public void onCreate() {
    super.onCreate();
    this.mySongs = findSong(Environment.getExternalStorageDirectory());
}


text:
Q: ember-simple-auth session restore not working I have a custom authenticator which is really just extending the oauth2 authenticator so I can pass additional infomration to the API with my POST to /token.
All works fine. However, when you do a page refresh and the session tries to restore I am redirected to the login page and not authenticated.
The restore() method, if still within expiry and has a token should and does resolve with data however this does not authenticate the session.
Any ideas?
restore: function(data) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
  var now = (new Date()).getTime();
  if (!Ember.isEmpty(data.expires_at) && data.expires_at < now) {
    if (_this.refreshAccessTokens) {
      _this.refreshAccessToken(data.expires_in, data.refresh_token).then(function(data) {
        resolve(data);
      }, reject);
    } else {
      reject();
    }
  } else {
    if (Ember.isEmpty(data.access_token)) {
      reject();
    } else {
      _this.scheduleAccessTokenRefresh(data.expires_in, data.expires_at, data.refresh_token);
      Ember.run(function() {
        log('returning restore')
        log(data) //shows my previous session data including access_token
        resolve(data);
      })
    }
  }
});
},


text:
Q: Concatenar variável com id buscada por Javascript Olá!
Tenho um código para autocomplete aqui que está me dando um pouco de dor de cabeça.
Meu código consiste em um foreach que gera uma linha a cada registro encontrado, a cada linha gera um botão que chama um modal, coloquei na linha que chama o modal uma variável que vai se iterando e concatenei essa variável com a id do modal, assim pude ligar o modal a linha correta.
<button type="button" data-toggle="modal" data-target="#modalAdicao<?php echo htmlspecialchars($idModal); ?>" class="botao btn-editar">Editar</button>

Logo quando a variável se refere a linha das 08:00, o modal abre com possibilidade de edição daquela linha, até aí tudo ok.
Meu problema é que o Javascript do autocomplete busca por uma id de input chamada #busca, porém só funciona na primeira ocorrência do modal, isso porque na segunda o #busca já foi utilizado, preciso então que a id desse input mude acompanhando o modal, logo pensei no seguinte:
<input type="text" id="busca<?php echo htmlspecialchars($idModal); ?>" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control" required>

A lógica é simples, já fiz isso em código pequeno, mas não soube aplicar no autocomplete pois sou bem leigo e não compreendo bem o código por completo ainda.
Amostra do código:
$(function() {

    // Atribui evento e função para limpeza dos campos
    $('#busca').on('input', limpaCampos);

    // Dispara o Autocomplete a partir do segundo caracter
    $( "#busca" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            $.ajax({
                url: "include/procura_paciente.php",
                dataType: "json",
                data: {
                    acao: 'autocomplete',
                    parametro: $('#busca').val()
                },
                success: function(data) {
                   response(data);
                }
            });
        },
        focus: function( event, ui ) {
            $("#busca").val( ui.item.rg );
            carregarDados();
            return false;
        },
        select: function( event, ui ) {
            $("#busca").val( ui.item.rg );
            return false;
        }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "
" )
        .append( "
Paciente: " + item.nome + " -  RG: " + item.rg + "
" )
        .appendTo( ul );
    };

    // Função para carregar os dados da consulta nos respectivos campos
    function carregarDados(){
        var busca = $('#busca').val();

        if(busca != "" && busca.length >= 2){
            $.ajax({
                url: "include/procura_paciente.php",
                dataType: "json",
                data: {
                    acao: 'consulta',
                    parametro: $('#busca').val()
                },
                success: function( data ) {
                   $('#nomePaciente').val(data[0].nome);
                   $('#nomePaciente2').val(data[0].nome);
                   $('#rgPaciente').val(data[0].rg);
                   $('#nascimentoPaciente').val(data[0].nascimento);
                   $('#cpfPaciente').val(data[0].cpf);
                }
            });
        }
    }

    // Função para limpar os campos caso a busca esteja vazia
    function limpaCampos(){
       var busca = $('#busca').val();

       if(busca == ""){
       $('#nomePaciente').val('');
           $('#nomePaciente2').val('');
           $('#rgPaciente').val('')
           $('#nascimentoPaciente').val('')
           $('#cpfPaciente').val('')
       }
    }
});

Primeira linha que chama o modal:
08:00 ID DA LINHA: 0
<button type="button" data-toggle="modal" data-target="#modalAdicao0" class="botao btn-editar">Editar</button>

Abaixo algumas amostras do código já com PHP renderizado:
Primeiro modal:

Novo Agendamento para João Santos

        <button type="button" data-dismiss="modal" aria-label="Close" class="close">×</button>

Preencha os campos abaixo 08:00 ID 0

        <form id="novoAgendamento" method="POST" action="include/novo_agendamento.php">

              Identidade
              <input type="text" id="busca" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control procura" required>

              Nascimento
              <input type="text" id="nascimentoPaciente" placeholder="Nascimento" name="nascimentoPaciente" class="mx-sm-69 form-control nascimentoPaciente" required>

            <input type="hidden" id="nomePaciente" name="nomePaciente" class="form-control nomePaciente">
            <input type="hidden" id="cpfPaciente" name="cpfPaciente" class="form-control cpfPaciente">
            <input type="hidden" id="horaPaciente" name="horaPaciente" value="08:00" class="form-control horaPaciente">
            <input type="hidden" id="dataPaciente" name="dataPaciente" value="2018-05-19" class="form-control dataPaciente">
            <input type="hidden" id="medicoPaciente" name="medicoPaciente" value="João Santos" class="form-control medicoPaciente">
            <input type="text" id="nomePaciente2" placeholder="Nome do Paciente" class="form-control nomePaciente2" disabled="">

            <input type="text" name="observacaoPaciente" placeholder="Observação" class="form-control observacaoPaciente" required>

            <button type="button" data-dismiss="modal" class="btn btn-secondary">Fechar</button>
            <button type="submit" class="btn btn-primary">Agendar</button>

        </form>

Segunda linha que chama o modal:
09:00 ID DA LINHA: 1
<button type="button" data-toggle="modal" data-target="#modalAdicao1" class="botao btn-editar">Editar</button>

Segundo modal:

Novo Agendamento para João Santos

        <button type="button" data-dismiss="modal" aria-label="Close" class="close">×</button>

Preencha os campos abaixo 09:00 ID 1

        <form id="novoAgendamento" method="POST" action="include/novo_agendamento.php">

              Identidade
              <input type="text" id="busca" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control procura" required>

              Nascimento
              <input type="text" id="nascimentoPaciente" placeholder="Nascimento" name="nascimentoPaciente" class="mx-sm-69 form-control nascimentoPaciente" required>

            <input type="hidden" id="nomePaciente" name="nomePaciente" class="form-control nomePaciente">
            <input type="hidden" id="cpfPaciente" name="cpfPaciente" class="form-control cpfPaciente">
            <input type="hidden" id="horaPaciente" name="horaPaciente" value="09:00" class="form-control horaPaciente">
            <input type="hidden" id="dataPaciente" name="dataPaciente" value="2018-05-19" class="form-control dataPaciente">
            <input type="hidden" id="medicoPaciente" name="medicoPaciente" value="João Santos" class="form-control medicoPaciente">
            <input type="text" id="nomePaciente2" placeholder="Nome do Paciente" class="form-control nomePaciente2" disabled="">

            <input type="text" name="observacaoPaciente" placeholder="Observação" class="form-control observacaoPaciente" required>

            <button type="button" data-dismiss="modal" class="btn btn-secondary">Fechar</button>
            <button type="submit" class="btn btn-primary">Agendar</button>

        </form>

A: Quando fazemos referência a um objeto no documento pelo seu identificador (ID). Esperamos obter um único resultado. Isso porque o id serve justamente para isso. Ser único. Sua ideia:
<input type="text" id="busca<?php echo htmlspecialchars($idModal); ?>" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control" required>

Me parece ser razoável pois vincula a busca a um id especifico.
Porém no seu script ajax estas a capturar um único id enquanto existem vários.
Logo agora sua ideia de razoável passou a ser um grande fiasco. Isso por que agora vamos ter que nos preocupar em relacionar esses ids ao seletor na função ajax. Uma solução mais simples consiste em selecionar os valores através do uso de classes passando o id do campo busca para ser utilizada no retorno dos dados. Isto é ! Para sabermos onde colocar o resultado da busca. Ex. $('#nome-'+id):

 $( document ).ready(function() {
        $('.busca').change(function(){
            busca(this.value , this.id);
        })

        function busca(busca , id){
            // Busca
            let resultado =  'resultato para a busca ' + busca;
            //Retornando os resultados
            $('#nome-'+id).val(resultado);
        }

 });
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <form action="">
        <input id="1" class="busca" type="text">Busca
    <input id="nome-1" type="text">Resultado
    </form>
    <form action="">
        <input id="2" class="busca" type="text">Busca
        <input id="nome-2" type="text">Resultado
    </form>
    <form action="">
        <input id="3" class="busca" type="text">Busca
        <input id="nome-3" type="text">Resultado
    </form>

A: Lamento ter que dizer isso mas essa sua aplicação está mal estruturada e devido a isso, até mesmo respondendo a dúvida, você terá outros problemas que não terá como resolver. Costumo dizer que quando a pergunta é complexa demais, não estamos fazendo a coisa certa.

*

*Procure centralizar e/ou reaproveitar as coisas, como por exemplo, tenha apenas uma Modal.

*Na modal você está usando o ID BUSCA no campo do RG, IDs não podem se repetir, crie um ID único para cada elemento

*Use a callback select do autocomplete para chamar carregaDados(item.id) com p ID do paciente, a partir dele você obtem todo o resto

*No seu botão de abrir a modal use onclick="carregaHorario('09:00')" e crie essa função para receber o horário e colocar o valor no campo na modal

Espero ter ajudado!
Boa sorte!


text: Q: Can I open and start an AppleScript-.scpt-program (Name is progName.scpt) with one click or a double-click? On my desktop I have several program-icons and all contains AppleScript-.scpt-programs. To start such a program, I must before load the program with a double-click and then make a click on the run-button. Can I avoid this without transfer the scpt-progam to an app-program.


text:
Q: E: Unable to locate package when I install unetbootin I try to install UNETbootin using the terminal. When I enter the following:
sudo apt-get update
sudo apt install unetbootin

I get this error:
E: Unable to locate package

I already tried many things.
I hope anyone has a solution for this? I'm using Ubuntu 18.10 is it because of this version I get this error? Are there other alternatives than unetbootin?

A: Three moments here:

*

*UNetBootin was available in the universe repository for 14.04 LTS and 16.04 LTS.

*UNetBootin's PPA ppa:gezakovacs/ppa do not have packages for 18.10.

*You still can install it by manually downloading packages from 18.04 LTS PPA:
cd ~/Downloads
wget https://launchpad.net/~gezakovacs/+archive/ubuntu/ppa/+files/unetbootin_667-1~bionic2_amd64.deb
wget https://launchpad.net/~gezakovacs/+archive/ubuntu/ppa/+files/unetbootin-translations_667-1~bionic2_all.deb
sudo apt install ./unetbootin*.deb

Note: I have sent e-mail to UNetBootin PPA owner about supporting of 18.10.

A: UNetbootin has been dropped from the default Ubuntu repositories in 18.04 and later, but the built-in Startup Disk Creator application is a good alternative to UNetbootin for the 5 live Linux USBs that I made with Startup Disk Creator instead of UNetbootin so far. My cumulative success rate with Startup Disk Creator as a UNetbootin alternative is 5 out of 5.


text:
Q: Add tax to grandtotal based on checkbox with javascript php I have a transaction form that could use tax or no tax if the transaction use tax than the user click the checkbox and it will give a value to taxes textbox (besides the checkbox)
And calculate/sum subtotal + taxes = grandtotal
the tax is fix 10% of subtotal
here is my code
<?php
$con = mysqli_connect('localhost', 'root', '', 'a.karat');
if(isset($_POST['product_id']))
{
    $prno=$_POST['prno'];
    $i=1;
    $sql = mysqli_query($con,"select * from detail_pr where prNo='$prno'");
while ($r = mysqli_fetch_array($sql)) {

    echo

    '

<input type="checkbox" name="check[]" id="check'.$i.'" value="'.$i.'">

  <input type="text" name="productCode'.$i.'" id="productCode'.$i.'" readonly value="'.$r["productCode"].'" size="12" >

  <input type="text" name="productName'.$i.'" id="productName'.$i.'" readonly value="'.$r["productName"].'"size="35" >

  <input type="number" onkeyup="calc(this);" name="qty'.$i.'" id="qty'.$i.'" readonly value="'.$r["qty"].'" size="10" >
<input type="number" onkeyup="calc(this);" name="price'.$i.'" id="price'.$i.'" size="10" min="1" max="99" onchange="calc(this);" >
<input type="number" onkeyup="calc(this);" name="discount'.$i.'" id="discount'.$i.'" size="10" min="0" max="99" onchange="calc(this);">
<input type="number" name="total'.$i.'" id="total'.$i.'" size="15" min="1" max="99" onchange="calc(this);"  >

';
  $i++;
      }
}
?>

<form name="form1" id="form1 >

    Sub Total
     :
    <input name="subtotal" id="subtotal" type="text" onFocus="startCalc();" onBlur="stopCalc();">

    tax 10% <input name="tax" id="tax" type="checkbox" value="10" >
     :
    <input name="taxes" id="tax1" type="taxes">

    Grand Total
     :
    <input name="grandtotal" id="grandtotal" type="text">

 </form>


text:
Q: fstab filesystem type for NTFS -- 'ntfs' or 'ntfs-3g'? I have a question about the difference between 'ntfs' and 'ntfs-3g' in the filesystem type field in the /etc/fstab file. My Linux distribution is Xubuntu; I suppose the answer may well vary between distros.
My question is basically which is best to use in which contexts. It seems that most websites tell you to use 'ntfs-3g', which is a FUSE driver for NTFS under linux. From some searching around it seems to be the case that 'ntfs' (without the -3g part) typically refers to a kernel driver, rather than the ntfs-3g userland driver. The only problem with that is that I've been using 'ntfs' in my fstabs rather than 'ntfs-3g', while a check of /proc/filesystems doesn't show any listing for ntfs.
Can anyone shed some light on what the precise difference in semantics (if there is any) is between 'ntfs' and 'ntfs-3g'? Is it safe to assume that if mount sees 'ntfs' it will search for a driver which supports that type of filesystem and find the ntfs-3g driver if it's installed?

EDIT: I forgot to add that 'ntfs' has worked whenever I've used it -- I was simply curious as to the answer, and I wanted to make sure I wasn't doing something iffy.

A: They're identical - both use ntfs-3g in (current) Ubuntu; the ntfs utils are just symlinked to ntfs-3g.
# which mount.ntfs
/sbin/mount.ntfs
# which mount.ntfs-3g
/sbin/mount.ntfs-3g
# ls /sbin/mount.ntfs* -l
lrwxrwxrwx 1 root root 13 2011-03-01 21:13 /sbin/mount.ntfs -> mount.ntfs-3g
lrwxrwxrwx 1 root root 12 2011-03-01 21:13 /sbin/mount.ntfs-3g -> /bin/ntfs-3g

A: The traditional NTFS kernel driver is read only. If you use ntfs in your fstab it will attempt to use that kernel driver, and mount your NTFS as read only
The ntfs-3g is the newer FUSE driver (as you mention) and will mount the partitions as read-write is you use it in NTFS.
Some distros have started treating them as one and the same, but as of about a year ago, using ntfs in fstab in Ubuntu would result in the file system not being writeable. I guess it might depend upon the version of Xubuntu you have installed.


text:
Q: VS code displays "Problems" when there are none I started  to use VS Code, and  I'm t   rying  to figure out an issue:
I've a very small basic code:
from PySide import QtGui, QtCore
app = QtGui.QApplication([])
window = QtGui.QWidget()
window.show()
app.exec_()

First time I launched, I forgot the [] parameters in the QApplication constructor, so there was effectively an error. I now have corrected it, I can launch the app, the window is properly displayed, everything is fine.
BUT, VS Code continue to display me 2 errors:
{
    "resource": "/f:/Dev/python-ui/firstApp.py",
    "owner": "python",
    "code": "E1101",
    "severity": 8,
    "message": "E1101:Module 'PySide.QtGui' has no 'QApplication' member",
    "source": "pylint",
    "startLineNumber": 4,
    "startColumn": 7,
    "endLineNumber": 4,
    "endColumn": 7
}

and
{
    "resource": "/f:/Dev/python-ui/firstApp.py",
    "owner": "python",
    "code": "E1101",
    "severity": 8,
    "message": "E1101:Module 'PySide.QtGui' has no 'QWidget' member",
    "source": "pylint",
    "startLineNumber": 5,
    "startColumn": 10,
    "endLineNumber": 5,
    "endColumn": 10
}

What did I missed?
It's annoying because in the file list I then have the name in red.

A: It means the linter you have chosen to run can't find those attributes on the object. Make sure that PySide is installed in the environment that you selected for VS Code and that the linter is able to find the package.


text:
Q: query on 3 Tables with Join I am trying to join all fields on 3 tables. I've tried nearly 7 queries all of which either take forever to load up (really slow) or throw errors.
I need to join all 3 table on table1 id field. All tables have corresponding id fields.
This is my latest experiment: (throws errors for duplicate rows)
SELECT * FROM
(Select * FROM
table1 as T1 JOIN
table2 as T2 ON T1.dep_id=T2.dep_id WHERE 1) as T12
JOIN
table3 as T3 ON T12.dep_id=T3.dep_id WHERE 1

A: try (UPDATE as per comments from OP):
SELECT * FROM TABLE1 T1 LEFT OUTER JOIN TABLE2 T2 ON T1.DEP_ID = T2.DEP_ID LEFT OUTER JOIN TABLE3 T3 ON T1.DEP_ID = T3.DEP_ID

A: You have columns with the same name which causes the error (T12.dep_id is not well-defined, does it refer to original T1.dep_id or T2.dep_id?).
You could use USING which merges two columns with the same name in both sides of the join, and joins them on an equality test. This is convenient when you don't want duplicate columns in the result set:
SELECT *
  FROM T1
  JOIN T2 USING(dep_id)
  JOIN T3 USING(dep_id)

Note that with the following query, you don't have a column named T1.dep_id or T2.dep_id nor T3.dep_id, you just have dep_id available if you want to SELECT that column only.
As per comments on Yahia's answer:
SELECT *
  FROM T1
  LEFT JOIN T2 USING(dep_id)
  LEFT JOIN T3 USING(dep_id)

A: you have some syntax errors in your code because t12 doesn't exist.
other problem is the declaration of your table
be patient with tables ids.
SELECT * FROM table1 t1,table2 t2,table3 t3 WHERE t1.dep_id=t2.id AND T2.id=T3.dep_id;


text:
Q: How to get Firefox debug output on Windows Firefox has started reliably crashing on startup. It crashes instantly in normal mode, and after about 4 seconds in safe mode. I'm trying to see any kind of debugging output so I can work out what is causing it but can't find anyway to see any kind of log!

*

*The Crash Reports\pending\xxx.dmp files are binary so not much help.

*If I run it from the console with -console it does create a new console window, but nothing is ever written to it, and it closes when Firefox crashes.

*-attach-console doesn't seem to work as described.

Any ideas?

A: Not a log, but all of the reported crashes are publicly available (who knew)?

*

*Go to %appdata%\Mozilla\Firefox\Crash Reports\submitted in Explorer

*Copy the filename (except .txt) of the latest crash, e.g. bp-21034108-2f5f-47ef-bf66-cf29f2160218

*Browse to https://crash-stats.mozilla.com/report/index/<paste filename here>
In my case it was Websense injecting a DLL (qipcap.dll) that caused Firefox to crash. Fix in this comment.


text:
Q: Anyone who knows how to store data into a txt file in windows mobile 7.5? I only find the way to store data in isolatedstorage but I cannot find the file in my mobile. It is said the file will not exist when mobile is off. And I only find the way to store picture in mobile but this is achieved by API provided by microsoft. I cannot find other method to store txt file in my mobile. Emergency! Help, Please!

A: You have to open an IsolatedStorageFileStream and declare your text file. This can be done easily. Check this link: http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.createfile(v=vs.95).aspx
Here you can learn a bit more about files in IsolatedStorage:
http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile(v=vs.95).aspx
hope this helps.


text:
Q: On Windows, stat and GetFileAttributes fail for paths containing strange characters The code below demonstrates how stat and GetFileAttributes fail when the path contains some strange (but valid) ASCII characters.
As a workaround, I would use the 8.3 DOS file name. But this does not work when the drive has 8.3 names disabled.
(8.3 names are disabled with the fsutil command: fsutil behavior set disable8dot3 1).
Is it possible to get stat and/or GetFileAttributes to work in this case?
If not, is there another way of determining whether or not a path is a directory or file?
#include "stdafx.h"

#include <sys/stat.h>
#include <string>
#include <Windows.h>
#include <atlpath.h>

std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

// The final characters in the path below are 0xc3 (Ã) and 0x3f (?).
// Create a test directory with the name à and set TEST_DIR below to your test directory.
const char* TEST_DIR = "D:\\tmp\\VisualStudio\\TestProject\\ConsoleApplication1\\test_data\\Ã";

int main()
{
    std::string testDir = TEST_DIR;

    // test stat and _wstat
    struct stat st;
    const auto statSucceeded = stat(testDir.c_str(), &st) == 0;
    if (!statSucceeded)
    {
        printf("stat failed\n");
    }

    std::wstring testDirW = s2ws(testDir);

    struct _stat64i32 stW;
    const auto statSucceededW = _wstat(testDirW.data(), &stW) == 0;
    if (!statSucceededW)
    {
        printf("_wstat failed\n");
    }

    // test PathIsDirectory
    const auto isDir = PathIsDirectory(testDirW.c_str()) != 0;
    if (!isDir)
    {
        printf("PathIsDirectory failed\n");
    }

    // test GetFileAttributes
    const auto fileAttributes = ::GetFileAttributes(testDirW.c_str());
    const auto getFileAttributesWSucceeded = fileAttributes != INVALID_FILE_ATTRIBUTES;
    if (!getFileAttributesWSucceeded)
    {
        printf("GetFileAttributes failed\n");
    }

    return 0;
}

A: The problem you have encountered comes from using  the MultiByteToWideChar function. Using CP_ACP can default to a code page that does not support some characters. If you change the default system code page to UTF8, your code will work. Since you cannot tell your clients what code page to use,  you can use a third party library such as International Components for Unicode to convert from the host code page to UTF16.
I ran your code using console code page 65001 and VS2015 and your code worked as written. I also added positive printfs to verify that it did work.

A: Don't start with a narrow string literal and try to convert it, start with a wide string literal - one that represents the actual filename.  You can use hexadecimal escape sequences to avoid any dependency on the encoding of the source code.
If the actual code doesn't use string literals, the best resolution depends on the situation; for example, if the file name is being read from a file, you need to make sure that you know what encoding the file is in and perform the conversion accordingly.
If the actual code reads the filename from the command line arguments, you can use wmain() instead of main() to get the arguments as wide strings.


text:
Q: Sustituir en una lista de números un número por un símbolo y redondear a 2 decimales al resto Tengo una lista
a = [ 1 , 2.5 , 3.34 , 5 , 5 , 0 , 2.0 ]

Quiero imprimir
1.00  2.50  3.34  --  --  0.00  2.00

Lo he intentado así entre otras formas
def add_two_floats (notasalumno):
    """Añadir dos decimales a las notas si tienen menos, rellenando con ceros a la derecha"""
    two_floats = ["%.2f"%i for i in notasalumno]
    print (two_floats)  #Esta sería solo para depurar

def reemplaza_ceros (notasalumno_two_floats):
    """Reemplazo los ceros por guiones al imprimir el boletin de alumnos"""
    for x in range(0,len(notasalumno_two_floats)):
        if notasalumno_two_floats[x] == "0.00":
            notasalumno_two_floats[x] = "----"

A: Al final lo he resuelto así. Os muestro parte del código y como queda impreso.
alumnosClase es una variable que almacena nombre, apellidos, notas alumno en cada evaluaciones y nota media total.
def cuerpo_informe_resultados():
    """Imprime el cuerpo de resultado examen alumnos"""
    for unAlumno in alumnosClase:
        n = unAlumno[0]  # Nombre del alumno
        s = unAlumno[1]  # Apellido del alumno
        neal = unAlumno[2]  # Notas alumno en cada evaluación
        nmeval = unAlumno[3]  # Notas media todas evaluaciones del alumno
        reemplaza_ceros_floats(neal)
        add_two_floats (nmeval)
        if len(n) <= 18 and len(s) <= 15:
            print(n[:18].ljust(20, " "), "\t", s[0:15].ljust(15, " "), '  '.join(str(x) for x in nueva),
                  "  ", '   '.join(str(e) for e in nmal))
        elif len(n) >= 18 and len(s) <= 15:
            print(n[:17].ljust(20, "."), "\t", s[0:15].ljust(15, " "), '  '.join(str(x) for x in nueva),
                  "  ", '   '.join(repr(e) for e in nmal))
        elif len(n) <= 18 and len(s) >= 15:
            print(n[:18].ljust(20, " "), "\t", s[0:12].ljust(15, "."), '  '.join(str(x) for x in nueva),
                  "  ", '   '.join(repr(e) for e in nmal))
        else:
            print(n[:17].ljust(20, "."), "\t", s[0:12].ljust(15, "."), '  '.join(str(x) for x in nueva),
                  "  ", '   '.join(repr(e) for e in nmal))

def add_two_floats (notamediaeval):
    """Añadir dos decimales a las notas si tienen menos, rellenando con ceros y remplazar ceros por guiones
    al imprimir boletin de alumnos"""
    two_floats = [format(float(i), '.2f') for i in notamediaeval]
    reemplazos = {'0.00': ' -- '}
    global nmal
    nmal = [reemplazos.get(x, x) for x in two_floats]
    return nmal

def reemplaza_ceros_floats (notasalumnos):
    """Añadir dos decimales a las notas si tienen menos, rellenando con ceros a la derecha.
    Reemplazo los ceros por guiones al imprimir el boletin de alumnos. """
    listformat = [format(float(i), '.2f') for i in notasalumnos]
    reemplazos = {'0.00': ' -- '}
    global nueva


text:
Q: Wordpress custom fields in custom post types The theme I purchased came without custom fields in the post/product editor. It uses a custom post type in its own admin php file. I've managed to add custom fields by pulling the following code out of wordpress core metabox.php file however I'm unsure how to get it to work. Its missing the area where the custom field values should go.

<?php
$metadata = has_meta($post->ID);
list_meta($metadata);
meta_form(); ?>

A: The developer forgot to support "custom-fields" when calling register_post_type.
When editing a post, if there is no checkbox under screen options for Custom Fields that's why.  In the init hook for my plugin I do...
register_post_type('mynamespace_product',
    array('labels' => array(
            'name' => __( 'Products' ),
            'singular_name' => __( 'Product' )
            ),
        'taxonomies' => array('category', 'product_type'), // this is IMPORTANT,
        'public' => true,
        'has_archive' => true,
        'supports' => array('title','editor','custom-fields','comments')
        )
    );

A: To get the custom fields associated to a post, you can query it this way:
 if ( get_post_meta($post->ID, 'my_customfield', true) ) :
 echo get_post_meta($post->ID, 'my_customfield', true)
 endif;

Hope this helps


text:
Q: UDP success trigger in iOS Currently editing an iPhone app that stores accelerometer data using UDP (see below). Is there a way to signal i.e put in a beep using "TGSineWaveToneGenerator.h" to signify when UDP is actually being successful?
[udpSocket sendData:[[NSString stringWithFormat:@"%f",[[tmp get_p] doubleValue]] dataUsingEncoding:NSUTF8StringEncoding] toHost:@"192.168.0.7" port:1234 withTimeout:-1 tag:1];


text:
Q: ¿Cómo puedo convertir mi entrada en input en una ecuación operable en Python? Estoy haciendo un programa que permita calcular los valores de las raíces de una función por el método de Newton-Raphson para cualquier tipo de función, el problema es que la introducir mi ecuación como 'input' y tratar de evaluarla en un valor "x" me arroja el mensaje <'str' object is not callable>
¿Hay forma de que el input pueda operarse como si fuera una línea más de código?
Este es mi código que llevo por el momento:
'''
from sympy import sympify
from sympy import lambdify

from Testing_Derivada import Primera_derivada, Segunda_derivada

def Newton_Raphson(c, funcion, variable, x):
    cont = 0
    Derivada1 = Primera_derivada(funcion, variable)
    Derivada2 = Segunda_derivada(funcion, variable)

while True:
    x_previa = x

    der1 = lambdify(variable, Derivada1)
    der2 = lambdify(variable, Derivada2)

    x = x_previa - (der1(x)/der2(x))
    y = lambdify(variable, funcion)
    fx = y(x)

    cont += 1

    print("It: {:02} - x: {:.10f} - f(x): {:.10f}".format(cont, x, fx))

    #if cont >= 20:
    if (abs(x-x_previa) <= c):
        print("-----------------------------------------------------------------")
        print("It: {:02} - x: {:.10f} - fx: {:.10f}".format(cont, x, fx))
        break

if __name__ == '__main__':
    c = float(input("Introduce una tolerancia de calculo: "))
    funcion = input("Introduce una función: ")
    variable = input("En función de que variable se realizará la derivada: ")
    x = float(input("Introduce un valor inicial de la variable: "))

resultado = Newton_Raphson(c, funcion, variable, x)
print(resultado)

'''
Finalmente mi codigo que involucra a las derivadas es el siguiente:
import sympy

def Primera_derivada(funcion, variable):
    x = sympy.Symbol(variable)
    U = funcion
    derivada1 = sympy.diff(U, variable)
    return derivada1

def Segunda_derivada(funcion, variable):
    x = sympy.Symbol(variable)
    U = funcion
    derivada2 = sympy.diff(U, variable, variable)
    return derivada2

if __name__ == '__main__':
    funcion = input("Introduce la función a derivar: ")
    variable = input("En función de que variable: ")
    #resultado = derivada(funcion, variable)
    resultados = [funcion, Primera_derivada(funcion, variable), Segunda_derivada(funcion, variable)]
    print(resultados)
    print(type(funcion))

A: Sé que es tarde para resolverte la duda pero la solución esta en el mismo sympy:
from sympy.parsing.sympy_parser import parse_expr

a=input("Cualquier cosa: ")

t=parse_expr(a)

print(t)# y te saldrá en codigo sympy.


text:
Q: Compatibility for Xcode 7, iOS 8, MacSierra and old iOS 6 and 7? I am currently on EL Capitan. I wish to clear few doubts before deciding to upgrade to Sierra.

*

*Can Xcode 7 run on Sierra?

*Can iOS simulator run on Sierra ?

*Can Xcode 7 in Sierra build and test with iOS 6 and iOS 7 actual devices? As my app is still supporting them. As i know, Xcode 8 can no longer build and run on ios 6.

Thanks!

A: Yes xcode 7 will work on Sierra, and all simulators will work. But the problem is that you cannot run real devices with version 10.0 or greater. Also you cannot upload a build to Appstore using sierra+xcode 7. For that u need xcode 8.
Hope this is helpful.


text:
Q: malloc in C++ for performance I'm optimizing a computationally intensive part of a program that has performance as a priority.
Currently I am using std::array for various types of data and caches that cannot be initialized immediately. I would like to allocate the memory for the cache without default initializing the elements for the sake of performance, so that I can initialize them with the appropriate values once they have been computed. The only way I could think of doing that is using malloc. Are there any "cleaner" ways of accomplishing this, and is this a justifiable use of malloc in C++?
I'm aware of the common advice of "never use malloc/new[]". There is a demonstrable need for optimization based on measurements. This is not premature optimization. This part of the code is called ~2.5 million times per second on each thread, and each call should run in under 1000 nanoseconds.

A: Allocate an array of bytes that is large enough to hold the maximum number of elements you want to eventually construct. You can then use placement-new whenever you want to construct an object at a given byte offset within the array.
You can alternatively use std::aligned_storage as the array element type instead of using raw bytes. The linked documentation even provides an example of this exact technique.

A: Here is how to cleanly allocate an std::array without initialising it and without resorting to C-style APIs or low-level APIs like aligned_storage.
#include <memory>
#include <array>

template <class T> struct uninit : public T
{
    uninit() {} // do not omit, do not make = default.
};

using myarray = std::array<int, 1337>;
using myarray_uninit = uninit<myarray>;

std::unique_ptr<myarray> allocate_myarray()
{
    return std::make_unique<myarray_uninit>();
}

Live demo
This particular answer is not concerned with the performance of allocating stuff on the heap vs the performance of not allocating stuff on the heap.


text:
Q: Android build error due to incorrect java version I am currently trying to build Android just for learning purpose. But I am facing strange error -

You are attempting to build with the incorrect version of java.   Your
  version is: java version "1.7.0_07". The correct version is: Java SE
  1.6.

my java - version gives me

java version "1.7.0_07" Java(TM) SE Runtime Environment (build
  1.7.0_07-b10) Java HotSpot(TM) 64-Bit Server VM (build 23.3-b01, mixed mode)

any Idea what went wrong?
regards,

A: After upgrade Ubuntu 12.04 to 12.10 - just export path before build Android e.g:
export PATH=/usr/lib/jvm/java-6-openjdk-amd64/bin/:$PATH

A: 1.) If you've already installed OpenJDK . Remove it by running this command:
sudo apt-get purge openjdk*
2.) Then:
sudo add-apt-repository ppa:webupd8team/java

Then update:
sudo apt-get update

3.) Select which version you want
To install Oracle Java 8:
sudo apt-get install oracle-java8-installer

To install Oracle Java 7:
sudo apt-get install oracle-java7-installer

To install the Java 6:
sudo apt-get install oracle-java6-installer

A: In Eclipse.. Goto Window -> Preferences.. from there Expand the "Java" group. Click "Compiler". From there set the compiler compliance level to 1.6 and all other settings (if not already set to use the default compliance level) to 1.6

A: Open jdk is not supported for android build. Try using sun jdk instead. You can install sun jdk by these commands:
add-apt-repository "deb http://archive.canonical.com/ lucid partner"
apt-get update
apt-get install sun-java6-jdk

If the above command does not work(fails to download jdk), use the following    commands instead:
add-apt-repository ppa:ferramroberto/java
apt-get update
apt-get install sun-java6-jdk

A: Exactly what the message says... Android requires Java 1.5 or 1.6... You are using 1.7
Install and use Java 1.5 or 1.6.