text:
Q: Unable To Install Grub/EFI For Lubuntu I'm trying to install Lubuntu 13.10 X86-64 on my laptop, but it's not working. Lubuntu itself installs fine, but at then end when it tries to install grub it fails and doesn't write anything to the UEFI partition. I'm attempting to install Lubuntu onto an SDHC card and specified that the internal hard drive's UEFI partition should be used. I've received the same result twice.
Details:
Internal 1TB sata hard drive running Windows 8. It's partitioned in GPT and has 4 partitions. 1=UEFI 2=Windows 8 3=Data 4=Data
SDHC 32gb for Lubuntu 13.10. It's partition in GPT and has 2 partitions. 1=UEFI (but I've deleted this so currently it's unformatted empty space), 2=Lubuntu
Secure Boot is disabled otherwise the Lubuntu disc is rejected as insecure, which is weird since secure boot support was added to Ubuntu back in 12.04.2-ish.
EDIT:
I believe the error message was "Failed to install grub-efi to /target/"

A: Yup, it was the internet connection. I connected to my wifi network and the installation completes with grub successfully installed [though grub only boots into rescue mode].


text:
Q: Load a double byte string path into TinyXML2 I'm using TinyXML2 to load an xml document from disk.
The path of the file (configFileName) is a wstring and I am converting it to string like so:
    tinyxml2::XMLDocument doc;
    std::string fileName(configFileName.begin(), configFileName.end());
    doc.LoadFile(fileName.c_str());

This works but there may be times where my program runs on a double byte OS such as Chinese or Korean and the conversion from wstring to string above will loose the characters.
How can I load a path such as the following:
wstring wPathChinese = L"C:\\我明天要去上海\\在这里等我\\MyProgram";

EDIT
I have tried the following to convert the string but it still corrupts the chinese characters:
std::string ConvertWideStringToString(std::wstring source)
{
    //Represents a locale facet that converts between wide characters encoded as UCS-2 or UCS-4, and a byte stream encoded as UTF-8.
    typedef std::codecvt_utf8<wchar_t> convert_type;
    // wide to UTF-8
    std::wstring_convert<convert_type, wchar_t> converter;
    std::string converted_str = converter.to_bytes(source);

    return converted_str;
}

string pathCh2 = ConvertWideStringToString(wPathChinese);

A: I suggest you to use the
XMLError tinyxml2::XMLDocument::LoadFile( FILE *)

So you can simply do something like this:
FILE* fp = nullptr;
errno_t err = _wfopen_s(&fp, configFileName.c_str(), L"rb" );
if( fp && !err )
{
    tinyxml2::XMLDocument doc;
    doc.LoadFile( fp );
    fclose( fp );
}

And forget to do the nightmare conversion between wstring and string...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get the total size of selected folders I have many files and folders inside a certain folder. I wanna get the total size for the files and/or folders I select select inside this certain folder (because when I click Get info I get the size for each one).

A: Select the folders and press optioncommandI (the letter i)
This will show a "get info" window for the combined items.

A: Select folder-> select view (from top near menus)->Select status bar.
Done.
Please see the example screen shots attached here.


text:
Q: add reminder to Google Calendar I have worked out how to add a reminder after setting a CalendarEventEntry using
insertedEntry = myService.insert( postUrl, myEntry )
reminder = new Reminder()
reminder.setMethod( Reminder$Method.ALERT )
//foo
insertedEntry.getReminder().add( reminder )
insertedEntry.update()

but if you update it becomes an EventEntry and the getReminder returns null and whatever you do it wipes all reminders
insertedEntry = myService.update(editUrl, myEntry)

can find nothing in the api or docs about this case.
Anyone solved this already??

A: Did you try to cast the update result ?
BaseEntry updateEntry = myService.update(editUrl, myEntry)
if (updatedEntry instanceOf CalendarEventEntry) {
    insertEntry = (CalendarEventEntry) updatedEntry
}

A: Can't you simply update it with:
insertedEntry.update()

rather than
insertedEntry = myService.update(editUrl, myEntry)


text:
Q: Concatenation of variables to registers How can I concatenate a variable to a command, for example, if I have a variable x, and give it a value of 10, and I'm going to change the state of a register, it would be like PORTB + 10, and would have to result in PORTB10. How can I do this concatenation?Translated by Google Translator,There may be inconsistencies.

A: You can't do that.  The names of things like PORTB only exist in the code as you are writing it.  Once the code is compiled all that turns into just memory addresses and the names are all meaningless at that point.  Under those conditions what you are asking to do makes no sense.  You can create pointers to the various PORT locations or use any number of other ways to accomplish what you want.  Since it isn't clear exactly what you are trying to do I can't give you anything more specific.


text:
Q: How to remove 'GROUP BY' from SQL query produced from get_posts? Wordpress, Archive Cateory page. From default WP_Query->get_posts() we are getting something like this:
SELECT wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE 1=1
AND ( wp_term_relationships.term_taxonomy_id IN (5) )
AND wp_posts.post_type = 'post'
AND ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 40

I want to remove this: "GROUP BY wp_posts.ID" from this SQL query, is it possible?
I've read about pre_get_posts and posts_groupby filter, but I see there is only way to change GROUP BY value, but how to remove it absolutely?

A: You can use posts_groupby filter:
add_filter( 'posts_groupby', function( $groupby ) {

            return '';

} );

If you want to apply to remove the GROUP BY only to main query and in the frontend, you could do something like this:
add_filter( 'posts_groupby', function( $groupby ) {

    if( ! is_admin() && is_main_query() ) {

            $groupby = '';

    }

    return $groupby;

} );


text:
Q: Javascript and HTML function issue <script stylesheet="text/javascript">
var statename;
function confirmReview(formObj){
    function myState( val ){
        statename = val;
        alert( "This is " + statename );
    }
    postcode = document.getElementById("postcode");
    //Folowing code
    if( statename== "Selangor" ){
          if( postcode < 10000 || postcode > 40000 )
                alert( "Invalid postcode for " + statename );
    }
}
</script>
<body>
<form name = reviewform onsubmit="return confirmReview(reviewform)" method=POST>
    <select id='state' onchange="myState(this.value);">
         <option>Specify state or territory</option>
         <option value="Selangor">Selangor</option>
         <option value="Terengganu">Terengganu</option>
    </select>
</form>
</body>

my question is how to store the value and save it to the statename as i fail to run in my HTML javascript code. can anyone teach?
i cannot print out my statename example if i want to make some comparison for my postcode
when i load the script it run to the funciton . my HTML will just clear all the data like refresh the page without showing anything
after i edited the things senior suggested . it's still same. it cannot go to the alert that validation code with the statename

A: You forgot the script tags:
<script type="text/javascript">
var statename;
function myState( val ){
   statename = val;
}
postcode = document.getElementById("postcode");
</script>


text:
Q: Lazy combinations I'm looking for a more lazy/IEnumerable/cleaner way of doing the following. I particularly not happy with the use of helper and Aggregate.
Any hints on how to modify the code to make it possible?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    class Program
    {
        static void PrintOut<T>(IEnumerable<IEnumerable<T>> data)
        {
            foreach (var item in data)
            {
                string output = "-";
                if (item != null)
                    output = string.Join(",", item.Select(x => (x == null) ? "-" : x.ToString()));
                Console.WriteLine(output);
            }
        }

        static IEnumerable<T> helper<T>(IEnumerable<T> orig, T toAdd)
        {
            if (orig != null)
                foreach (var item in orig)
                    yield return item;
            yield return toAdd;
            yield break;
        }

        static IEnumerable<IEnumerable<T>> helper2<T>(IEnumerable<IEnumerable<T>> input) where T : class
        {
            var initalAcc = new List<IEnumerable<T>> { };
            var result = input.Aggregate(initalAcc,
                (acc, choiceSet) =>
                    acc.DefaultIfEmpty()
                        .SelectMany((chosen) => (choiceSet ?? new List<T> { }).DefaultIfEmpty().Select(choice => helper(chosen, choice))).ToList()
            );
            return result;
        }

        static void Main(string[] args)
        {
            var preCombination = new List<List<string>> {
                new List<string> {"1","2"},
                new List<string> {"3"},
                new List<string> {"4","5"},
                null,
                new List<string> {"6","7"}
            };
            var postCombination = helper2(preCombination);

            PrintOut(preCombination);
            Console.WriteLine();
            PrintOut(postCombination);
            Console.ReadLine();
        }
    }
}

Here is the expected output
1,2
3
4,5
-
6,7

1,3,4,-,6
1,3,4,-,7
1,3,5,-,6
1,3,5,-,7
2,3,4,-,6
2,3,4,-,7
2,3,5,-,6
2,3,5,-,7

I've changed initalAcc now
var initalAcc = Enumerable.Empty<IEnumerable<T>>();

A: Here you go. ConcatItem and Yield replace helper.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    class Program
    {
        static void PrintOut<T>(IEnumerable<IEnumerable<T>> data)
        {
            foreach (var item in data)
            {
                string output = "-";
                if (item != null)
                    output = string.Join(",", item.Select(x => (x == null) ? "-" : x.ToString()));
                Console.WriteLine(output);
            }
        }

        static IEnumerable<T> Yield<T>(T item)
        {
            yield return item;
        }

        static IEnumerable<T> ConcatItem<T>(IEnumerable<T> enumerable, T item)
        {
            return enumerable == null ? Yield(item) : enumerable.Concat(Yield(item));
        }

        static IEnumerable<IEnumerable<T>> helper2<T>(IEnumerable<IEnumerable<T>> input) where T : class
        {
            var initalAcc = Enumerable.Empty<IEnumerable<T>>();
            var result = input.Aggregate(initalAcc,
                (acc, choiceSet) =>
                    acc.DefaultIfEmpty()
                        .SelectMany((chosen) => (choiceSet ?? Enumerable.Empty<T>()).DefaultIfEmpty().Select(choice => ConcatItem(chosen, choice)))
            );
            return result;
        }

        static void Main(string[] args)
        {
            var preCombination = new List<List<string>> {
                new List<string> {"1","2"},
                new List<string> {"3"},
                new List<string> {"4","5"},
                null,
                new List<string> {"6","7"},
            };
            var postCombination = helper2(preCombination);

            PrintOut(preCombination);
            Console.WriteLine();
            PrintOut(postCombination);
            Console.ReadLine();
        }
    }
}


text:
Q: SSL certificate does not appear automatically I have bought SSL certificate for my domain and have installed successfully. But the problem is when I type my domain https:// does not appear automatically and when I Type manually https:// it is appeared without any problem. What should I do that when the users type my domain it appears with https:// automatically?
Thanks

A: You can use the following code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Good luck :)


text:
Q: Java, compare Strings in a list of object.s Hello and sorry if I did not explain myself properly.
I am trying to compare if a String is within a previously created list of objects.
example:
List<People> listOfPeople = new ArrayList<>();
Person person1 = new Person("Marija" , "Zagreb");
Person person2 = new Person("Joan", "Barcelona");
Person person3 = new Person("Vinko" , "Zagreb");
listOfPeople.add(person1);
listOfPeople.add(person2);
listOfPeople.add(person3);

What I want to do is checking the city value and be able to create a message if a person appears has the same location. I can't seem to search strings of specific values within a list.
listOfPeople.contains is telling me "given object cannot contain instances of String.
Please let me know if I should extend my question.
Thanks beforehand.

A: From java8, you can use stream, example bellow
import java.util.ArrayList;
import java.util.List;

public class newExample {

    public static void main(String[] args) {
        List<People> listOfPeople = new ArrayList<People>();

        People People1 = new People("Marija", "Zagreb");
        People People2 = new People("Joan", "Barcelona");
        People People3 = new People("Vinko", "Zagreb");
        listOfPeople.add(People1);
        listOfPeople.add(People2);
        listOfPeople.add(People3);

        String city = "Barcelona";

        if (listOfPeople.stream().anyMatch(x -> x.getCity().equals(city))) {
            // found
        }

    }
}

class People {

    String name;
    String city;

    public People(String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

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

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

A: Assuming you are using Java 8 and above, you can use this:
package com.Example;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Person> listOfPeople = new ArrayList<>();
        Person person1 = new Person("Marija" , "Zagreb");
        Person person2 = new Person("Joan", "Barcelona");
        Person person3 = new Person("Vinko" , "Zagreb");
        listOfPeople.add(person1);
        listOfPeople.add(person2);
        listOfPeople.add(person3);

        listOfPeople.stream()
            .filter(p -> p.getCity().equals("Barcelona"))
            .forEach(System.out::println);
    }
}

class Person implements Serializable{
    private static final long serialVersionUID = -414171236169806542L;
    private String name;
    private String city;

    public Person(String name, String city) {
        super();
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

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

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", city=" + city + "]";
    }
}

Output:

Person [name=Joan, city=Barcelona]


text:
Q: Rails 4.2 Ruby 2.2.1 Spring won't start I just did a fresh install of rails using RailsInstaller Ruby 2.1
And after I did a bundle install and everything succeeded I tried to start up spring and got the following error:
    C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/spring-1.3.3/lib/spring/sid.rb:33:in ``': No such file or directory
 - ps -p 1108 -o sess= (Errno::ENOENT)
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/spring-1.3.3/lib/spring/sid.rb:33:in `sid'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/spring-1.3.3/lib/spring/sid.rb:39:in `pgid'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/spring-1.3.3/lib/spring/server.rb:78:in `set_pgid'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/spring-1.3.3/lib/spring/server.rb:34:in `boot'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/spring-1.3.3/lib/spring/server.rb:14:in `boot'
        from -e:1:in `<main>'

Here is what my sid.rb file looks like
begin
  # If rubygems is present, keep it out of the way when loading fiddle,
  # otherwise if fiddle is not installed then rubygems will load all
  # gemspecs in its (futile) search for fiddle, which is slow.
  if respond_to?(:gem_original_require, true)
    gem_original_require 'fiddle'
  else
    require 'fiddle'
  end
rescue LoadError
end

module Spring
  module SID
    def self.fiddle_func
      @fiddle_func ||= Fiddle::Function.new(
        DL::Handle::DEFAULT['getsid'],
        [Fiddle::TYPE_INT],
        Fiddle::TYPE_INT
      )
    end

    def self.sid
      @sid ||= begin
        if Process.respond_to?(:getsid)
          # Ruby 2
          Process.getsid
        elsif defined?(Fiddle) and defined?(DL)
          # Ruby 1.9.3 compiled with libffi support
          fiddle_func.call(0)
        else
          # last resort: shell out
          `ps -p #{Process.pid} -o sess=`.to_i
        end
      end
    end

    def self.pgid
      Process.getpgid(sid)
    end
  end
end

I suppose that the that real error is that it can't get the sid here:
 if Process.respond_to?(:getsid)
      # Ruby 2
      Process.getsid

But I have no idea what to do about this. I am using spring 1.3.3 which is the latest version.
Thanks,

A: Ah, seems that spring is not supported on windows. Just re-read the docs
Spring makes extensive use of Process.fork, so won't be able to provide a speed up on platforms which don't support forking (Windows, JRuby).


text:
Q: Games crashes to desktop with no error, artifacts and visual tear I hope this is the correct stack exchange site.
4 days ago I upgraded my motherboard and cpu as well as new cpu cooler.
MSI Z170A TOMAHAWK -> MSI MAG Z490 TOMAHAWK
Intel i5 6600K -> Intel i5 10600K
Cpu Fan -> MSI MAG CORELIQUID 240R
and didn't change my gpu, ram and psu which are GEFORCE GTX 1070 GAMING 8G, Everest BTX-750-1 750W, 2x Kingston KHX2400C15/8.
I already clean installed Windows 10 Pro, updated BIOS, removed and reinstalled drivers for everything several times. Checked thermals and cpu doesn't go beyond 55-60, and gpu doesn't go beyond 75-80. I did every stress test and memtest and there has been no crashes or errors occurred. The main problem is whenever I try to play any games there are artifacts and screen tear happening, less than 10 minutes in the game, it crashes to desktop with no error. Tried Modernwarfare, Cold War, Battlefield5 and Witcher 3.
Only game it doesn't crash is minecraft and I host a 6 player server while playing on max settings. Most of the time these issues are bound to gpu but I literally took out a working gpu from one motherboard )very carefully and placed it to the other one. (When it didn't work, I took out and cleared the fins and put it back in). Also thermal values are really good. Only thing I know for sure is that my ram sticks are not supported by the motherboard but I don't think these problems occur because of that, if so I will gladly change the sticks but gpu is too much for my wallet. Is there any way for me to solve this, besides gaming I have zero problem, and I feel like it progressively gone worse while gaming, after hardware change I could play for maybe 10 minutes, now it crashes after like 2 minutes. I didn't hurt any of my components I am pretty sure, can the ram sticks not being compatible cause these problems ?


text:
Q: Presentation of UIHostingController glitches with .overCurrentContext modal presentation style I am trying to display a UIHostingController which shows my SwiftUI Popup on screen - however, the presentation glitches and the presented view controller is somewhere stuck in the topmost left corner (see picture, the glitching hosting controller is inside the red circle).
This only occurs if I display another View controller before my hosting controller. So, if nothing was presented before my hosting controller, everything works fine.
Things also work fine, if I set my UIHostingController's modalPresentationStyle = .formSheet - however, that's not a solution for me since I need the behavior of .overCurrentContext for my use case.
So, in short, I do experience a glitch when:

*

*an arbitrary view controller is presented (using self.present(...)) at some point

*before my UIHostingViewController is presented.
I do not get that glitch when:

*

*I only display the UIHostingViewController

Code
I receive the described behavior using the following code:
// First, I display an ActivitySheet
let ac = UIActivityViewController(activityItems: [someItems], applicationActivities: nil)
self.present(ac, animated: true)

// then I present my ViewController using overCurrentContext, after the ActivityViewController was dismissed
let myPopupVC = MyPopupVC()

myPopupVC.isModalInPresentation = true
myPopupVC.modalPresentationStyle = .overCurrentContext // error would not occur if this was .formSheet, but I need .overCurrentContext for my use case.
myPopupVC.modalTransitionStyle = .crossDissolve

self.definesPresentationContext = true
self.present(self, animated: true)

Both modal presentations are the result of button clicks in my interface. The UIActivityViewController is displayed when a share button is clicked, and the popup is displayed when the leave button is pressed (to confirm the user is sure they want to do that).
What I assume
My first thought was that this could have something to do with the UIHostingController being presented by the dismissed activity sheet, however, that wouldn't make sense since it is freed from memory according to Apple's documentation on view controller dismissal (chapter "Dismissing a presented View Controller").
I therefore don't understand why this is happening.
Does anyone know why this behavior arises and, most importantly, how I can fix it using .overCurrentContext as my modal presentation style?

A: The mistake was that I set translatesAutoResizingMaskIntoConstraints to false, which resulted in the UIHostingController's view to lack information needed to position itself correctly.
Therefore, make sure that translatesAutoResizingMaskIntoConstraints remains true if you modally present a UIHostingController.


text:
Q: generate printer logs I am using Ubuntu 14.04 LTS with an EPSON WF 2540 printer.
The printer drivers come from the Epson Linux download centre and so far have been working ok.
The question here for me is how to log every batch of printed jobs to a directory on the side. There is a cutePdf printer on windows that I am aware of which would "print" as if a printer to a pdf file.
I would need as the printer prints and is complete to log a pdf file of exactly what was printed out so as to reprint if I need to at later stage ..etc.
How can this be done automatic under Ubuntu. I am guessing cups may be involved...


text:
Q: How to know if the oauth access token is expired Description
In Web Api project template, after sending a POST request to the Token endpoint: www.mycoolwebsite.com/Token, we get a Json similar to this:
{
   "access_token":"qkRwQD0A85...",
   "token_type":"bearer",
   "expires_in":14,
   "userName":"admin@mycoolwebsite.com",
   ".issued":"Wed, 24 Feb 2016 18:15:53 GMT",
   ".expires":"Wed, 24 Feb 2016 18:16:08 GMT"
}

On the client side, (let say a mobile application) I am saving this json on a file, and to see if the token is expired, I compare DateTime.UtcNow to token's .expires key.
Question
Is this the correct way to see if an access token has expired?
If not, what is the best way check this?

A: I wouldn't check the access token's expiry time. Rather than build a mechanism to check the expiration time and handle it, why not just send the access token you have to the API and, if you get a 401 back, request a new access token. You'll have to build in logic to handle 401's anyway...why not rely on that instead?


text:
Q: HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths I am using webpack and the HtmlWebpackPlugin to inject bundled js and css into an html template file.
new HtmlWebpackPlugin({
   template: 'client/index.tpl.html',
   inject: 'body',
   filename: 'index.html'
}),

And it produces the following html file.
<!doctype html>

    ...
    <link href="main-295c5189923694ec44ac.min.css" rel="stylesheet">

This works fine when visiting the root of the app localhost:3000/, but fails when I try to visit the app from another URL, for example, localhost:3000/items/1 because the bundled files are not injected with an absolute path. When the html file is loaded, it will look for the js file inside the non-exist /items directory because react-router hasn't loaded yet.
How can I get HtmlWebpackPlugin to inject the files with an absolute path, so express will look for them at the root of my /dist directory and not at /dist/items/main-...min.js? Or maybe I can change my express server to work around the issue?
app.use(express.static(__dirname + '/../dist'));

app.get('*', function response(req, res) {
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});

Essentially, I just need to get the line:

to have a slash at the start of the source.

A: in webpack config
config.output.publicPath = ''

in your index.html
<base href="/someurl/" />

this should do it.

A: Try setting the publicPath in your webpack config:
output.publicPath = '/'

HtmlWebpackPlugin use the publicPath to prepend the urls of the injects.
Another option is to set the base href in the  of your html template, to specify the base url of all relative urls in your document.
<base href="http://localhost:3000/">

A: In fact, I had to put :
output.publicPath: './';

in order to have it working in a non-ROOT path.
At the same time I was injecting :
   baseUrl: './'

into
<base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>">

With both parameter set, it worked like a charm.


text:
Q: ProtectedData.Protect Method with CurrentUser in ASP.NET web app In my ASP.NET web application I need to save a password in a database. (Note that this is not a login password and a user providing such password is given a visible security warning.) I was thinking to provide some scrambling for the password before placing it into the database.
So I was thinking to do this:
byte[] bytesToSave_Scrambled =
System.Security.Cryptography.ProtectedData.Protect(
    System.Text.Encoding.UTF8.GetBytes(password), null,
    System.Security.Cryptography.DataProtectionScope.CurrentUser);

The issue is that according to this page, when I use DataProtectionScope.CurrentUser only that same user account will be able to decode it back. I can of course use DataProtectionScope.LocalMachine instead, but the documentation says that it is less secure.
So my question is, when my web app runs on a web server, does it run under the same Windows user account to ensure consistency of the scrambling method above?


text:
Q: Explaining why the $F(x,y)=x^2+y^2$ has a minimum on $xy = 3$ but not a maximum
I have been asked to find the minimum value of the function $F:\Bbb{R}^2\to\Bbb{R}$, $F(x,y)=x^2+y^2$ on the curve $xy = 3$.

I found the minimum value with using Lagrange multipliers theorem. The answer is $(-\sqrt{3},-\sqrt{3})$ and $(\sqrt{3}, \sqrt{3})$; and when you place these into the function, the value is $6$, so the minimum value is $6$.
There are two problems now:

*

*In class the only way we learn to say if its minimum or maximum is to use weirshtrass theorem that saying that the function gets max and min and than choose between the potential max and min points. Here, i can't use weirshtrass theorem so i am not sure how i am supposed to prove this is a minimum point and not maximum point. I thought of taking another random point on the curve and just say that it's smaller than it but it's look not formal and strong.

*I need to explain why the function has minimum on the curve but does not have a maximum on the curve. I don't know what they want from me and how I am supposed to approach it.
At the bottom line, I think they miss to teach us all we need in class, so I am asking for explanation or a link to a video with explanation to this problem.

A: For the maximum, you can prove that F isn't bounded on the curve xy=3.
For any bound $M \geq 6$, we have with $(x,y) := (M,\frac{3}{M})$ that $xy=3$ and $f(x,y) = x^2 + y^2 = M^2 + \frac{9}{M^2} > M$

A: I edit my post to try to make the argument more clear.
$1$ variable case.
Claim: take $f:\mathbb{R} \to \mathbb{R}$ continuous such that $\lim_{x\to{-\infty}}f(x)=\lim_{x\to +\infty}f(x)=+\infty$ then $f$ has a minimum (not a maximum obviusly), this property is called coercivity. An example of coercive function is $ f_1(x)=x^2$ but also $f_2(x)=x^2+\arctan(45+\sin(x^{2/5}))$. They both explode to $+ \infty $ as $|x|$ grows. You can intuitively see that the minimum cannot be found far away from $0$ because they will be grater and grater as we move away. Rigorously take $f(0)=c$ the definitions of limits give us that there exists  a constant $R>0$ such that if $x>R$ then $f(x)>c$ , and if $x<-R$ $f(x)>c$. Therefore the $$\inf_\mathbb{R} f(x)=\inf_{[-R,R]}f(x)$$
the second infimum exists and is a minimum by Weierstass because we have restricted to a compact set ( we are not so far away from $0$).
2 variable case
The idea is the same, you have to observe that the function grows as you move away from the origin. For example you find that there is one point where the function attains the value $6$, now you can search the minimum only in the set $\{xy=3\} \cap \{x^2+y^2 \le 6\}$ which is compact!
In this case compactness is easy and I see now that coercivity is not needed, altought if you want to maximize a generic function $G(x,y)$ over $\mathbb{R}^2$ you need precisely this property.

A: Convert this into polar coordinates,
$x = r\cos\theta, y = r\sin\theta$
Curve $xy = 3 \implies r^2 \sin2\theta = 6$
We need to find min and max of $ \displaystyle f(r, \theta) = r^2 = \frac{6}{\sin2\theta} $
As $r \in \mathbb{R}, \sin2\theta \geq 0$ and $f$ is minimum when $\sin2\theta$ is maximum which is $1$.
$\therefore \min f(r, \theta) = 6$
Also you can clearly see there is no maximum as $\theta \to n\pi/2, f \to \infty$.


text:
Q: docker-compose no refleja los paquetes de node_modules en mi local El problema es el siguiente mi imagen se crea correctamente y se levanta igual. En el contenedor todos los paquetes de node_modules están pero no se ven reflejados en mi entorno local. La cual al abrir el editor me marca error.
Dockerfile
FROM node:10.16

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm i --quiet

COPY . .

EXPOSE 5000

CMD npm run dev

docker-compose.yml
version: '2'
services:
  work-today-api:
    build: .
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - "5000:5000"
      - "9229:9229"
    environment:
      - NODE_ENV=development

A: Este post me dio la solución a mi problema ya funciona correctamente.
Mi archivo docker-compose.yml quedo asi.
version: '2'
services:
  work-today-api:
    build: .
    volumes:
      - .:/usr/src/app
    ports:
      - "5000:5000"
      - "9229:9229"
    environment:
      - NODE_ENV=development
    command: bash -c "npm run dev"


text:
Q: Option to remove section from certain pages in wordpress I am currently creating a wordpress site. Some pages will need a section with some images at the bottom and other pages won't. But this needs to be controlled via the backend
So when you go on that specific page in the wordpress backend, there will need to be a check box to decide whether to display the section or not.
It has to be this simple as my client is not tech savvy in the slightest.
Is there a plugin to maybe achieve this?
Thanks in advance
Danny

A: Install the Advanced Custom Fields plugin. This way you can do a simple conditional along  the lines of if(get_field('myCheckbox'){ // add your images };
Further information can be found here: http://www.advancedcustomfields.com/resources/field-types/checkbox/
Update in response to comment
For a radio button, the code should be pretty similar - something like:

    $theField = get_field('name_of_radio_button_goes_here');
    if($theField == "enabled"){
        // THE HTML YOU WANT TO BE HIDDEN/SHOWN GOES HERE
    }

No need to add display:none or anything like that - unless "enabled" is selected for the page in Wordpress, then nothing will display for the page you are on


text:
Q: Pass params Using GET method using volley library How can we pass params from editText to url using request.GET method.
Actually I am trying to pass an email address as parameter to a api which should b attached to api-url .
I came to know from here that getParams() is not called on the GET method, so it seems you'll have to add it to the URL before you send the request.
suggest me  any solution to achieve the task ..
when i pass REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer@novatoresols.com";
it return success=true response as expected because is registered user
but if i set REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser and pass the params (get value from edittext and use params.put in getparams() method ).response is always success=false i.e params is not attached to url
here is my code.
    package com.example.mts3.hammadnewsapp;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class RegisterActivity extends AppCompatActivity {

    Button btn_verf;
    EditText et_Email;
    String u_emails,stat;
    AlertDialog.Builder alertDialog;
    private static final String TAG = "LoginActivity";
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    Context context;
//    public static String firstname, lastname, useremail, userphone, userpass;

//    String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer@novatoresols.com";
    String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        btn_verf=findViewById(R.id.btn_reg_send_vf_code);
        et_Email=findViewById(R.id.et_reg_email);
        alertDialog =new AlertDialog.Builder(RegisterActivity.this);
//        u_emails=et_Email.getText().toString().trim();

        btn_verf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callApi();
            }
        });
    }

    private void callApi() {
//        Log.e(TAG, "onClick: ");
        /*if (!utility.isInternetConnected()) {
            Toast.makeText(LoginActivity.this, "Please check your internet connection.", Toast.LENGTH_SHORT).show();
            return;
        }*/
//        dialog = utility.showProgressDialog(LoginActivity.this, "Please wait");
        final String email = et_Email.getText().toString().trim();

//        Log.e(TAG, "onClick: email = " + email );

//        JSONObject params = new JSONObject();
/*
        HashMap<String,String> params=new HashMap<>();
        params.put("email",email);*/
        /*try {
//            params.getString("email");
            params.put("email",email);
            Log.e(TAG, "getParams: param = " + "try of put prams");
        } catch (JSONException e){
            Log.e(TAG, "getParams: param = " + "catch of put prams");
            e.printStackTrace();
        }*/
        RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, REG_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(RegisterActivity.this, "REsponse: " + response, Toast.LENGTH_SHORT).show();
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> params=new HashMap<>();
//                params.put("email",email);
                params.put("email",email);
                return params;

            }
        };        queue.add(stringRequest);

    }
}

A: As suggested by @Puneet worked for me which is as :
getParams is only called for POST requests. GET requests don't have a body and hence, getParams is never called. For a simple request like yours just add the parameters to your URL and use that constructed URL to make that request to your server (REG_URL + "?email=" + email).

A: To pass the parameters, you need to create a class for the key-value pairs.
1) Create a class KeyValuePair with two fields key and value with appropriate constructor and getter-setter methods.
2) Now, for each parameter, you need to create an object of this class, i.e., for a key username with value user@gmail.com, the object would be new KeyValuePair("username", "user@gmail.com").
3) Now, you need to create a List to store these parameters and pass this list to the below method with your base url,
 public static String generateUrl(String baseUrl, List<KeyValuePair> params) {
    if (params.size() > 0) {
        for (KeyValuePair parameter: params) {
            if (parameter.getKey().trim().length() > 0)
                baseUrl += "&" + parameter.getKey() + "=" + parameter.getValue();
        }
    }
    return baseUrl;
}

4) Pass this baseUrl to your Request.


text:
Q: my js works in another browser but not in chrome when i click on button ajax must load more contents and to throw the user in top of the new load contents.Function worked perfectly in mozilla and IE but not in Chrome i don't know where is the problem. Thanks in advance.
if ($showMoreOffersButton) { ?>

            <a class="site-button blue" onclick="showMoreTourismOffers(<?php echo $offset; ?>)"
               onclick="ga('send', 'event', '<?= isset($parent_component) ? $parent_component : 'Unknown' ?>', 'Show More Offers' );">

                ОЩЕ ОФЕРТИ

    <? }

function showMoreTourismOffers(begin_offset) {
if (!btn_lock) {
    //check if user already visited this page and saw more than 16 boxes
    if (offset < begin_offset) {
        offset = begin_offset;
    }
    var mobileFlag;
    if(isMobile == 1){
        mobileFlag = true;
    }else{
        mobileFlag = false;
    }
    $.ajax({
        url: base_url + 'pochivki/show_more_offers/',
        type: 'POST',
        data: {
            filter: ajaxDealFilter(true, mobileFlag),
            country_index: countryIndex,
            region_index: regionIndex,
            city_index: cityIndex,
            offset: offset,
            current_url: window.location.href
        },
        success: function (data) {
            $('#tourism-deals-holder').append(data.deals);
            if (data.hideButton) {
                $('#show-more-tourism-offers-btn-holder').remove();
            }
             offset += 48;
            $('#travel-arrow-spinner').hide();
        },
        error: function () {
        },
        beforeSend: function () {
            btn_lock = !btn_lock; // becomes true
            $('#travel-arrow-spinner').show();
        },
        complete: function () {
            btn_lock = !btn_lock; // becomes false again
            $('.images-rotation').imagesRotation()
        },
        dataType: "json"
    });
}   }

A: solving this problem  i hope this help of anyone who have the same problem
function showMoreTourismOffers(begin_offset) {
if (!btn_lock) {
    //check if user already visited this page and saw more than 16 boxes
    if (offset < begin_offset) {
        offset = begin_offset;
    }
    var mobileFlag;
    if(isMobile == 1){
        mobileFlag = true;
    }else{
        mobileFlag = false;
    }

    var buttonPosition = $('#show-more-tourism-offers-btn-holder').position();
    var buttonPositionTop = buttonPosition.top;

    $.ajax({
        url: base_url + 'pochivki/show_more_offers/',
        type: 'POST',
        data: {
            filter: ajaxDealFilter(true, mobileFlag),
            country_index: countryIndex,
            region_index: regionIndex,
            city_index: cityIndex,
            offset: offset,
            current_url: window.location.href
        },
        success: function (data) {
            $('#tourism-deals-holder').append(data.deals);
            $('body').scrollTop(buttonPositionTop);
            if (data.hideButton) {
                $('#show-more-tourism-offers-btn-holder').remove();
            }
             offset += 48;
            $('#travel-arrow-spinner').hide();
        },
        error: function () {

        },
        beforeSend: function () {
            btn_lock = !btn_lock; // becomes true
            $('#travel-arrow-spinner').show();
        },
        complete: function () {
            btn_lock = !btn_lock; // becomes false again
            $('.images-rotation').imagesRotation()
        },
        dataType: "json"
    });
}

}


text:
Q: Windows 10 100% disk usage I have Windows 10 on my laptop, and I can't do nearly anything with it because my disk is kept on 100% even when I'm doing nothing.
Some of my observations:

*

*In most cases, the disk is eaten up by: Windows Antimalvare Executable, |OR| System and Compressed Memory, |OR| svchost

*Every item which were included using only 0.5-3.5 MB/S

*Edit: Now i have 2 min startup 100% then 10-15 min of smooth run, and then again 100%

Tried the followings:

*

*Disabled superfetch

*Disabled Windows searh

*Disabled all notifications

*Disabled pagefile

*Deleted all of theese cloud storage apps

Have no further idea about what should I do. Any other ideas?
Laptop: Asus X555UJ, Intel Core I5 6200U, 5400RPM 500GB HDD, 4GB RAM, Geforce GT 920M
EDIT: I can't do anything because it is so slow, what is slow? everything. Opening up apps, saving documents, even waiting for the start menu to come up.
Edit:

A: You should take a look at this question for Windows 8, because your issue is likely the same even though the OS is different. In short, HDDs score only a few MB/s in random reads/writes or on a fragmented file. Additionally, if your HDD is old and SMART tools e.g. CristalDiskInfo warn you about unstable or remapped sectors, the first noticeable symptom of such aging is also a severe performance drop when such sectors are accessed.
If you can't detect a specific software problem and defragmenting the drive doesn't help, buying a new HDD (or, better yet, an SSD) is the only long-term fix.

A: I got the same issue because of couple of things.

*

*I had OneDrive open at 2 locations and I was messing up with folders.

*I did select all in temp folder and deleted Temp files, but it failed to delete some files.

Then I ran sfc /scannow Command prompt by running it as administrator.
This is the result after completing. It may take 10-15 mins to complete.

After this, disk usage went down to normal.

A: I can't read the processes in task manager, but I do understand your frustration. I have a laptop with similar specs and the same problem.
In short, the problem is that you probably have a lot of programs and startup services and programs. This will use all of your HDD (hard drive) to read the data and launch the applications. The HDD in your laptop is just slow, and the only thing you can do is do a full (yes full) reset of Windows 10 and ONLY install the bare minimum of applications that you need.
I don't know when you posted this, but I can bet that you never fixed it unless you either upgraded your laptop, got a new laptop or reset Windows 10 (which probably didn't help that much).
Hope this helps!


text:
Q: Tips/tricks for architecting MVC in non-trivial desktop app What are some lesser known tips for implementing a loosely-coupled MVC structure in a non-trivial desktop application (e.g. having at least two levels of views/controllers and more than one model)?

A: Declare event handlers in your interfaces (important for the views).  This way you can loosely couple event handling which is managed by the controller.  You may need to use the InvokeRequired when working with the view if your application is multi-threaded.

A: Use interfaces.
A lot. I like using the "IDoThisForYou" style (even in a language where this isn't idiomatic) because an interface represents a role that another class can use.
Make the controllers responsible for controlling interaction
The controllers control interaction between domain objects, services, etc.
Use events to pass information between controllers
Let every controller who needs information subscribe to the event. Use an interface.
Don't put presentation information on your domain objects
Instead, allow the controller to create a presenter or view model which has the information you need. This includes no "ToString()". If you're in a language without multiple inheritance you might end up with a bit of duplication between presenters. That's OK - duplication is better than coupling, and the UI changes a lot anyway.
Don't put logic in your gui
Instead, allow the controller to create a presenter or view mdoel which has the information you need. This includes train wrecks like "MyAnimal.Species.Name" - make it present "SpeciesName" instead.
Test it
Manually. There is no substitute. Unit and acceptance testing goes a long way, but there's nothing like bringing the app up and actually using the mess you wrote for finding out how messy it is. Don't pass it to the QAs without having a go yourself.
Oh, and don't mock out domain objects in unit tests. It's not worth it. Use a builder.


text:
Q: How to run arbitrary code before each test re-run in watch mode in Jest? I need to run an arbitrary piece of code before each unit test re-run  in watch mode (to write a new hash or random generated number to the test.json file).
I had a problem when I was using "setupTestFrameworkScriptFile": "<rootDir>/setupTests.js" which is mentioned in Running a global test setup before each test in Jest
in Jest configuration. It works, but it adds my script to test files and runs forever. Unfortunately I couldn't fix the problem, even when I use "testPathIgnorePatterns" or "collectCoverageFrom".
Is there any better solution to this problem in Jest?


text:
Q: production.log empty on Rails 4 / Capistrano / Passenger / Nginx server (digital ocean) I have set up a rails 4 server on Ubuntu 12.04 using Capistrano, Nginx, Passenger, Postgres, Redis/Resque
Everything is working great, except that the production.log file is always empty.
I have tried a variety of configuration changes in production.rb to no avail.
It's definitely not a permissions issue, as the permissions on both the log dir and each of the logs are wide open (777)
Can anyone hep me figure out how to get basic logging working?

A: To clarify, the rails_12factor gem was responsible, but that's only because it includes rails_stdout_logging, which is the real culprit, however, due to it's intended behavior to "ensure that your logs will be sent to standard out."

A: Check with the log levels in production.rb file, config.log_level = :debug will display it's errors. Also make sure the server is running production mode, in case you have not made any changes any configuration files for rails env, production mode is by default.

A: The culprit was Heroku's rails_12factor gem
Removing that gem from the Gemfile, now the logs are working as expected.
# group :production do
#   gem 'rails_12factor'
# end


text:
Q: Can I async UIImageJPEGRepresentation writeToFile? I am doing the following when I get an image back from the server. But this code is bringing my app to its knees. It freezes up the UI.
Can this be run on a background thread in iOS? Can I use async?
 if (![NSString isEmpty:user.avatarURL])
 {
     NSString *pathToImage = user.avatarURL;
     NSURL *url = [NSURL URLWithString:pathToImage];
     NSData *data = [NSData dataWithContentsOfURL:url];
     UIImage *image = [[UIImage alloc] initWithData:data];

     [[NSUserDefaults standardUserDefaults] setObject:UIImageJPEGRepresentation(image, 1) forKey:kUserImage];

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,                                                                                NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     NSString* path = [documentsDirectory stringByAppendingPathComponent:@"userAvatar.png" ];
     NSData* jpegdata = UIImageJPEGRepresentation(image, 1);
     [jpegdata writeToFile:path atomically:YES];
 }

A: As @valentin says, you can do everything inside the if() statement in a dispatch_async() call.
Note I suspect what's probably slowing you down is actually the -dataWithContentsOfURL:, not the UIImageJPEGRepresentation(), so you'll want to make sure that's inside your dispatch_async, not outside.
Also, I'm not clear why you're decompressing the data into an image, then re-compressing it. You're going to get artifacts doing this, and with most services the avatar image is going to be compressed anyhow.
I'd do the following:
if (user.avatarURL)
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *const imageURL = [NSURL URLWithString:user.avatarURL];
        if (!imageURL)
            return;
        NSData *const imageDdata = [NSData dataWithContentsOfURL:imageURL];
        if (!imageDdata.length)
            return;

        [[NSUserDefaults standardUserDefaults] setObject:imageDdata forKey:kUserImage];

        [imageDdata writeToFile:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userAvatar.png"] atomically:YES];
    });

A: The line which is doing most damage is:
 NSData *data = [NSData dataWithContentsOfURL:url];

Because it does the download from the network. Nothing in your code updates the UI so it can all be run on a background thread. Just ensure that if you post a notification or subsequently update the UI after the image is saved that you switch back to the main thread.


text:
Q: Three.js : rotate cube and track faces positions I have a cube with colors or textures on faces.
I rotate it but I need to keep track of the position of the colors on the faces after each rotation.
For example, at the start, green is top, blue in front, and red is left.
So by clicking on "get position", I should get "gbr".
I click on "rotate".
Then the function getPosition() should return "rbn" (for red on top, blue on front, none on left).
Is there a way with three.js to do it?
Do cube.material, cube.geometry.vertices, cube.geometry.faces or anything else have this information?
Here is all the code :

scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
renderer = new THREE.WebGLRenderer({
  alpha: true
});
renderer.setSize(500, 500);
document.getElementById('cube').appendChild(renderer.domElement);

camera.position.x = -2;
camera.position.y = 2;
camera.position.z = 4;

var material = [
  new THREE.MeshBasicMaterial({
    color: '#000000'
  }), // right
  new THREE.MeshBasicMaterial({
    color: '#FF0000'
  }), // left
  new THREE.MeshBasicMaterial({
    color: '#00FF00'
  }), // top
  new THREE.MeshBasicMaterial({
    color: '#000000'
  }), // bottom
  new THREE.MeshBasicMaterial({
    color: '#0000FF'
  }), // front
  new THREE.MeshBasicMaterial({
    color: '#000000'
  }) // back
]
var cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material);
scene.add(cube);

var domove = false;
var stoprotation;

animate();

function animate() {
  requestAnimationFrame(animate);

  if (domove) {
    cube.rotation.z -= 0.05;
    if (cube.rotation.z <= stoprotation) {
      domove = false;
    }
  }

  renderer.render(scene, camera);
} // animate

function rotate() {
  if (domove) {
    console.log('SKIP : currently rotating');
    return;
  }
  stoprotation = cube.rotation.z - Math.PI / 2;
  domove = true;
} // move

function getPosition() {
  console.log(cube.material);
  console.log(cube.geometry.vertices);
  console.log(cube.geometry.faces);
}
body {
  margin: 0;
}

canvas {
  width: 100%;
  height: 100%
}

get position

rotate


text:
Q: Setting up a second TFDPhysFBDriverLink - possible and necessary? My application has a design time TFDConnection and TFDPhysFBDriverLink as source connection. This may or may not be opened in Firebird embedded mode (if so, FDPhysFBDriverLink.VendorLib := 'fbembed.dll' is set (32 bits)).
I create a run-time target TFDConnection which must use embedded Firebird because we do not know if Firebird is installed on the PC (our setup supplies fbembed.dll).
How do I set this up? At runtime I can create another TFDPhysFBDriverLink and set its VendorLib, but how does FireDAC know what its associated connection is? Or can I use only one FDPhysFBDriverLink in the application?
This is old code I'm converting, using DirectSQL, and this also used to set some magic SDFib.SqlApiDLL := FBEMBED property, which supposedly worked for the target database only.

A: Worst case in your situation is that Firebird is installed, so one connection connects to that installed server instance whilst another to the embedded one. For that is enough to have one physical driver object, but there's no problem having more.
So, drop one TFDPhysFBDriverLink on a form or datamodule and setup its DriverID property to a unique name (that is not used as base driver ID for any driver), and mark it as Embedded (that has no practical meaning in case when you specify VendorLib at this time, but you can use it to identify the driver; FireDAC uses this property only for decision which default library should be loaded).
Then for one connection use DriverID that you defined and for the other one use fallback to default Firebird driver settings by using its BaseDriverID (I've omitted settings unecessary for this task):
FDPhysFBDriverLink1.DriverID := 'FBEmbedded'; { ← ID not used by any BaseDriverID }
FDPhysFBDriverLink1.Embedded := True; { ← not mandatory when VendorLib is specified }
FDPhysFBDriverLink1.VendorLib := 'C:\fbembed.dll'; { ← client library file name }

FDConnection1.Params.DriverID := 'FB'; { ← driver's BaseDriverID }
FDConnection1.Open; { ← this will connect to the installed server }

FDConnection2.Params.DriverID := 'FBEmbedded'; { ← driver's DriverID }
FDConnection2.Open; { ← this will connect to the embedded server }

But I would prefer having two separate driver objects, one for installed server (with default settings, like base driver has) and one for embedded server. For example:
FDPhysFBDriverLink1.DriverID := 'FBEmbedded'; { ← ID not used by any BaseDriverID }
FDPhysFBDriverLink1.Embedded := True; { ← not mandatory when VendorLib is specified }
FDPhysFBDriverLink1.VendorLib := 'C:\fbembed.dll'; { ← client library file name }

FDPhysFBDriverLink2.DriverID := 'FBInstalled'; { ← ID not used by any BaseDriverID }

FDConnection1.Params.DriverID := 'FBEmbedded'; { ← driver 1 DriverID }
FDConnection1.Open; { ← this will connect to the embedded server }

FDConnection2.Params.DriverID := 'FBInstalled'; { ← driver 2 DriverID }
FDConnection2.Open; { ← this will connect to the installed server }


text:
Q: allow a user to run specific monit action I have installed monit for many applications with the root user.
One of the applications is started with a non-root user account.
Unfortunately, when I
 update my app, I also need to restart it. My update process uses the non-root user (I use capistrano to udpate my app)
Since Monit is checking this app and the update process is done with the non-root user. In order to restart the app, the non-root user kills the app and monit restarts it.
I would like to allow the non-root user to be allowed to only restart this specific app. This user shouldn't be aloud to run other monit related actions.
Is there a way to allow a user run a specific monit action, even if he is not the owner of the monitrc ?

A: Add an entry to /etc/sudoers...
%non-root-group ALL=NOPASSWD:/usr/bin/monit

or
non-root-user ALL=NOPASSWD:/usr/bin/monit

or
non-root-user ALL=NOPASSWD:/usr/bin/monit reload # to give a specific Monit command.

A: According to https://mmonit.com/monit/documentation/monit.html#CONFIGURATION-EXAMPLES, you can use a configuration with

start program ...as uid "capistrano" and gid "users"

Maybe this does what you want?


text:
Q: Overriding sass media query mixins I'm having trouble getting style to change as set within my media query mixing includes. I'm writing mobile first style then declaring the styles for larger screens within these media queries.
At the top of the doc I have.
@mixin breakpoint($point) {
  @if $point == medium {
    @media (min-width: em(480)) { @content; }
  }
}

@mixin breakpoint($point) {
  @if $point == large {
    @media (min-width: em(800)) { @content; }
  }
}

Then throughout I have styles written like this:
.col-1-4 {
    width: 100%;
    padding: 0;

    @include breakpoint(medium) {
        width: 50%;
        padding-right: em(10);

        &:nth-child(2n) {
            padding-right: 0;
            padding-left: em(10);
        }

    }

    @include breakpoint(large) {
        width: 25%;

        &:nth-child(4n) {
            padding-right: 0;
        }
   }

}

The style for large show up at the desired min-width but not the medium styles.
If I switch the mixing at the top to:
@mixin breakpoint($point) {
  @if $point == large {
    @media (min-width: em(800)) { @content; }
  }
}

@mixin breakpoint($point) {
  @if $point == medium {
    @media (min-width: em(480)) { @content; }
  }
}

The styles change at min-width medium but not large.
How can I have the styles I want to take affect at the desired min-width?
My compiled CSS looks like this:
.col-1-4 {
  width: 100%;
  padding: 0; }
  @media (min-width: 50em) {
    .col-1-4 {
      width: 25%; }
      .col-1-4:nth-child(4n) {
        padding-right: 0; } }

If I swap the mixins at the top it only compiles the one written at the top.
Any help would be great.

A: The problem is that you're defining your breakpoint mixin twice, which is causing the first one to be overwritten.
@mixin breakpoint($point) {
  @if $point == medium {
    @media (min-width: em(480)) { @content; }
  } @else if $point == large {
    @media (min-width: em(800)) { @content; }
  }
}


text:
Q: Finding area between two graphs. Find the area between the graphs of $ f(x) = (3x-2)^{10} $ and $ g(x) = 3x-2 $.
I just got the $ x's $ and can't continue.
$ x = \frac{2}{3} or \;x = 1 $

A: From where you left off, you determined the values of $x$ for the intersection points.  If we work out the substitution of those values, then we have
$$\begin{aligned}
f\left(\dfrac{2}{3} \right) &= \left(3 \cdot \dfrac{2}{3} - 2 \right)^{10} = 0 = g\left(\dfrac{2}{3} \right)\\
f(1) = g(1) &= 1
\end{aligned}$$
So the coordinates of those intersection points are $\left(\frac{2}{3},0 \right)$ and $(1,1)$.
The graphs of the function $f(x)$ and $g(x)$ are here.
For the integral setup, we use the $x$-bounds (so we need to express the equation in terms of $x$).  Since the graph of $f(x) = (3x - 2)^{10}$ is below the graph of $g(x) = 3x - 2$, from the link I posted, we see that $f(x)$ is the lower function while $g(x)$ is the upper function within the interval $\frac{2}{3} \leq x \leq 1$.  For this case, the area of the region is
$$\begin{aligned}
\text{Area} &= \int_{\frac{2}{3}}^1 (\text{upper} - \text{lower})\,dx\\
&= \int_{\frac{2}{3}}^1 \left(3x - 2 - (3x - 2)^{10}\right)\,dx\\
&= \int_{\frac{2}{3}}^1 (3x - 2)\,dx - \int_{\frac{2}{3}}^1 (3x - 2)^{10}\,dx\\
&= \left.\dfrac{3}{2}x^2 - 2x - \dfrac{1}{3}\cdot \dfrac{(3x - 2)^{11}}{11}\right\vert_{x = \frac{2}{3}}^{x = 1}\\
&= \dfrac{3}{22}
\end{aligned}$$


text:
Q: Value of select list (dropdown) not shown just the (unwanted) indexnumbers I know questions like this are asked before, but i can't find the correct answer for my question.
Within a HTML form i have a select list (dropdown) named "custnames" which is filled from a database (within PHP).
The HTML page is saved as a tpl file because i work with Smarty.
All the values (custnames) are shown correctly in the list when i click the dropdown select box.
When i click the submit button i can't get the chosen name from the select list into the $_POST["custnames"].
The only thing the $_POST["custnames"] has is the index number from the chosen option from the select list.
How can i get the chosen name from the dropdownlist into the $_POST["custnames"] instead of the index number of that name.
All other fields have also Smarty tags and work fine with their respective $_POST[]
I searched the web for a long time now and tried many things but nothing works so far.
I use the same code like the example wich comes from a studybook about Smarty.
HTML(Smarty) code:
<td colspan="2">
    <select name="custnames" class="gewonetekst" id="custnames">
        {html_options options=$custnames selected=$cust}
    </select>
</td>

The list is filled from a database wich is working fine.
PHP code:
$klt_array = array();
while ($row = mysql_fetch_assoc($result))
{
    $klt_array[] = $row[name]
}

$m_objSmarty->assign('custnames', $klt_array);

When i click on the selectlist i see all the names correctly in the select (dropdown) list.
All other (Smarty) fields work fine with their respectiv $_POST[] exept this one.
T.i.a.
Regards,
Tino, The Netherlands.

A: Seems like you haven't set  "value" attribute of custnames option tags with the proper value.
Check if they are defined as
<option value="My_custname_1">My_custname_1</option>

Surely not. You should put the same tag inside option tags and value attribute in your smarty template if you want to receive the same as shown


text:
Q: how to delete all files except the latest three in a folder I have a folder which contains some subversion revision checkouts (these are checked out when running a capistrano deployment recipe).
what I want to do really is that to keep the latest 3 revisions which the capistrano script checkouts and delete other ones, so for this I am planning to run some command on the terminal using a run command, actually capistrano hasn't got anything to do here, but a unix command.
I was trying to run a command to get a list of files except the lastest three and delete the rest, I could get the list of files using the following command.
(ls -t /var/path/to/folder |head -n 3; ls /var/path/to/folder)|sort|uniq -u|xargs

now if I add a rm -Rf to the end of this command it returns me with file not found to delete. so thats obvious because this returns only the name of the folder, not the full path to the folder.
is there anyway to delete these files / folders using one unix command?

A: Below is a useful way of doing the task.......!!
for Linux and HP-UX:
ls -t1 | tail -n +50 | xargs rm -r       # to leave latest 50 files/directories.
for SunOS:
rm `(ls -t |head -n 100; ls)|sort|uniq -u`

A: Alright, there are a few things wrong with your script.
First, and most problematically, is this line:
ls -t /var/path/to/folder |head -n 3;

ls -t will return a list of files in order of their last modification time, starting with the most recently modified. head -n 3 says to only list the first three lines. So what this is saying is "give me a list of only the three most recently modified files", which I don't think is what you want.
I'm not really sure what you're doing with the second ls command, but I'm pretty sure that's just going to concatenate all the files in the directory into your list. That means when it gets sorted and uniq'ed, you'll just be left with an alphabetical list of all the files in that directory. When this gets passed to something like xargs rm, you'll wipe out everything in that directory.
Next, sort | uniq doesn't need the uniq part. You can just use the -u switch on sort to get rid of duplicates. You don't need this part anyway.
Finally, the actual removal of the directory. On that part, you had it right in your question: just use rm -r
Here's the easiest way I can think to do this:
ls -t1 /var/path/to/folder | tail -n +4 | xargs rm -r

Here's what's happening here:

*

*ls -t1 is printing a list, one file/directory per line, of all files in /var/path/to/folder, ordering by the most recent modification date.

*tail -n +4 is printing all lines in the output of ls -t1 starting with the fourth line (i.e. the three most recently modified files won't be listed)

*xargs rm -r says to delete any file output from the tail. The -r means to recursively delete files, so if it encounters a directory, it will delete everything in that directory, then delete the directory itself.

Note that I'm not sorting anything or removing any duplicates. That's because:

*

*ls only reports a file once, so there are no duplicates to remove

*You're deleting every file passed anyway, so it doesn't matter in what order they're deleted.

Does all of that make sense?
Edit:
Since I was wrong about ls specifying the full path when passed an absolute directory, and since you might not be able to perform a cd, perhaps you could use tail instead.
For example:
 ls -t1 /var/path/to/folder | tail -n +4 | xargs find /var/path/to/folder -name $1 | xargs rm -r

A: Hi I found a way to do this we can use the unix &&
so the command will look like this
cd /var/path/to/folder && ls -t1 /var/path/to/folder | tail -n +4 | xargs rm -r


text:
Q: Signal Strength not refreshing every few seconds I have a code which tells me the signal strength from the wifi. Now, I wished that it should refresh every 5 seconds and tell me the new signal strength.

*

*It gives a set of signal strength 5 times and every time it gives me the same signal strength. I dont know why.

*Once install on my android device it gives me the signal strength which is same as the answer of signal strength when it was installed first. So, whenever I run the application on the android device, I get the same answer.
The code is :
I get the answer in dbm.
    public class MainActivity extends Activity {
            protected static final long TIME_DELAY = 5000;
            TextView mTextView;
            Handler handler=new Handler();
            int count =0; String data ="";

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                mTextView = (TextView) findViewById(R.id.text_id);
                handler.post(updateTextRunnable);

            }

 @Override
                public void onResume() {
                    super.onResume();
                    // Register the scan receiver

                    registerReceiver(wifiReciever);
                }

                @Override
                public void onPause() {
                    super.onPause();
                    // Register the scan receiver

                    unregisterReceiver(wifiReciever);
                }

            Runnable updateTextRunnable = new Runnable() {
                public void run() {
                    if (count < 5) {
                        StringBuilder sb = new StringBuilder();
                        WifiManager mainWifiObj;
                        mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                        class WifiScanReceiver extends BroadcastReceiver {
                            public void onReceive(Context c, Intent intent) {

List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
                        for (ScanResult result : wifiScanList) {
                            if (result.SSID.equals("Khosla ka Ghosla")) {
                                sb.append(""+result.level);
                            }
                            if (result.SSID.equals("panny")) {
                                sb.append(""+result.level);
                            }
                            if (result.SSID.equals("ferbora")) {
                                sb.append(""+result.level);
                            }
                        }
                            }
                        }
                        WifiScanReceiver wifiReciever = new WifiScanReceiver();
                        registerReceiver(wifiReciever, new IntentFilter(
                                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

                        count++; mTextView.setText("getting called " +count + sb);
                    } else {

                    }
                        //----------------code here to send values to java server---
                          handler.postDelayed(this, TIME_DELAY);
                            }
                    };
    }

Please help me. Thanks in advance.

A: You are going about this all wrong.
mainWifiObj.getScanResults(); gets the last-updated scan results. These are not updated right away. You need to make a call (which you do) to register a receiver to listen for changes in the wifi signals. The receiver's onReceive method will automatically be called every time the signal strength changes - so you don't need to call your Runnable over and over.
Just handle all the code from List<ScanResult> wifiScanList = mainWifiObj.getScanResults();, onward in the onReceive method of WifiScanReceiver, and register this receiver in onResume, and unregister it in onPause.
You will also benefit from having a look at the source code for the WiFi Settings app on Android, which is available here.


text:
Q: Powershell script foreach ($x in $y) not working correctly Just writing some basic scripts after avoiding PowerShell for too long and I'm getting kinda stuck here. Trying to pass multiple parameters to a single "argument" in a function but it will only ever return the first value in the string
#--------------------------------
# Returns logged on user of machine(s) given in parameter
#--------------------------------
function Get-UserLogged{
    param($computerName)
    foreach ($computer in $computerName) {

        return (query user /server:$computerName)
    }
}

Now if i call the function and run for example...
Get-UserLogged Server01 Server02 Server03

It will only return the output for server 1, so it seems that the foreach isn't working as expected
Different script same issue:
function p{
    param($computerName)

    foreach ($computer in $computerName) {

        return (test-connection $computer -Count 1)

    }

}

if I run:
p localhost, google.com, bbc.com

it will only attempt localhost

A: You're referencing the array $computerName inside the loop, not the "current item", $computer.
function Get-UserLogged{
    param($computerName)
    foreach ($computer in $computerName) {

        query user /server:$computer
    }
}

To pass an array of strings to a parameter, use a comma to separate the items:
Get-UserLogged -computerName Server01, Server02, Server03


text:
Q: G+ Domain API Google Apps Script Public Posts Scan I'm running a script that scans our domain users G+ posts and flags any post shared publicly and then sends an email notification with a link to the post to the end user. The script was written by someone else who is no longer with the company. I want to change the script so that it will flag any post that does not have "domainRestricted";True.
Here's an output of a scanned post with the type of access associated "domainRestricted":True. This post is shared within the domain.
{
  "description":"Shared privately",
  "domainRestricted":true,
  "kind":"plus#acl"
}

Here's an output example of a scanned post without domainRestricted access. This post is shared with a Circle containing users outside of the domain, essentially Public.
{
  "description":"Shared privately",
  "kind":"plus#acl"
}

Here's an output example of a scanned post with Public as the access. This post was explicitly shared publicly.
{
  "items":[{"type":"public"}],
  "description":"Public",
  "kind":"plus#acl"
}

I want to change this code, to scan for any posts that does not contain the access "domainRestricted":True.
function checkPublicPosts( userId ) {
  var publicPosts = Array();
  var pageToken;

  try {
    do {
      Logger.log( 'Scanning posts by ' + userId );

      // Search for all Google Plus posts by userId
      posts = PlusDomains.Activities.list( userId, 'user', {
        maxResults: 100,
        pageToken: pageToken
      });

      // If posts are found, check to see if they are public
      if( posts.items ) {
        for( var i = 0; i < posts.items.length; i++ ) {
          var post = posts.items[i];

          var public = false;
          if( !post.access.domainRestricted && ( typeof( post.access.items ) != 'undefined' ) ) {
            for( var j = 0; j < post.access.items.length; j++ ) {
              if( post.access.items[j].type = 'public' ) {
                public = true;
                j = post.access.items.length;
              }
            }
          }

          // If a post is public, add it to the list of public posts for userId
          if( public ) publicPosts.push( post );
        }
      }

      // If user has more than 100 posts, continue with the analysis of subsequent batches of 100
      pageToken = posts.nextPageToken;

    } while (pageToken);

  } catch( err ) {
    // The code above sometimes fails for unexpected reasons. We
    // log this error.

    Logger.log( 'Failed on ' + userId + ' with error ' + err );
  }
  return publicPosts;
}

Can anyone help me?


text:
Q: MergeSort in python def merge(A,l,m,r):

    i = l
    j = m+1
    new = []

    while i <= m and j <= r:
        if A[i] <= A[j]:
            new.append(A[i])
            i += 1
        else:
            new.append(A[j])
            j += 1

    while i <= m:
        new.append(A[i])
        i += 1

    while j <= r:
        new.append(A[j])
        j += 1

    return new

This function doesn't work due to an error, can you help me to understand what is the error and how to fix it?

A: This statement doesn't make sense:
return new

Since you nowhere use the return of the function. So the function merge() does nothing.
I believe you need to change the array A directly inside the function. No need to create and return the new array.


text:
Q: splitting a CSV and keeping the header without intermediate files I am trying to split a dozen 100MB+ csv files into managable smaller files for a curl post.
I have managed to do it but with a lot of temporary files and IO. It's taking an eternity.
I am hoping someone can show me a way to do this much more effectively; preferably with little to no disk IO

#!/bin/sh

for csv in $(ls *.csv); do
    tail -n +2 $csv | split -a 5 -l - $RANDOM.split.
done

# chose a file randomly to fetch the header from

header=$(ls *.csv |sort -R |tail -1 | cut -d',' -f1)

mkdir split

for x in $(/usr/bin/find . -maxdepth 1 -type f -name '*.split.*'); do
    echo Processing $x
    cat header $x >> split/$x
    rm -f $x
done

The above script may not entirely work. I basically got it working through a combination of these commands.
I decided to make the curl POST another step entirely in the case of upload failure; I didn't want to lose the data if it were all posted. But, if, say, on error from curl the data could be put into a redo folder then that can work.
#!/bin/sh

# working on a progress indicator as a percentage. Never finished.
count=$(ls -1 | wc -l 2> /dev/null | cut -d' ' -f1)

for file in $(/usr/bin/find . -maxdepth 1 -type f); do
    echo Processing $file
    curl -XPOST --data-binary @$file -H "Content-Type: text/cms+csv" $1
done

A: An entirely different approach would be to use GNU parallel, and use its --header and --pipe options:
cat input.csv | parallel --header : --pipe -N 10 'cat > output{#}.csv'

This will get you 11 lines in each of the files (the header line plus the ten from -n 10, except in the last file written that way).


text:
Q: What are the disadvantages/flaws/faults of Object Orientation in general? Object orientation is probably the most dominant programming paradigm today. Some people say, there are certain disadvantages, flaws or faults to this paradigm. Some even consider it a complete failure. What are the concrete reasons/arguments for that?

A: What I found the biggest flaw of OOP is that the most prominent frameworks/methods encourage writing not object-oriented code. If we are developing service and DAO layer with no state at all (just business methods passing arguments from layer to layer) and have a domain model with no logic at all (just a bunch of fields and maybe getters/setters/properties), it is no longer OOP. Most of the enterprise projects, even considered to be well written, aren't actually object oriented. They have a collection of functions grouped together in logical namespaces (called classes) and a collection of data structures, having private fields to annoy programmers (called domain). The domain does not have any operations.
IMHO OOP model was sacrificed in enterprise applications because it does not handle concurrency properly (or maybe because people prefer to have a stable set of objects rather than creating new instance per request ?!?). This is probably the reason why functional languages (and immutable objects to some degree) are getting much more attention.
On the other hand, are immutable objects actually in the spirit of OOP? I am not sure.


text:
Q: CORS blocks a request from frontend to Flask server when started with docker compose Description
I have a React application that makes the following request:
await axios.get(`${process.env.REACT_APP_MASTER_HOST}/api/agl-history`, { headers: { Authorization: `Bearer ${token}` }, data: { label, date } });

In some cases it works but when the backend is started with docker-compose up -d, it gives me the following in Chrome:
Access to XMLHttpRequest at 'http://localhost:8080/api/agl-history' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When it works

*

*When I manually build the image with sudo docker build . -t test and run, sudo docker run -p 8080:8080 -t test, it works perfectly

*When I run the flask server with flask run --host=0.0.0.0
When it does not work

*

*docker-compose up -d
// docker-compose.yml, relevant service is master
version: "3.9"
services:
  agl-history:
    depends_on:
        - mariadb
    build: ./agl-history
    restart: on-failure
    networks:
        - main
  master:
    depends_on:
        - mariadb
    build: ./master
    restart: on-failure
    ports:
        - 8080:8080
    networks:
        - main
  mariadb:
    image: "mariadb:10.5.10"
    restart: on-failure
    environment:
        MYSQL_ROOT_PASSWORD: ${MARIADB_PASSW}
    ports:
        - 3306:3306
    volumes:
        - /var/lib/docker/volumes/add3-data:/var/lib/mysql
    networks:
        - main
networks:
    main:
        driver: bridge

// Dockerfile
FROM python:3.9.5-buster

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .

ENV FLASK_RUN_PORT 8080
ENV FLASK_APP source/server_config.py

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

// Flask endpoint
from datetime import date
from flask import Flask
from flask import jsonify
from datetime import datetime
from flask_cors import CORS

# app reference
app = Flask(__name__)
cors = CORS(app)

# This method executes before any API request
@app.before_request
def before_request():
    print('before API request')

@app.route('/api/agl-history', methods=['GET'])
def get_agl_history():
    print('during')
    response = jsonify([
        {
            'id': 1,
            'customerId': 777,
            'campaignName': 'Test campaing',
            'adGroupName': 'Test ad group',
            'execDate': datetime.now(),
            'label': '92'
        }
    ]
    )
    return response

# This method executes after every API request.
@app.after_request
def after_request(response):
    return response

Notes

*

*React frontend and server backend is going to be run on different hosts eventually

What am I doing wrong? Any help is greatly appreciated! Thanks!

A: I think the issue comes from your Flask backend and it's CORS headers. I'd suggest using --host=127.0.0.1 in your flask command. Also, check this answer, it provides a lot of information.

A: It could be that browser is sending preflight ( OPTIONS ) request because you have Authorization headers , i had same problem before with react dev server and express,
I solved the problem with , OPTIONS route on same path with :
Access-Control-Request-Headers : Authorization
But i am maybe wrong here , because cors is confusing thing :)

A: Browers issue preflight request(OPTION call) when the origin (frontend localhost:3000) is different from the API origin (localhost:8080)
For development, you can allow all the origin in the flask server. This is the default configuration. Seems this is the case with your working scenarios
But when running via the docker-compose the hostname of the flask server would be master. From your failing scenario, it seems, flask does only accept from that hostname.
So when deploying in a production environment I would suggest adding cors origin configuration allowed origin as front end domain
For your docker-compose scenario, you could configure below in flask server
CORS_ORIGINS: "localhost:3000"

A: I did not realize that docker-compose does not rebuild images by default so I was using an older build that did not have CORS enabled.
The only change that was needed to fix the issue was:
cors = CORS(app, origins="*")

when starting flask server. Then, start the services with:
sudo docker-compose up -d --build master


text:
Q: Why did S.H.I.E.L.D. leave such an important object so undefended? This question is about the end of season three of Agents of S.H.I.E.L.D.
After they

trap Hive in a gel matrix and take him back to base

they just leave it in the hangar with the hangar doors wide open and a couple mall cops.
I understand the hangar doors were still damaged, but why leave it out there? That's idiotic and makes no sense. This was a terrible black spot on an otherwise good episode and season. Or, if it needed to be out there for some unexplained reason, why not put it under heavy guard? Even after the bomb went off, a couple of guards with guns could have solved things with bullets.
In all likelihood, everything would have been fine if they'd just taken some reasonable precautions. I guess that's what Coulson meant by "our mistakes"?

A: The reason it was left out in the dock was because there was no adequate storage facility ready inside the base, and Fitz needed to be there to oversee the transport.
There was no reason for the lack of guard duty, at least heavier guarding or one of the tougher veterans such as Mack or May should have been guarding it at all times, especially since there were known operatives still at the loose.
The reason they couldn't get the situation under control was because they were using icers which have no effect on the intruders. Bullets would have been the far better choice as we know they work, however SHIELD are known for using more non-lethal tactics hence the guards being equipped with icers.
I believe the mistake Coulson was referring to was when he 'crossed the line' as he mentioned in the episode. He sees that event as the catalyst that allowed it all to happen.
That was my take on it all!


text:
Q: Capistrano: cap aborted! Don't know how to build task 'deploy:setup_config' I'm deploying a Rails 4.0 app to an ubuntu server using capistrano 3.2.1 but I'm getting the error when I try running capistrano commands.
cap aborted!
Don't know how to build task 'deploy:setup_config'

This are the commands I have tried
cap production rvm:check
cap production deploy

Here is my deploy.rb file
lock '3.2.1'

set :application, 'app_name'
set :repo_url, 'git@github.com:GITUSERNAME/REPO.git'

set :deploy_user, 'deploy'
set :use_sudo, false

set :ssh_options, {:forward_agent => true, :keys => %w(/home/USER/.ssh/id_rsa)}

# Default branch is :master
# ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }.call

# Default deploy_to directory is /var/www/my_app
set :deploy_to, '/var/www/app_name'

 set :scm, :git
 set :scm_passphrase, ""

 set :format, :pretty
 set :log_level, :debug

set :linked_files, %w{config/database.yml}

set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}

 set :keep_releases, 5

set :tests, []
set(:config_files, %w(
  nginx.config
  database.example.yml
  ))

set(:symlinks, [
  {
    source: "nginx.conf",
    link: "etc/nginx/sites-enabled/#{fetch(:full_app_name)}"
  }
  ])

namespace :deploy do
  before :deploy, "deploy:check_revision"
  before :deploy, "deploy:run_tests"
  before 'deploy:setup_config', 'nginx:remove_default_vhost'

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      # Your restart mechanism here, for example:
       execute :touch, release_path.join('tmp/restart.txt')
    end
  end

  after 'deploy:smylink:shared', 'deploy:compile_assets_locally'
  after :finishing, 'deploy:cleanup'

  after 'deploy:setup_config', 'nginx:reload'
  after :publishing, :restart

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end

end

here is my Capfile.rb
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rvm'
require 'capistrano/rails'
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

production.rb
set :stage, :production
set :branch, "master"
set :full_app_name, "#{fetch(:application)}_#{fetch(:stage)}"
set :server_name, "SERVERURL"
set :rails_env, :production
role :app, %w{deploy@example.com}
role :web, %w{deploy@example.com}
role :db,  %w{deploy@example.com}
server 'SERVERURL', user: 'deploy', roles: %w{web app db}, primary: :true

I know there is no cap deploy:setup_config command in capistrano 3. What am I not doing right?

A: You need
 cap deploy:setup

not
 cap deploy:setup_config

Checkout this for more info


text:
Q: How to grant user who can commit directly to protected branch on GitHub I am using a repository which has a protected branch.
How to grant an user who can commit directly to protected branch on GitHub.
I am admin so I don't want to grant other guide to become a admin (Who can delete the repository)

A: You can give the user "write" permission, instead of full "admin" permission. See https://help.github.com/articles/repository-permission-levels-for-an-organization/.


text:
Q: Horde Authentication Backend Configuration I've installed Postfix, Postfixadmin, Dovecot and Horde successfully on Kubuntu 12.04.
When I go to mail.mydomain.com, it goes to the Horde dummy administration page.
When I tried to Add User, it says "Your authentication backend does not support adding users. If you wish to use Horde to administer user accounts, you must use a different authentication backend."
How can I use "Different authentication backend" ??

A: The error you get means that you use a authentication backend which cannot write to users database.
Assuming you have updated to the latest Horde version (5.1.5), I suppose in your Horde config (-> Administration/Configuration/Horde/Authentication) you are using the default "IMP auth" backend (which normally uses IMAP backend), thus you cannot write/add users to IMAP backend.
If you want to add new users over Horde web-access config panel, you have to select an other authentication backend first - select (and configure) SQL or LDAP backends (in Administration/Configuration/Horde/Authentication), they support addding users (because you can write to these backends - you cannot write to IMAP).
Regards,
Megodin


text:
Q: How to go to "APP for Sharepoint" page sharpoint online I have developed an spfx webpart and i need to upload the same in sharepoint site. Could please guide me how to go to that "Apps for sharepoint" site.

A: Do you mean that you want to upload web parts to app catalog?

If so, you have to prepare an App Catalog site collection:

*

*https://learn.microsoft.com/en-us/sharepoint/use-app-catalog


text:
Q: Why does this CUDA example kernel have a for loop? I have been looking at the following example from the official CUDA website:
http://docs.nvidia.com/cuda/cuda-samples/index.html#simple-cufft
Download here: http://developer.download.nvidia.com/compute/DevZone/C/Projects/x64/simpleCUFFT.zip
It contains the following kernel:
// Complex pointwise multiplication
static __global__ void ComplexPointwiseMulAndScale(Complex *a, const Complex *b, int size, float scale)
{
    const int numThreads = blockDim.x * gridDim.x;
    const int threadID = blockIdx.x * blockDim.x + threadIdx.x;

    for (int i = threadID; i < size; i += numThreads)
    {
        a[i] = ComplexScale(ComplexMul(a[i], b[i]), scale);
    }
}

My question is, why is there a for loop here? Doesn't CUDA simultaneously call an array of thread? I removed the thread, replacing it with the following code and it produced the same output.
// Complex pointwise multiplication
static __global__ void ComplexPointwiseMulAndScale(Complex *a, const Complex *b, int size, float scale)
{
    const int threadID = blockIdx.x * blockDim.x + threadIdx.x;

    a[threadID] = ComplexScale(ComplexMul(a[threadID], b[threadID]), scale);
}

As this is an official example on the CUDA website, I imagine I must be missing something.

A: Your version is basically what happens when numThreads is equal to size (but only then).
What the official example does is the following: Suppose numThreads is equal to 4 (for simplicity, usually it will be much larger), and consider the array positions (both for a and b):
  a or b                  x x x x x x x x
  thread that works here  0 1 2 3 0 1 2 3

Then the first thread will work on all array position divisible by 4, et cetera.
The problem with your version is that the caller of your function will have to make sure that there are as many threads as size is large. For example, if you call your version with a 1-dim grid and both gridDim.x and blockDim.x being 2, but on vectors of length 8, then half of your vector isn't processed!
The official example works regardless - no matter how many threads the caller assigns to it, the entire vector will be processed.


text:
Q: Import Module Benchmark I have been doing some performance testing and got rather curious at my latest findings.
>>> timeit("import timeit")
0.8010718822479248
>>> timeit("from timeit import timeit")
1.3421258926391602

How can importing the whole module be faster, than importing just a specific part ?
Based on the answers, I have been doing some tests and I came across the following:
>>> timeit("x = timeit.timeit", setup="import timeit")
0.09205102920532227
>>> timeit("x = timeit", setup="from timeit import timeit")
0.0244600772857666

Regarding performance, if you plan on using a class/function/submodule a lot, it takes less time if you specify where to import from and can  offset or even make up for the time lost in the import.

A: import timeit will get the module directly while from timeit import timeit will take time browsing entire timeit module. Hence the results.

A: Because when you want to import one/some part of a module, all the searching through the module's namespace, storing the object in stack and pop from it take time, while for importing the module at once python just does one step, binding the module to its name.
For a better demonstration you can use dis module for checking the bytecode for two recipes separately:
In [10]: def import_all():
    import timeit
   ....:

In [11]: def import_one():
   ....:     from timeit import timeit
   ....:

In [12]: import dis

In [13]: dis.dis(import_all)
  2           0 LOAD_CONST               1 (0)
              3 LOAD_CONST               0 (None)
              6 IMPORT_NAME              0 (timeit)
              9 STORE_FAST               0 (timeit)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE

In [14]: dis.dis(import_one)
  2           0 LOAD_CONST               1 (0)
              3 LOAD_CONST               2 (('timeit',))
              6 IMPORT_NAME              0 (timeit)
              9 IMPORT_FROM              0 (timeit)
             12 STORE_FAST               0 (timeit)
             15 POP_TOP
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE

As you can see in second case we have an IMPORT_FROM and POP_TOP more than the first one.


text:
Q: Why did not I get NotSerializableException? class NotSerializable {}

class MyClass implements Serializable {
   private NotSerializable field; // class NotSerializable does not implement Serializable!!
}

public class Runner {
   public static void main(String[] args) {
      MyClass ob = new MyClass();

      try {
         FileOutputStream fs = new FileOutputStream("testSer.ser");
         ObjectOutputStream os = new ObjectOutputStream(fs);
         os.writeObject(ob);
         os.close();
      } catch (IOException e) {
          e.printStackTrace();
      }

      try {
         FileInputStream fis = new FileInputStream("testSer.ser");
         ObjectInputStream ois = new ObjectInputStream(fis);
         MyClass copyOb = (MyClass) ois.readObject();
         ois.close();
      } catch (Exception e) {
          e.printStackTrace();
      }
   }
}

This program executes correctly and successfully serializes the object ob. But I expected to get java.io.NotSerializableException at runtime. Because MyClass has reference of class which does not implement the Serializable interface! What is really going on?

A: Because the field is null. And null can be serialized fine.
The serialization mechanism checks the actual, concrete type of each field, and not its declared type. You could have an instance of a subclass of NotSerializable, that is Serializable, and it would then serialize fine as well. If that was not the case, you would not be able to serialize any object having a member of type List for example, because List doesn't implement Serializable.


text:
Q: read text from uploaded file - c# and javascript I have something like this:
<form action="" id="fileUpload">
    <input type="file" id="fileTest"/>
    <input type="button" id="saveFile"/>   </form>

For the user to upload a file.
I then have this js:
$('#saveFile').click(function () {
    PageMethods.ReadFile($('#fileTest').val());
});

And in my c# code i do this:
[WebMethod]
public static void ReadFile(string path)
{
    try
    {
        // Create an instance of StreamReader to read from a file.
        // The using statement also closes the StreamReader.
        using (StreamReader sr = new StreamReader(path))
        {
            String line;
            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
    catch (Exception e)
    {
        // Let the user know what went wrong.
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}

But the path that is sent to the webMethod is not the correct path of the file.
I am just trying to get the data from the file and then do with it somethings.
Is this the way to do it? If so, how can i get this to work?
Or is there a better way of doing this.
Thanks.

A: You're trying to access a client-side file ($('#fileTest')) on the server.  This isn't possible.
Instead, you'll need to POST the upload form to the web server and handle it on that end.

A: I am not sure why you are sending the local file path to webservice and then trying to read the file content. This is not possible. The webserver cannot view or access your local folders. You would need to upload the file and then you can use a webservice call the get back the data of successfully uploaded file.

A: <form action="MyPage/MyWebMethod.aspx" method="post" enctype="multipart/form-data" >
    <input type="file" id="fileTest"/>
    <input type="button" id="saveFile"/>
</form>

then on the server you can access the files from Request.Files. Or something like that. i don't remember the exact member off of Request. also ajax isn't straight forward with file uploads. there are many tricks with uploading files in an ajax manner, one of which is using iframes.