text:
Q: NSCollectionViewItem double-click action? How do I set an action for when a user double clicks an NSCollectionViewItem. NSTableView, for example, has the setDoubleAction method. Is there something similar for NSCollectionView?
Thanks

A: I know this question is ancient, but it comes up as the third result on Google right now, and I've found a different and very straightforward method that I haven't seen documented elsewhere. (I don't just need to manipulate the represented item, but have more complex work to do in my app.)
NSCollectionView inherits from NSView, so you can simply create a custom subclass and override mouseDown. This is not completely without pitfalls - you need to check the click count, and convert the point from the main window to your collection view's coordinate, before using NSCollectionView's indexPathForItem method:
override func mouseDown(with theEvent: NSEvent) {
    if theEvent.clickCount == 2 {
        let locationInWindow = theEvent.locationInWindow
        let locationInView = convert(locationInWindow, from: NSApplication.shared.mainWindow?.contentView)

        if let doubleClickedItem = indexPathForItem(at: locationInView){
        // handle double click - I've created a DoubleClickDelegate
        // (my collectionView's delegate, but you could use notifications as well)
...

This feels as if I've finally found the method Apple intended to be used - otherwise, there's no reason for indexPathForItem(at:) to exist.

A: You'd probably want to handle this in your NSCollectionViewItem, rather than the NSCollectionView itself (to work off your NSTableView analogy).


text:
Q: Question asking pipeline for Huggingface transformers Huggingface tranformers has a pipeline for question answering tuning on the Squad dataset.
What would I need to do to develop a pipeline for a question asking pipeline? This would use the context, question and answer to generate questions with answers from a context. Are there any examples for creating new hunggingface pipelines?

A: Pipelines can simply be treated as a wrapper around pre-trained models. In this case, you could perform fine-tuning/pre-training in the same way as existing example scripts such as run_squad. You can of course
An example on how to load custom checkpoint models is given on the HuggingFace website (slightly modified here):
from transformers import pipeline

# Question answering pipeline, specifying the checkpoint identifier
pipeline('question-answering', model='distilbert-base-cased-distilled-squad', tokenizer='bert-base-cased')

If your pipeline differs from existing options to a point where you indeed need to implement a new pipeline class, then I would suggest to look at the respective implementation. Specifically, most models do "nothing more" than to neatly wrap the tokenization step on pre-trained models, and calling the correct parameters on the model.forward function. This is probably as concise as an example as you will currently (version 2.8) find, since the feature is still relatively new.
I hope all the pointers helped to get you started!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Censura de Pagina para não logado Estou com um problema na hora de colocar um bloqueio de pagina...
Quando coloco o bloqueio no topo do site, que no caso estava usando isso:
    if(!empty($_SESSION['id'])){
    echo "Olá ".$_SESSION['nome'].", Bem vindo
";
    echo "Sair";
}else{
    $_SESSION['msg'] = "Área restrita";
    header("Location: login.php");
}

Ele me dá esse erro: headers already sent
Por conta dessa linha na minha pagina:
> if(mysqli_affected_rows($conn)){      $_SESSION['msg'] = "
 style='color:green;'>Item apagado com sucesso
";
>       header("Location: adm_tabela.php"); **//Essa Linha que dá o erro**

Como fazer o bloqueio dela para que nao de erro ?

A: O problema ocorre porque você está fazendo header: Location: ... duas vezes, já que o script não é interrompido quando deveria (ao final do else, uma vez que a intenção é redirecionar o usuário sem permissão para a página de login).
Nesta resposta tem mais detalhes, e neste trecho está a descrição do problema:

A página/output sempre segue os headers. O PHP é obrigado a passar os
  headers ao servidor primeiramente. Ele pode apenas fazer isto uma vez.
  E depois da quebra de linha dupla (envio de output para simplificar),
  ele não pode adicionar mais headers. (grifei)

Para corrigir basta fazer exit ou die no final do else, assim o redirecionamento ocorrerá e o script será interrompido:
if (!empty($_SESSION['id'])){
    echo "Olá ".$_SESSION['nome'].", Bem vindo
";
    echo "Sair";
}

else {
    $_SESSION['msg'] = "Área restrita";
    header("Location: login.php");
    exit();
}


text:
Q: Conversion between C string and std::string lead to garbled text in platform specific way I was dealing with a platform specific bug today in which on a Windows machine a certain string would be quite garbled, but not on a Mac.  The bug had to do with several lines that did both explicit and implicit conversions between std::string and const char *.  Basically, I had a function with the signature
void foo(const std::string &id);

where foo at some point prints the string.  On Windows, if called like below it would print the id string with various levels of corruption (garbling the first few characters or as much as the whole string)
std::string mystring = bar();
const char *id = mystring.c_str();
foo(id); // pass the C style string in because I thought that's what it took

I corrected the error by calling foo correctly:
std::string mystring = bar();
foo(mystring);

I can't figure out a few things though, like

*

*What was the source of the bug?

*Why was it platform specific?

*Is implicit conversion between const char * and std::string ever safe?

A: I'm going to take a wild guess and say that the code in your question isn't representative of your real code. The symptom sounds like memory being reused, which means the string isn't valid anymore at the time of the foo call. You could get that by using c_str on a temporary, for example const char *id = bar().c_str();.

A: There are two likely possibilities, and from just what you've said, we can't tell which:

*

*foo mishandles the case where it gets a reference to a temporary. For example, perhaps it stashes a pointer to its parameter somewhere and other code uses it after foo returns.

*The data in mystring contains embedded zero bytes and the length is lost when you call c_str.

A: I don't know what is going on, but is there any reason not to copy the result of c_str() into a buffer you own, call foo() on it, and destroy the buffer you created? If that doesn't fix it, it is a problem with foo() only rather than the implementation or some conflict between the implementation and foo().


text:
Q: BSImagePicker all Images blurred I'm using BSImagePicker instead of UIImagePicker to enable multi select.
I'm using following code for this:
    let bsImagePicker = BSImagePickerViewController()
    bsImagePicker.maxNumberOfSelections = 4

    self.bs_presentImagePickerController(bsImagePicker, animated: true, select: { (asset : PHAsset) in

    }, deselect: { (asset : PHAsset) in

    }, cancel: { (assets : [PHAsset]) in

    }, finish: { (assets : [PHAsset]) in

        for asset in assets {

            self.selectedAssets.append(asset)

            self.convertAssetsToImage()
        }

    }, completion: nil)

And for converting the PHAsset to an image I'm using this code:
func convertAssetsToImage() {

    for asset in selectedAssets {

        let manager = PHImageManager.default()
        let option = PHImageRequestOptions()
        var thumbnail = UIImage()
        option.isSynchronous = true

        manager.requestImage(for: asset, targetSize: CGSize(width: 340, height: 365), contentMode: .aspectFit, options: option, resultHandler: {(result, info) -> Void in

            thumbnail = result!
        })

        self.selectedPhotos.append(thumbnail)
    }

    DispatchQueue.main.async {

        self.imageViewImage.animationImages = self.selectedPhotos
        self.imageViewImage.animationDuration = 5.0
        self.imageViewImage.startAnimating()
    }
}

But all images are blurred. If the ImagePicker is shown, all images are slightly blurred and after selection the image is still blurred.
Thats an image of selection Screen:

Thats an Image of the selected Image:

And for example, this is an image if I'm using an UIImagePicker:

A: You can add these two PHImageRequestOptions to tell photos to provide a high-quality image (possibly sacrificing speed).
option.deliveryMode = .highQualityFormat
option.resizeMode = .exact

A: 100% worked for me :)
                   let option = PHImageRequestOptions()
                    option.deliveryMode = .highQualityFormat
                    option.resizeMode = .exact

                    PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: option) { (image, info) in
                        // Do something with image

                    }


text:
Q: Call subclass constructor from parent in Java so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.
What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.
public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}

public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}

Why would I want to do that?
I would like to be able to not have to deal with SmartPhone in the main.
I'd like to be able to do:
Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

A: Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

this makes no sense. If you want a SmartPhone instance, you must call
Phone iphone = new SmartPhone("iPhone", 368, "4G");

You cannot call a sub-class constructor from a super-class constructor.
If you want the type of the Phone to be determined by the passed parameters, you can use static factory methods:
public class PhoneFactory {

    public static Phone newPhone (String brand, int weight) {
        return new Phone(brand, weight);
    }

    public static Phone newPhone (String brand, int weight, String tech) {
        return new SmartPhone(brand, weight, tech);
    }
}

Phone nokia = PhoneFactory.newPhone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = PhoneFactory.newPhone("iPhone", 368, "4G"); // <- SmartPhone instance

A: Calling the constructor of a subclass within the constructor of the base class is not possible. There are various reasons for this but one is that a constructor of a derived class calls, implicitely or explicitly, a constructor of the base class. This would cause an infinite loop.
What you could do, is the following: Create a static method within the base class that decides what instance should be created.
public class Phone
{
  ...

  public static Phone createPhone(String brand, int weight, String tech)
  {
    if (tech == null)
      return (new Phone(brand, weight));
    else
      return (new SmartPhone(brand, weight, tech));
  }

  ...

}

A: You could use a private constructor, and instantiate a SmartPhone() object from within the Phone() constructor with three parameters.


text:
Q: Error while logging in (on the server) in the flutter application I have an application that has a piece of code that is responsible for authorization. I sent the encrypted data to the server, the data on the server will be checked, if everything is fine with the data, then I return the code 200 and additional data. I tested this code on the server without protection (http). But now when I started debugging this application with a server that has a certificate (https) I had a problem. Maybe someone knows how to solve this problem? Here is the problem code:

E/flutter (23247): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: HandshakeException: Handshake error in client (OS Error:
E/flutter (23247):   CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:354))

Here is my code:

  signIn(String login, pass) async {

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    var AESLogin = login;
    var AESpass = pass;
    //generate a 16-byte random key
    var key = '33CC2E0DD531B761316FE1231231211';

    print(key);
    //encrypt
    var encryptLogin = await FlutterAesEcbPkcs5.encryptString(AESLogin, key);
    var encryptPass = await FlutterAesEcbPkcs5.encryptString(AESpass, key);

    var jsonResponse = null;

    var response = await http.post(
      global.urlVar + "/auth_user", body: json.encode(
        {
          "login": encryptLogin,
          "pass": encryptPass
        }),
    );
    if (response.statusCode == 200) {
      jsonResponse = json.decode(response.body);
      print('Response body: ${response.body}');
      if (jsonResponse['message'] ==
          '200') { //if( jsonResponse['message'] == '200') {
        setState(() {
          _isLoading = false;
        });

        global.nameUser = jsonResponse['name'];
        global.dataArea = jsonResponse['data_area'];
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => MyApp()),
        );
      }
      else {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => Error_Auth()),
        );
      }
    }

    else   {
      setState(() {
        _isLoading = false;
      });
      print(response.body);
    }
  }


text:
Q: How to know a ScrollView content is scrollable or not react native? I have some dynamic content which I have placed inside a ScrollView.
As per the content's height it makes scroll. Some times because of the content height there is no scroll. I just want to know is there any way to detect programmatically  ScrollView container is scrollable or not depending on the content's height ?

A:
If for a given height to the scrollview, the content is not fitting to
  that height then automatically the scrollview is scrollable, otherwise
  its just a normal view. It Depends mostly on the device height, Let
  say for a small device the view is scrollable and for long devices,
  that view is not scrollable.
  It purely depends on the content, you are not able to figure out when it should be scrollable and when not.

Hope this helps...Thanks :)


text:
Q: C++ / G++ Maxmind geolite2++ third party shared object undefined reference I posted this question yesterday which was marked as a duplicate, after reading the original I was able to get my compile to go a bit further. (Will delete the linked question once I've got this resolved or given up).
Now I have two g++ commands compiling to a .o file but remain with the undefined reference errors regarding a third party .so that I obtained from this library (geolite2++).
Here are my compile commands:
sudo g++ -std=c++11 -I/home/ubuntu -L/home/ubuntu -g -lstdc++ -lgeolite2++ -c -O2 -MMD -MP -MF "main.o.d" -o main.o main.cpp

(appears to work)
sudo g++ -std=c++11 -L/home/ubuntu -I/home/ubuntu -pthread -g -o main main.o -lstdc++ -lgeolite2++ -lz -ldl

(generates the following errors)
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_lookup_string'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_free_entry_data_list'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_open'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_strerror'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_lib_version'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_aget_value'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_get_entry_data_list'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_get_metadata_as_entry_data_list'
/home/ubuntu/libgeolite2++.so: undefined reference to `MMDB_close'
collect2: error: ld returned 1 exit status

I've done more research and read here (answer by Dmitry Yudakov) that I can use the ldd command to see if the /home/ubuntu/libgeolite2++.so shared object has found it's dependencies. My output indicates this isn't the case:
ldd /home/ubuntu/libgeolite2++.so
        linux-vdso.so.1 =>  (0x00007ffe7fae1000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fb281442000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fb28122c000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb280e64000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fb280b5e000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fb2819d6000)

Here is my programs code:
#include <cstdlib>
#include <iostream>

#include <GeoLite2PP.hpp>
#include <GeoLite2PP_error_category.hpp>
#include <GeoLite2PP_version.hpp>

using namespace std;
using namespace GeoLite2PP;

int main(int argc,char* argv[]) {

    GeoLite2PP::DB db( "./GeoIP2-City.mmdb" );
    std::string json = db.lookup( "216.58.216.163" );
    std::cout << json << std::endl;
}

As such my question is, is this a problem with the /home/ubuntu/libgeolite2++.soshared library that's my fault or is it a problem with the library? Is the answer to be found in the duplicate of my original question (link above) or is it something else? Apologies in advance if this question is very newbie, but I am a bit out of my depth. Thanks in advance for any help.
Regards,
James

A: Googling those undefined symbols, it seems libgeolite2++ has an undeclared (and undocumented) dependency on libmaxminddb.
Since it's undeclared, ldd is of no help; however, even it were declared, you'd still need to link that other dependency into your executable.
You can dive into installing and linking that dependency, and/or you can talk to the author of libgeolite2++.


text:
Q: sum and multiply of doubles and ints does not work I wrote this code in C:
 double x1 = 7.52, x2 = 7, x3 = 8;
 int m = 0;
 double sum = x1 + x2*m + x3*m*m;

 printf("%lf", m, sum);

but sum is always 0 no matter what the value of m that i changed..
why doesnt it make normal calculation ?
thanks

A: Because your are printing m which is int with the "%lf" specifier which is for double.
And you are also passing more arguments to printf() than format specifiers, which means that you are not enabling compiler warnings, you should, specially if you are a beginner.
Change this
printf("%lf", m, sum);

to
printf("m   = %d\nsum = %f\n", m, sum);

and see what I mean.

A: Actually you are printing the value of m  -
 printf("%lf", m, sum);

You have to print -
 printf("%lf",sum);


text:
Q: Help to show the next proposition Let $f:[a,b] \rightarrow R$ be a bounded function in $[a,b]$ such that $f$ is equal to zero except for a finite number of points in $[a,b]$. Show that $f$ is integrable and that its integral is zero.
I attempted the solution by induction over the number of points in which $f \neq 0$. Starting with only one point, and getting that it works for n number of points.
Proof: By induction.
Base case: Suppose that $f(x) = 0\; \forall x \neq c$ with c being a point in $[a,b]$.
But I don't know how to continue with the proof.

A: Let $a < x_1 < x_2 < \dots < x_n < b$ be the $n$ distinct points where $f \ne 0$. (Although $a = x_1$ and $x_n = b$ are possible, just take $\hat{a} < a$ and $\hat{b} > b$ and consider the same problem on $[\hat{a}, \hat{b}]$.) Without loss of generality, assume $f \geq 0$. Let $C = \sum_{i=1}^{n} f(x_i)$.
We need to show that $L(f) = U(f)$, where $L(f) = \sup_P L(f,P)$ and $U(f) = \inf_P U(f,P)$.
First, let's show that $L(f) = 0$. To this end, let $P = \{a = y_0 < y_1 < \dots < y_m = b \}$ be any partition of $[a,b]$. Then $\inf\{f(x) : y_i \leq x \leq y_{i+1}\} = 0$ for each $i$, so $L(f,P) = 0$; hence, $L(f) =0$.
Conversely, let $\varepsilon > 0$ be sufficiently small. Consider the partition
$$
P_\varepsilon = \{ x_i \pm \varepsilon : i = 1, \dots, n \}.
$$
Then
\begin{align}
  U(f, P_\varepsilon) &= \sum_{i=1}^{n} \sup\{f(x) : |x-x_i| \leq \varepsilon \} \cdot 2\varepsilon \\
  &= \sum_{i=1}^{n} 2\varepsilon f(x_i) \\
  &= 2 C \varepsilon,
\end{align}
so $U(f) = \inf_P U(f,P) = \lim_{\varepsilon \to 0} U(f,P_\varepsilon) = 0$.
Since $U(f) = L(f)$, it follows that $f$ is Riemann integrable. Moreover, $\int_a^b f = 0$.


text:
Q: Programmatically created button doesn't follow theme's button style The buttons created programmatically don't follow the buttonStyle defined in the apptheme, but the buttons created in xml follow it.
Below is my style.xml
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="buttonStyle">@style/Button.Primary</item>
    </style>

    <style name="Button.Primary" parent="Widget.AppCompat.Button.Colored">
        <item name="textAllCaps">true</item>
        <item name="android:textColor">#fff</item>
        <item name="backgroundTint">@color/btn_bck</item>
    </style>

And this is how I create a button programmatically:
Button progBtn = new Button(this);
progBtn.setText("Programmatic button");
LinearLayout layout = findViewById(R.id.container);
layout.addView(progBtn);

And it shows up as the default gray colored background with black text color.
But if I use the button in xml like:
<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

It works fine and shows up with white text color and the correct backgroundTint specified in style.
I'd like to know why is there an inconsistency in the button style between the above 2 methods of button creation?

A: They are different because you are using a Theme.AppCompat.* theme.
With this theme the Button defined in the layout is replaced at runtime by a AppCompatButton.
You can use:
Button progBtn = new AppCompatButton(this);
progBtn.setText("Programmatic button");
LinearLayout layout = findViewById(R.id.container);
layout.addView(progBtn)

A: This should do the trick
int buttonStyle = R.style.Button.Primary;
Button button = new Button(this, null, buttonStyle);

or
int buttonStyle = Button.Primary;
Button button = new Button(new ContextThemeWrapper(this, buttonStyle), null, buttonStyle);


text:
Q: The App Engine app associated with this project has been deleted The message displays on dashboard:
The App Engine app associated with this project has been deleted.
App Engine services malfunction in project number 502019044490

A: It seems you shutdown your project. You can still restore the project within 30 days after the project has shutdown. Here is the link for more details about restoration.


text:
Q: How can I change the language in the ProfileManager? My standard language for Firefox and Thunderbird is Dutch.
When I use the terminal to open firefox or thunderbird with the -ProfileManager option, the resulting ProfileManager is in English.
How can I change the language to Dutch in the ProfileManager?

A: You can download a fully localized version of Firefox here:
  http://www.mozilla.org/en-US/firefox/all.html
and then extract that in e.g. /home/{yourusername}/programs/firefox/
Then, create a directory /home/{yourusername}/bin/ and create a symbolic link "firefox" in that directory, pointing to /home/{yourusername}/programs/firefox/firefox.
Starting from the next time you log in, all invocations of "firefox" (including through the system menus) should invoke your own localized version of Firefox instead of the Ubuntu-maintained version.
(This is what I do, because I'm using a nightly build of Firefox instead of the Ubuntu-maintained version.)


text:
Q: Error getting data from YouTube API v2 $yt_id = "RWtxqtBTkpY";
$yt_data = file_get_contents('http://gdata.youtube.com/feeds/api/videos/' . $yt_id . '?v=2&alt=jsonc');

$decoded_josn = json_decode($yt_data);
//var_dump($decoded_josn->data);

foreach($decoded_josn->data as $key => $value)
    print $key . ': ' . $value . '<br>';

This is what I'm getting but there is more data as shown by var_dump();
id: RWtxqtBTkpY
uploaded: 2012-05-29T18:57:42.000Z
updated: 2014-06-30T12:50:11.000Z
uploader: babastarschannel
category: Entertainment
title: BABASTARS - HIGH (Official Video 2012)
description: Rrethi jon i gjon

Catchable fatal error: Object of class stdClass could not be converted to string in C:\Apache24\htdocs\yt_title.php on line 23

var_dump($decoded_josn->data);

object(stdClass)#2 (18) { ["id"]=> string(11) "RWtxqtBTkpY" ["uploaded"]=> string(24) "2012-05-29T18:57:42.000Z" ["updated"]=> string(24) "2014-06-30T12:50:11.000Z" ["uploader"]=> string(16) "babastarschannel" ["category"]=> string(13) "Entertainment" ["title"]=> string(38) "BABASTARS - HIGH (Official Video 2012)" ["description"]=> string(17) "Rrethi jon i gjon" ["thumbnail"]=> object(stdClass)#3 (2) { ["sqDefault"]=> string(46) "http://i1.ytimg.com/vi/RWtxqtBTkpY/default.jpg" ["hqDefault"]=> string(48) "http://i1.ytimg.com/vi/RWtxqtBTkpY/hqdefault.jpg" } ["player"]=> object(stdClass)#4 (2) { ["default"]=> string(71) "http://www.youtube.com/watch?v=RWtxqtBTkpY&feature=youtube_gdata_player" ["mobile"]=> string(42) "http://m.youtube.com/details?v=RWtxqtBTkpY" } ["content"]=> object(stdClass)#5 (3) { ["5"]=> string(73) "http://www.youtube.com/v/RWtxqtBTkpY?version=3&f=videos&app=youtube_gdata" ["1"]=> string(102) "rtsp://r6---sn-4g57kue6.c.youtube.com/CiILENy73wIaGQmWklPQqnFrRRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp" ["6"]=> string(102) "rtsp://r6---sn-4g57kue6.c.youtube.com/CiILENy73wIaGQmWklPQqnFrRRMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp" } ["duration"]=> int(221) ["rating"]=> float(4.2605257) ["likeCount"]=> string(4) "5150" ["ratingCount"]=> int(6318) ["viewCount"]=> int(1730090) ["favoriteCount"]=> int(0) ["commentCount"]=> int(1571) ["accessControl"]=> object(stdClass)#6 (8) { ["comment"]=> string(7) "allowed" ["commentVote"]=> string(7) "allowed" ["videoRespond"]=> string(9) "moderated" ["rate"]=> string(7) "allowed" ["embed"]=> string(7) "allowed" ["list"]=> string(7) "allowed" ["autoPlay"]=> string(7) "allowed" ["syndicate"]=> string(7) "allowed" } }

A: Your JSON has nested objects, e.g. (in pseudo-code)
$obj = object (
   'obj2' => object (
        'obj3' => object ( ... )
   )
)

When you loop on the top level $obj, you end up doing the equivalent of
echo $obj['obj2']

and try to directly echo out an object. Since they're stdClass, they have no magic __toString() method, and cannot be converted to strings, which causes your error.


text:
Q: Where to store Application Data in Windows 7 and Vista My application needs to, like most, store data.  The application was previously used on XP only where it would store the data in Program Files.  Now that our customers are moving to Windows 7 I had to upgrade it so that it stored the data in a new folder.  I opted for the ApplicationData folder as I thought I would be allowed access without needing UAC at all.
Now on some Windows 7 machines this is fine, but on others access to the folder fails, presumably because of permissions, but when ran with Administrator privelidges the program works fine.
Am I using the wrong folder or are these cases outliers? In either case what is the best practice for this kind of thing?
I am using the following C# SpecialFolder to get the AppData folder location.
System.Environment.SpecialFolder.ApplicationData

A: David is right.
As far I know, there's also some difference if you deploy your app via ClickOnce or Installer: the first allows a few subset of permissions than the normal installer.
I must confess I'm not an expert on that.
Of sure, Program Files is the worst place to store data, even since XP.

A: System.Environment.SpecialFolder.ApplicationData is per-user and roams. That doesn't sound like what you want. You appear to want machine wide settings and so should use System.Environment.SpecialFolder.CommonApplicationData.
Because CommonApplicationData is shared between all users, the default access control is limited. By default standard users cannot write in this location. The recommended practise is to create a sub-folder of CommonApplicationData at installation time and assign it suitably permissive access control settings.


text:
Q: How can I store data inside python? I'm making a game in which the player works for a certain amount of money. But I'm running the code on a discord server which means that there will be multiple users? If I can get a unique ID for each user then how can I store information for each user?
This is some code I made that basically reflects my other one. How can I store money as well as returning money if they enter a username that's been used before.
def start():
        name = input("What is your name?")
        main()
def main():
        print('1. New Player')
        print('2. Work')
        answer = input()
        if answer == '1':
            start()
        if answer == '2':
            work()
    def work():
        print("You work for $100")
        money += 100
        main()
    main()

(Sorry if my question is too broad... ask any questions if want more details.)

A: A simple suggestion would be to create a class that describes a player, their attributes and any functions associated with the player.  For example:
class Player:
    def __init__(self, id):
        self.money = 0
        self.items = []
        self.level = 1
        # Initialize other player attributes here

    def add_money(self, amount_added):
        self.money += amount_added

def main():
    player_1 = Player(id=1)
    player_1.add_money(100)
    player_2 = Player(id=2)

This is a very generic example, but defining a class for a player will allow you to easily create an object for which you can associate each player.  If you add 100 to player 1's money then that will be completely independent of player 2's money.  I suggest searching up tutorials/examples on classes and you'll get a feel!


text:
Q: Java file upload using Oreilly Multipartrequest
I'm doing a java web application that manage online auctions. At a certain point in the application the user can sell a product, so I have built a page where there is a form; in this form I have to handle the file upload using Oreilly Multipartrequest library. When I click the submit button a servlet should handle all the parameters, add the product on the database, and then redirect to the users page, but instead of doing it, the application hangs in a blank page. I'm using netbeans so I have checked the logs, but I can't find any errors; I have also checked on the logs inside the tomcat folder, but again I can't any errors. I don't know what to do neither where to search the solution.
Here is the part of the code that handle the upload:
try {

        MultipartRequest multi =
            new MultipartRequest(request, getServletContext().getRealPath("/img"), 10*1024*1024,
            "ISO-8859-1", new DefaultFileRenamePolicy());

        Enumeration files = multi.getFileNames();
        while (files.hasMoreElements()) {
            name = (String)files.nextElement();
            filename = multi.getFilesystemName(name);
            // String originalFilename = multi.getOriginalFileName(name);
            // String type = multi.getContentType(name);
            File f = multi.getFile(name);

            if (f != null) {
                session.setAttribute("success", "file written correctly");
            }
        }
    } catch (IOException IEx) {
        this.getServletContext().log("Error reading saving file");
    }

Am I doing something wrong, or my idea is correct?
 P.S.  If the user decide not to upload any picture, I have to put on the database a default picture.


text:
Q: My macro is not assignable I'm trying to define a macro that returns an absolute value of numbers. Here how it looks like:
#define ABSOLUTE_VALUE(v) ( (v) < 0 ? (v) *= -1 : (v))

It works fine when I insert just a single number. The problem is, when I try to insert an expression (number + anotherNumber, for example), the compiler throws an error, saying that the expression is not assignable. I can't figure out why it does that. If you know the reason of the error, I would appreciate your help.

A: What's going on here is that the entire expression number + anotherNumber is getting passed to your macro, so anywhere there is v, it's not the result v = number + anotherNumber, rather, v is replaced by number + anotherNumber before evaluation. So:
 (v) *= -1

Becomes
(number + anotherNumber) *= -1

Since number + anotherNumber is yet another number, that part of the code is trying to assign the value of -1 * (number + anotherNumber) to number + anotherNumber , which results in the error you are seeing, because you can't assign something to an expression.

A: From one of your comments:

The problem is that I'm trying to assign the result of (number + anotherNumber) * (-1) to an expression, which is number + anotherNumber. But shouldn't the + fire first, before the *= operator?

You are misunderstanding assignment. The left hand side (LHS) of an assignment must be an lvalue, which means something like a variable, which references a storage location into which values can be stored.
A value is just that, it is not associated with any storage location, you cannot assign to it. The result of your expression number + anotherNumber is a number, it cannot go on the LHS of an assignment.
Your macro would work if you simply replace =* with *.
HTH


text:
Q: QMAKE. How to figure out host platform and target platform when cross compiling QT projects I compiling for QNX, ARM, My Host platform can be Win32/64 ,  Linux  or Mac
I want to find a way to see wheat is my host platform in my PRO file (on computer I building my project)
Apparently using:
win32 {}
unix {}
macx {}

does not work because on different OSes it will always report unix, so I assume this is target platform
So what is the way to obtain current host platform to make PRO file flexible because on different platform I would like to do different things.
Thank you

A: Maybe QMAKE_HOST variable is the answer to your question?
Here's information from official Qt documentation:
QMAKE_HOST
Provides information about the host machine running qmake. For example, you can retrieve the host machine architecture from QMAKE_HOST.arch.

*

*.arch - Host architecture

*.os - Host OS

*.cpu_count - Number of available cpus

*.name - Host computer name

*.version - Host OS version number

*.version_string - Host OS version string

win32-g++:contains(QMAKE_HOST.arch, x86_64):{
    message("Host is 64bit")
    ...
}

A: Could not get anything better then:
QMAKE_SPEC_T = $$[QMAKE_SPEC]

contains(QMAKE_SPEC_T,.*win32.*){
    HOST_PLATFORM=WIN
    IS_WIN = 1
}

contains(QMAKE_SPEC_T,.*macx.*){
    HOST_PLATFORM=MAC
    IS_MAC = 1
}

contains(QMAKE_SPEC_T,.*linux.*){
    HOST_PLATFORM=LINUX
    IS_LINUX = 1
}

and then anywhere to check:
!isEmpty(IS_WIN):message($${HOST_PLATFORM})
!isEmpty(IS_MAC):message($${HOST_PLATFORM})
!isEmpty(IS_LINUX):message($${HOST_PLATFORM})


text:
Q: Jenkins job api json and Rundeck remote url I tried to bind the remote url of Rundeck job with the job api of jenkins as options provider.
So i use the api that give jenkins to call my job with this url http://localhost:8080/job/my_job/api/json?tree=jobs[name] who give this
{"_class":"org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject","jobs":[{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","name":"lenormandSeb-patch-2"},{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","name":"master"},{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","name":"update%2Fcodesniffer"}]}

But when i use this url on rundeck as remote url, only "_class" and "jobs" are showing on select.
Did i miss something on the Rundeck job configuration ?
enter image description here
thank

A: That's because Rundeck only admits this kind of format as a remote option. To "understand" other "formats" the quickest way is to develop a custom option plugin that gives options using jq similar to this one, you can take a look at this.


text:
Q: Is there a way to check if a variable is an instance of an inner class whose outer class is a certain class? example code:
class A:
    class B:
        def __init__(self):
            pass

var = A.B()

i need a function, let's say check_if_class_parent(obj, class_type) that would check if var is an instance of an inner class whose outer class is A, which if i run check_if_class_parent(var, A), it would return True
sometimes the class structure could be like this:
class A:
    class B:
        def __init__(self):
            pass

        class C:
            def __init__(self):
                pass

var = A.B.C()
var_two = A.B()

check_if_class_parent(var, A), check_if_class_parent(var, B), and check_if_class_parent(var_two, A) would all return True, but check_if_class_parent(var, C) would return False

A: *

*An outer attribute could be added to the inner classes, in which case it's just a matter of walking up any outer attributes found on a value's type to see if A can be reached. However this does add extra definitions.

*A search can be conducted starting from A. E.g. (and not accounting for any dastardly cyclic references at all):
def is_type_within(obj, type_):
    if isinstance(obj, type_):
        return True
    for attr in dir(type_):
        if attr.startswith('__'):
            continue
        if is_type_within(obj, getattr(type_, attr)):
            return True
    return False


text:
Q: When are the Dolbeault and de Rham dgas homotopy equivalent? Let $M$ be a compact Kahler manifold.  Then the Hodge decomposition says that the Dolbeault dga (of forms of all bidegree) and the de Rham dga on $\Omega_{\mathbb C}^\bullet(M)$ have isomorphic cohomology groups.
Are there any stronger relationships between these two dgas? For example, are there simple conditions on $M$ that imply that these dgas are homotopy equivalent?

A: A relevant reference might be J. Neisendorfer, L. Taylor: Dolbeault homotopy theory. Trans AMS 245 (1978), 183-210.
One of the results (Theorem 8) states that compact connected Kähler manifolds are both Dolbeault formal and de Rham formal (strengthening the result of Deligne-Griffiths-Morgan-Sullivan). This implies that the isomorphism of cohomology groups can be promoted to a zig-zag of homotopy equivalences of dgas.


text:
Q: Paying from any account to any other via PayPal API I'm trying to figure out whether it is possible to send money directly from any paypal account to any other via PayPal API.
I tried to find the answer in the API documents as hard as I could, but unfortunately haven't found it :-(

A: Two choices: Mass Pay and Adaptive Payments API.
Mass payments is the simplest of the two, and also the old, legacy one (note also it is limited to 250 payments at once).
https://www.x.com/developers/paypal/products/mass-pay
The Adaptive Payments API is the next-generation API, allowing for more complex scenarios and implementations.
https://www.x.com/developers/paypal/products/adaptive-payments
Hope this helps.


text:
Q: View Controller Cannot Find Segue With Identifier I have 3 view controllers in a part of my storyboard. I also have 2 push segues, one switches the first view controller to the second one, and the other one switches the second view controller to the third one.
I perform both segues programmatically, and I have set all three view controllers to use the same custom class ( Called RegViewController ).
Everything works fine with the first segue, but the second one throws an exception saying
Crash: Receiver (<RegViewController: 0xab74b50>) has no segue with identifier 'a'

I set the identifier for second segue to "a" to make sure it is short and I'm not making any mistake.
Anyways, I'm sure that my view controller has a push segue with that identifier and I dunno if I'm making any mistake logically !
Any ideas ?

A: Found the problem :
Assigning 3 view controllers to same custom class, results in errors when you're trying to perform a segue, because the segue with desired identifier is not created from every view controller using that custom class. Using different custom classes would solve the problem.

A: check your segue identifier. because your segue identifier doesn't same in your code or you are declared identifier name different on your storyboard


text:
Q: Matriz no se muestra (Tokenizacion de string por delimitaciones (",")) C++ tengo una pregunta bastante importante para mí y es llevar un texto tipo string a un chart o una matriz utilizando delimitadores y sin depender de archivos de texto externos al programa. El codigo que hice para llevar el string a la matriz separando el texto por el delimitador (",") es este:
std::string mvalores [50] [12];
//convetir string en tabla pasando las letras a char y luego designarlas a una casilla de la matriz concatenando la variable actual con el nuevo char hasta llegar al delimitador

std::string from4 = ",";
std::string::size_type pos4 = 0;
std::string concatenacion;
int da = 0;

for (int fils = 0; fils <= 50; fils++){

    for (int cols = 0; cols <= 12; cols++){
    pos4 = DATA.find(from4, pos4) < std::string::npos;

        for (int da; da < pos4, da++;){
        concatenacion = concatenacion + DATA[da];//designar concatenacion a matriz.
        }

    mvalores [fils][cols] = concatenacion;
    std::replace(mvalores [fils][cols].begin(), mvalores [fils][cols].end(), ',', '\0');
    concatenacion = "";
    std::cout << mvalores [fils][cols] << std::endl;

    }
}

Los valores no se muestran en las casillas de la matriz... como si de nada se tratase, se muestra vacío todo.
Lo que hace el código es convertir los números y letras de mi string en un solo texto, concatenándose hasta llegar a la "," que es mi delimitador, luego lo concatenado se va pegando a mi matriz columna por columna hasta llegar a la columna 12, de ahi se salta a una nueva fila y sigue el mismo proceso.

A: Aquí
pos4 = DATA.find(from4, pos4) < std::string::npos;

Fíjate que no estás guardando una posición sino, simplemente, un 1 o un 0.
Ese operador menor que realiza una operación booleana, por lo que el resultado final será 1, si se ha encontrado la cadena, o 0 en caso contrario.
Esta línea realmente deberías dividirla en dos
pos4 = DATA.find(from4, pos4);

if (pos4 < std::string::npos)
{ \* ...  */ }


text:
Q: Como fazer upload por FTP ao invés de HTTP Eu preciso mandar arquivos acima de 2GB, e acabei lendo que é melhor usar FTP, pesquisei um pouco e consegui esse código:
uploadFTP.php
<?php
    set_time_limit(0);
    $server_ftp = 'xx.xx.xxx.xxx';

    $usuario_ftp = SQL_USUARIO;
    $senha_ftp   = SQL_SENHA;

    $limitar_tamanho = 0;

    $arquivo = $_FILES['arquivo'];
    $nome_arquivo = $arquivo['name'];
    $tamanho_arquivo = $arquivo['size'];
    $arquivo_temp = $arquivo['tmp_name'];

    $destino = DIR_ARQUIVOS.$nome_arquivo;

    $conn_ftp = ftp_connect($server_ftp);
    $login_ftp = @ftp_login($conn_ftp, $usuario_ftp, $senha_ftp);

    if (!$login_ftp){exit('Usuário ou senha FTP incorretos.');}

    if (@ftp_put($conn_ftp, $destino, $arquivo_temp, FTP_BINARY))
    {
        echo 'Arquivo enviado com sucesso!';
    } else {echo 'Erro ao enviar arquivo!'; }

    // Fecha a conexão FTP
    ftp_close( $conn_ftp );

O problema é que no meu caso, eu tenho um form(POST) com um <input type="file"> que eu uso if(isset($_POST['fileInputName'])) desta forma para mover(move_uploaded_file) o arquivo que foi feito upload, porém eu gostaria de uma forma de fazer esse upload (de vários arquivos no mesmo input) pelo código FTP acima, e ainda sim poder usar o isset.

A: Cara, coloca um atributo name nos inputs que siga um padrão. Por exemplo:
<input type="file" name="arquivo_1" />
<input type="file" name="arquivo_2" />
<input type="file" name="arquivo_3" />

Depois, faz um loop pra ver se você acha esses caras no seu POST:
$ix = 1;
while( isset($_POST["arquivo_$ix"]) )
{
  ...
  $ix++;
}


text:
Q: Routing with several stops using QGIS I have point layer and a network (segments) stored in a GeoPackage and using QGIS. The number of points and their ids are always different.

What I need is to get a route from first to last points but through several stops in a specific order.
I am thinking in a script or algorithm where to select an order column and then do the shortest path between first and last points setting the rest of it as stops ordered and get a single layer with the entire path.
I've tried the Analysis tools of QGIS and plugins but I can't find a tool with this functionality.
I have also tried the v.net.salesman that computes a route through all the points but it isn't what I need, It can't assign an order to the stops and  the route should not be cycle.
Is there any way, using QGIS or PyQGIS, to do that?

A: The solution requires some basic usage of PyQGIS. This code computes paths for every subsequent pair of points using the order specified in the "order" field. Then all the paths are merged into a single layer.
Add an order column, change your input variables and run this as a script in QGIS 3.
###input###
networkLayerName = 'prg_ulice'
pointLayerName = 'pkt_adresowe'
orderColumnName = 'order'
output = '/home/lpowalka/Documents/dane/geopackage/path.gpkg'
###input###

networkLayer = QgsProject.instance().mapLayersByName(networkLayerName)[0]
pointLayer = QgsProject.instance().mapLayersByName(pointLayerName)[0]

expr = '"{column}" is not null'.format(column=orderColumnName)
pointLayer.selectByExpression(expr)

stops = []
for feat in pointLayer.selectedFeatures():
    stops.append((feat['order'], feat.geometry().asPoint()))

#sort by order column
stops.sort(key=lambda x: x[0])
paths = []
for i, (order, point) in enumerate(stops[0:-1]):
    endPoint = stops[i + 1][1]
    print('Order: ', order)
    print('From {} to {} \n'.format(point, endPoint))
    parameters = {'INPUT': networkLayer,
                'STRATEGY': 0,
                'DIRECTION_FIELD': '',
                'VALUE_FORWARD': '',
                'VALUE_BACKWARD': '',
                'VALUE_BOTH': '',
                'DEFAULT_DIRECTION': 2,
                'SPEED_FIELD': '',
                'DEFAULT_SPEED': 50.0,
                'TOLERANCE': 20.0,
                'START_POINT': point,
                'END_POINT': endPoint,
                'OUTPUT': 'memory:'}

    path = processing.run('qgis:shortestpathpointtopoint', parameters)['OUTPUT']
    paths.append(path)

params = {'LAYERS': paths, 'OUTPUT': output}
pathsMerged = processing.run('qgis:mergevectorlayers', params)['OUTPUT']
vlayer = QgsVectorLayer(pathsMerged, 'result', 'ogr')
QgsProject.instance().addMapLayer(vlayer)


text:
Q: Why the amplitude of monopole solution in Helmholtz equation is complex? 1. Background
Given an surface of vibrating object $\partial \Omega$, I am trying to simulate the outer acoustic field. I use the equivalent source method[1], which basically tries to approximate the solution (sound pressure) field by a linear combination of basis functions.
Helmholtz
We know the propagation of a wave is governed by the Helmholtz equation (homogenous):
$$
(\nabla^2 + k^2) p  = 0
$$
where $ p = p(x) \in \mathbb C$ is a complex sound pressure field.
This equation has a family of solutions. One of them is the Monopole solution:
$$
p(\mathbf x; \mathbf c) = A \frac{e^{- i k r}}{4 \pi r }
$$
where $\mathbf c \in \mathbb R^3 $ is the center of monopole, $r = |\mathbf x - \mathbf c|$, $A $ is a strange complex amplitutde.
After searching for many books and papers, I still cannot figure out the following questions:
2. question
I cannot figure out why $A$ is a complex number (this paper [1] claims the "amplitude" is complex), would anyone please tell me the reason?

*

*I understand $p(x)$ should be complex, because the phase shift $e^{i\phi}$ is involved in $p(x)$. But this phase shift has been considered by Monopole in its $e^{- i kr}$ item now.

*Why A is still complex?
reference
[1] Kondapalli, P.S., Shippy, D.J. and Fairweather, G., 1992. Analysis of acoustic scattering in fluids and solids by the method of fundamental solutions. The Journal of the Acoustical Society of America, 91(4), pp.1844-1854.

A: If there is a single monopole it does not matter whether $A$ is real or not but if you have two or more sources then their relative phases, and thus the phase of $A$, do matter. The same holds if the source is distributed and not point-like.
Acoustic phase is important if you care about spatial distribution of the wave field, ie., radiation pattern, but to a first (?) order human hearing is not sensitive to phase. In other words humans cannot hear the difference between $x_1(t)=K_0cos(\omega_0 t+\phi_1)$ and $x_2(t)=K_0cos(\omega_0 t+\phi_2$. Apparently, humans can "hear" $\omega_0 $ (frequency) and $|K_0|$ (amplitude) but not $\phi$ (phase). In other words, the human ear is a frequency sensitive non-coherent intensity  detector, just like a spectrum analyzer. This is true whether the oscillation be damped or undamped.
A phase sensitive detector is really two frequency coherent detectors in "quadrature", that is phase is measured relative to two reference signals one is, say, $r_c(t)=Rcos(\omega_0 t+\psi)$ the other is $r_s(t)=Rcos(\omega_0 t+\psi - \pi/2) = Rsin(\omega_0 t+\psi)$ where $\psi$ and $R$ are the arbitrary phase and amplitude of the local reference, resp. While measuring the time evolution of $x(t)=K_0 cos(\omega_0 t+\phi)$ relative to the oscillations of $r_c(t)$ and $r_s(t)$ we can calculate $\phi - \psi$ and then all the other relative phases between the other sources, as well, at the same frequency. Human and I think most if not all animal hearing is very sensitive to time delay between two sources, this is how we discern the direction from which the sound is emitted. It is amazing how sensitive the directional hearing of grasshoppers or crickets is despite the fact that spatial separation between the "ears" of a grasshopper is at most a few millimeters. One wonders if the cricket's hearing may be phase sensitive then, but I am just guessing here and do not really know.


text:
Q: if $|f(x)-f(y)|\le |x-y|^{\sqrt 2}$ then is $f$ a constant function? if $f: \mathbb{R}\to \mathbb{R}$ satisfies
$$|f(x)-f(y)|\le |x-y|^{\sqrt{2}}$$ for all $x,y\in \mathbb{R}$ ,then is f increasing ,decreasing or constant?
in my view ,it is clear that $|f(x)-f(y)|$ is not zero so it is not constant.
And since the rate of change is positive so the function would be increasing.Is my solution correct or wrong?

A: Consider the more general case: $|f(x)-f(y)|\le |x-y|^{1+\varepsilon}$, with $\varepsilon>0$.
Then $f$ is differentiable with $f'=0$ because
$$
\lim_{x\to x_0} \left|\frac{f(x)-f(x_0)}{x-x_0}\right|
\le
\lim_{x\to x_0}|x-x_0|^{\varepsilon}
= 0
$$
So, $\sqrt2$ is a red herring. Its only relevant property is $\sqrt2>1$.


text:
Q: Need to run a command if the jenkins build stuck In the Jenkins "Abort the build if it's stuck" feature, if a time out happens I want to run a powershell command, instead of aborting or failing the build. Is it possible to accomplish this?

A: under system configuration-> configure system, found below option:

once enabled this option, "perform build step option" will be available under "time-out action" where we can execute any script or cmd.

A: Perhaps you could set a "Time-out variable" in the "Abort the build..." menu. Then run a post-build script using the PostBuildScript plugin that checks that env var and takes action accordingly. Haven't tried it.


text:
Q: Why does fitBounds method work incorrect in google maps? I have following code:
function fitBounds() {
        var bounds = calculateBounds();
        if (bounds != undefined) {
            map.fitBounds(bounds);
        }
    }

In debug I see following information:

After this row execution I invoke following method in console:
map.getBounds

and see following result:

For me it is very strange. Expected result: value equal passed bounds argument.
Can I achieve that this method return value like bounds ?
UPDATE
function calculateBounds() {
        if (terminalMarkers.length > 0) {
            var bounds = new google.maps.LatLngBounds();
            for (i = 0; i < terminalMarkers.length; i++) {
                bounds.extend(terminalMarkers[i].getPosition());
            }
        }
        return bounds;
    }

P.S.
In my bussiness logic I suppose that longitude of second point should be more first.


text:
Q: What should I expect from calling `Cancel` on `PrintEventArgs` from `PrintDocument`? I had to modify the print feature in our application in order to not print some specific pages. The only way I found that didn't requires heavy modifications was to recycle the page (I only know if the page need to be skipped after I "printed" it so I clear this page I use it again for the next). The problem is when the page I need to recycle is the last one I end up with a blank page for which I have no use. The clever trick I do at that point is to call Cancel on PrintEventArgs which effectively seems to cancel only the last page. Is that guaranteed to always be the case or I run the risk of cancelling more than the last page under some specific circumstances (ex: slow spooler)? I don't have any other fix in mind.

A: Yes, this should be a problem.  Setting e.Cancel to true in the PrintPage event causes AbortDoc() to be called.  From the SDK docs:
If Print Manager was used to start the print job, calling AbortDoc erases the entire spool job, so that the printer receives nothing. If Print Manager was not used to start the print job, the data may already have been sent to the printer. In this case, the printer driver resets the printer (when possible) and ends the print job.
Not actually sure what the "Print Manager" is.  Ask at superuser.com


text:
Q: Measure on non-measurable subset If $(Y, \Sigma_Y)$ is a measurable space and $X \subseteq Y$, then we can turn $X$ into a measurable space by setting
$$
\Sigma_X = \{ E \cap X \mid E \in \Sigma_Y \}.
$$
When $X \in \Sigma_Y$, we have $\Sigma_X \subseteq \Sigma_Y$ and therefore any measure on $(Y, \Sigma_Y)$ restricts to one on $(X, \Sigma_X)$.
When $X \notin \Sigma_Y$, is there a sensible way to do this restriction?

A: Yes, you can do it in pretty much the same way. Given a measure $\mu_Y$ on $\Sigma_Y$, you can define $\mu_X$ by declaring that for any $A\in \Sigma_X$, you have $\mu_X(A)=\inf\{\mu(A')\mid A\subseteq A'\in \Sigma_Y \}$.
$\Sigma_X$ will not be contained in $\Sigma_Y$, but you can simply check directly that all the measure axioms hold.
This construction allows you to construct quite irregular measures. For example, you can find a subset $B$ of the reals which has full outer measure (with respect to any reasonable continuous measure) and such that every compact subset of $B$ is finite. Then $B$ is a metric space with lots of Borel measures, and such that no continuous measure is inner regular with respect to compact sets.


text:
Q: How to format a partitioned sd card? I have a SD card that has several partitions on it.
Running sudo fdisk -l gives me:
        Device Boot      Start         End      Blocks   Id  System
/dev/mmcblk0p1            8192     2121093     1056451    c  W95 FAT32 (LBA)
/dev/mmcblk0p2         2121728    15333375     6605824    5  Extended
/dev/mmcblk0p3        15333376    15398911       32768   83  Linux
/dev/mmcblk0p5         2129920     2252799       61440    c  W95 FAT32 (LBA)
/dev/mmcblk0p6         2260992    15333375     6536192   83  Linux

Note all the above devices does not show up when I disconnect the SD card, hence I can assume all the above is related to the SD card.
Note the SD card is 8GB.
How can I format the SD card so that it behaves like normal?

A: Try this:

*

*Insert sd card

*Open a terminal,Press Ctrl+Alt+T

*Run it:
sudo -i
umount /dev/mmcblk0p6
umount /dev/mmcblk0p5
umount /dev/mmcblk0p3
umount /dev/mmcblk0p2
umount /dev/mmcblk0p1
gparted

*In Gparted, create a new partition table on a sd card device:

*Select a sd card device.

*Choose: Device --- Create Partition Table.

*The application displays a Create partition table on /path-to-device dialog.

*Select a msdos partition table type.

*Apply

*Create a new partition.

*Select an unallocated space on the sd card device.

*Choose: Partition --- New. (The application displays the Create new Partition dialog)

*Specify the size and the location for the partition.

*Specify the type of partition.

*Specify the type of file system for the partition.

*Specify the label of the file system for the partition.

*Click Add to add the create partition operation to the operation queue.

A: *

*Go into the dash

*Type "disks"

*Choose the programs called disks

*Choose your device

*Delete all the partitions by selecting the blocks and click the minus sign

*Select the whole partition and click format

A simple Disks can do the job. Hope it helped :D


text:
Q: Reading input file and processing it in flask I'm trying to write a simple flask program that will create a web page in which it receives a file (by uploading it), and then using that file's data and displaying a filtered part of it in my web page, I just cant seem to understand how to do that.
This is the code I used to upload the file, which worked fine.
import os
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'C:/Users/ohadt/PycharmProjects/logFiles'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'log'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('read_uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form action="" method=post enctype=multipart/form-data>

<input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

Then I tried writing the method for opening the file and reading the data from it, but I couldn't figure how to do that, could you please help me understand how to read the file content and presenting a filtered version of it on my site?
Thanks!

A: You already saved it here
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

just open it up and read as you work with any other files, example:
@app.route('/read_file', methods=['GET'])
def read_uploaded_file():
    filename = secure_filename(request.args.get('filename'))
    try:
        if filename and allowed_filename(filename):
            with open(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as f:
                return f.read()
    except IOError:
        pass
    return "Unable to read file"

You need to carefully sanitize user input here, otherwise method could be used to read something unintended (like app source code for example). Best is just not grant user ability to read arbitrary files - for example when you save a file, store it's path in database with some token and give user just this token:
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
token = store_in_db(filepath)
return redirect(url_for('read_uploaded_file',
                                   token=token))

Then accept a token, not a filename when you read a file:
@app.route('/read_file', methods=['GET'])
def read_uploaded_file():
    filepath = get_filepath(request.args.get('token'))
    try:
        if filepath and allowed_filepath(filepath):
            with open(filepath) as f:
                return f.read()
    except IOError:
        pass
    return "Unable to read file"

Tokens need to be random, long, not guessable (uuid4 for example) - otherwise there will be a possibility to easily read other users files. Or you need to store relation between file and user in database and check it too. Finally, you need to control size of file uploads to prevent user from uploading huge files (app.config['MAX_CONTENT_LENGTH']) and control amount of info you read in memory when you display "filtered" file content (f.read(max_allowed_size)).


text:
Q: Bash command output string comparison and using IF ELSE condition How do I compare bash command output and use IF ELSE block to do something.
I am trying to capture the bash command output in CMD variable and if the variable is empty / zero, then output that the binary/feature is missing. Pretty basic.
In the below code, the second if else
# Check if the CPU supports KVM
cmd=$(grep -Eiw 'vmx|svm' /proc/cpuinfo)
if [[ $cmd -ne 0 ]];then
    echo "CPU on this machine does not support KVM. Check documentation please"
fi

#!/bin/bash

# Check if KVM kernel modules are installed.
cmd=$(lsmod | awk '{print $1}' | grep -Eiw 'kvm\|kvm_intel\|kvm_amd')
if [[ $cmd -ne 0 ]];then
    echo "KVM kernel modules kvm or kvm_[intel|amd] missing. Use modprobe to load them please"
fi

# Check if the CPU supports KVM
cmd=$(grep -Eiw 'vmx|svm' /proc/cpuinfo)
if [[ $cmd -ne 0 ]];then
    echo "CPU on this machine does not support KVM. Check documentation please"
fi

Instead of just checking the condition, the script is printing the command output (/proc/cpuinfo), I just want it to print the echo line but not the command output.

A: You should check command exit status, not it's output.
#!/bin/bash

# Check if KVM kernel modules are installed.
if ! lsmod | awk '{print $1}' | grep -q -Eiw 'kvm|kvm_intel|kvm_amd'; then
    echo "KVM kernel modules kvm or kvm_[intel|amd] missing. Use modprobe to load them please"
fi

# Check if the CPU supports KVM
if ! grep -q -Eiw 'vmx|svm' /proc/cpuinfo; then
    echo "CPU on this machine does not support KVM. Check documentation please"
fi

or
#!/bin/bash

# Check if KVM kernel modules are installed.
lsmod | awk '{print $1}' | grep -q -Eiw 'kvm\|kvm_intel\|kvm_amd'
ret=$?
if ((ret != 0)); then
    echo "KVM kernel modules kvm or kvm_[intel|amd] missing. Use modprobe to load them please"
fi

# Check if the CPU supports KVM
grep -q -Eiw 'vmx|svm' /proc/cpuinfo
ret=$?
if ((ret != 0)); then
    echo "CPU on this machine does not support KVM. Check documentation please"
fi

Also decide if you use grep 'vmx\|svm' or grep -E 'vmx|svm'. Escaping \| in -E will parse | as literal character. Here bashfaq How can I store the return value and/or output of a command in a variable? is a good bash introduction.
Also the grep -Eiw looks a bit strange. Are you really looking for a modules named KvM_InTeL or kVM_INteL or kVm_InTeL? There is only one module name, it's lowercase - kvm, kvm_intel, kvm_amd. Also using -w is irrelevant - lsmod | awk '{print $1}' output is already one per line. I would just go with grep 'kvm\|kvm_intel\|kvm_amd'.

A: You are making this more difficult than need be. You simply need to use a compound command to (1) check whether vmx or svm extensions are present in /proc/cpuinfo, and (2) check whether the kvm or kvm_intel module is loaded by checking /proc/modules. Using a compound command two calls are all that are needed:
#!/bin/bash

grep -wq 'vmx\|svm' /proc/cpuinfo || {   ## check CPU support
    printf "error: CPU does not support vmx or svm extensions.\n" >&2
    exit 1
}

grep -q '^kvm' /proc/modules || {        ## check modules loaded
    printf "error: CPU supports KVM, but kvm modules not loaded.\n" >&2
    exit 1
}

printf "CPU supports KVM and modules present.\n"

Example Use/Output
$ bash ~/scr/utl/kvmsupport.sh
CPU supports KVM and modules present.

You can do it any number of ways, but generally the simpler you can keep it, the less opportunity for error there is.

A: Thank you for your answers.
Many of you suggested using exit code which maybe the answer but I was specific about checking if the output result stored in the variable is an empty string or non-empty string and the [[ ]] test condition should not output to STD-OUT, just do a comparison without outputting anything to the terminal.
Second, I didn't want to use -q as it exits with zero status , not only for any match found but also for errors encountered.
Thirdly, I didn't use egrep as it is non-standard and deprecated [Ref:http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html]
Lastly, using -i and -w is redundant as the modules will be in lowercase and awk is doing the same as -w [Agreed] but just wanted to avoid assumptions esp that it will always be lowercase.
My Solution:
cmd=$(grep -Eiw 'vmx|svm' /proc/cpuinfo)
[[ -z "$cmd" ]] && echo "error: :CPU does not support KVM. Check documentation." && exit 1
-z does not output the return string to the terminal and just tells if the string is empty or non-empty.

A: The standard way to get a zero exit code if and only if some pattern is matched is grep --quiet PATTERN (or -q if you don't have GNU Grep). You can use the same pattern in a pipeline if grep is the last command in the pipeline or you use set -o pipefail to get the first non-zero exit code in the pipeline as the exit code of the whole pipeline.
So in your case it would simply be:
if lsmod | awk '{print $1}' | grep -Eiw 'kvm\|kvm_intel\|kvm_amd'
then
    …


text:
Q: How to convert this one-liner into a generator which returns k elements? How would you rewrite the following sliding window code using generator?
My issue is that each iteration I want to consume k=100 elements or the number of elements left.
n=1005
m=5
step=2
a=[(i,j) for i in range(0,n-m+1,step) for j in range(0,n-m+1,step) if i<j]

I came up with this solution:
Maybe this was a dumb question. Anyways here is a possible, non-optimal solution:
def my_gen(n,m,k,step):
    res = []
    count = 0
    for i in range(0,n-m+1,step):
        for j in range(0,n-m+1,step):
            if i<j:
                res.append((i,j))
                count += 1
                if count%k == 0:
                    yield res
                    res = []
    yield res

Validating it works:
n=104
m=5 # size of the window
step=2
k=8
a=[(i,j) for i in range(0,n-m+1,step) for j in range(0,n-m+1,step) if i<j]

gen=my_gen(n,m,k,step)
b=[]
for g in gen:
    b.extend(g)
for x,y in zip(a,b):
    assert(x==y)


text:
Q: Add JSON array data into a temp or real table I have JSON like this
DECLARE @json VARCHAR(MAX) = '{
    "prefix": "data",
    "body": [
        "Hello_1",
        "Hello_2",
        "Hello_3",
        "Hello_4"
    ]
}'

Now I want to add only "body" array into a table and get this output from table

A: DECLARE @json VARCHAR(MAX) = '{
    "prefix": "data",
    "body": [
        "Hello_1",
        "Hello_2",
        "Hello_3",
        "Hello_4"
    ]
}'

select value Name
from openjson(@json,'$.body')

or the more explicit:
DECLARE @json VARCHAR(MAX) = '{
    "prefix": "data",
    "body": [
        "Hello_1",
        "Hello_2",
        "Hello_3",
        "Hello_4"
    ]
}'

select Name
from openjson(@json,'$.body')
with
(
  Name  VARCHAR(20) '$'
)

output
Name
--------------------
Hello_1
Hello_2
Hello_3
Hello_4

(4 rows affected)

A: After some tried I got the query as
SELECT [VALUE] AS NAME into #temp_table FROM OPENJSON(@json,'$.body')

SELECT * FROM #temp_table


text:
Q: Apache in Docker won't deliver sites After installing an apache webserver in a docker container, I wanted to display a sample page just to make sure it works. However I always get 404 Not found.
Here's the dockerfile
FROM ubuntu:14.04
MAINTAINER <mail@example.org>
RUN DEBIAN_FRONTEND=noninteractive

# Install required packages
RUN apt-get -y update
RUN apt-get install -y apache2 libapache2-mod-php5 php5-gd php5-json php5-mysql php5-curl php5-intl php5-imagick bzip2 wget

# Enable the php mod
RUN a2enmod php5

# Configuration for Apache
ADD ./apache.conf /etc/apache2/sites-available/
RUN ln -s /etc/apache2/sites-available/apache.conf /etc/apache2/sites-enabled/
RUN a2enmod rewrite

RUN mkdir /var/www/test && echo "
Yo
" >> /var/www/test/index.html

EXPOSE :80

CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

apache.conf
<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www

    <Directory /var/www/test/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

</VirtualHost>

The container is up and running. Port 80 is forwarded to 8080 on the host machine.
When I browse to localhost:8080, I can see the apache2 default page. However, when I go to localhost:8080/test/index.html I do only get 404 Not found.

A: This is because you still have the default sites-enabled config.
To remove this file, you should add a line to remove this (probally around about the same place as where you add the new vhost configuration) with:
RUN rm -rf /etc/apache2/sites-enabled/000-default.conf

A: My guess is that it's a permissions issue. Remember, when creating the docker container from the dockerfile, everything is run as root. So your /var/www/test/index.html file is owned by root. My guess is that it has some restricted permissions.
Try this:
After
RUN mkdir /var/www/test && echo "
Yo
" >> /var/www/test/index.html

add
RUN chmod 0755 /var/www/test/index.html

This will reset the permissions on that file so that anyone can read it. If I'm right, that will fix your problem.

A: I just had a similar issue like this, and was able to resolve it.
First determine that apache2 is running or not
/etc/init.d/apache2 status

If it is not running, you can add this to your dockerfile:
CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"]


text:
Q: continuity in one point mean and the definition this is real analysis continuity and limit section
I heard that "function can be continuous in one point"
this make a little sense and i can force to myself to accept it
but i want to understand this concept more naturally
=====================================================
if a certain pint is not an isolated point it can say that its continuous in that point?

A: The definition of continuity in one point is:
$$
\lim_{x\to a+} f(x) = \lim_{x\to a-} f(x) = f(a)
$$
, where those limits are lateral limits.
Translated into English, this means that for a point a, the function is continuous if a is next to the points in left and next to the points in right. So, there is no 'gap' between those points.
Another perspective would be to take a projection of f(x) on x axis and on y axis, on a vecinity of a. In order to be continuous in a, there must be no gap, no matter how small is the vecinity.
I know my explanation is not very academical, but i hope you get a better understanding of continuity.

A: For example let $f:[0,1]\cup ${${2}$}$\to \Bbb R$ with $f(x)=x$. Then $f$ is continuous,because is continuous in $[0,1]$ and {$2$} is isolated point.


text:
Q: How to SELECT * from table WHERE day of month = current day of month and not miss users on the 31st I have a cron job that emails a list of users monthly. The cron runs daily and searches for the signup_date in the users table. The idea is to mail the user 1 month after they signup and continue to do this for the life of their account. I was thinking of doing something like this:
SELECT *
FROM users
WHERE DAYOFMONTH(signup_date) = DAYOFMONTH(now());

The problem is this will miss users every other month that signup on the 31st (not to mention problems in February with leap years). Is there and sql statement that will ensure that every user will get selected at least once a month when run daily? I don't really want to create an extra field in the DB either (such as date_last_emailed).

A: Maybe on the last day of the month include all the users that signed up that day or later?
WHERE IF(
  DAY(NOW()) == DAY(LAST_DAY(NOW())),
  DAY(signup_date) >= DAY(NOW()),
  DAY(signup_date) = DAY(NOW())
)

A: SELECT a, b
  FROM tbl
 WHERE DAYOFMONTH(signup_date) = DAYOFMONTH(CURRENT_DATE)
       OR
       -- special handling for end of month
       (LAST_DAY(CURRENT_DATE) = CURRENT_DATE
        AND
        DAYOFMONT(signup_date) > DAYOFMONTH(CURRENT_DATE))

On Feb. 28 of a non-leap year, this will email those who signed up on the 29th, 30th or 31st of any month.
UPDATE
Corrected per comments.


text:
Q: raise TypeError("expected non-empty vector for x") TypeError: expected non-empty vector for x I have a project which is OpenCV python lane dedection, i can easily run code with video(importing VideoFileClip in moviepy.editor). Actually when i try to convert video file to real time using VideoCapture. I can get this error:
Traceback (most recent call last):
  File "advanced_lane_finding(1).py", line 619, in <module>
    a=process(frame)
  File "advanced_lane_finding(1).py", line 575, in process
    left_poly = fit_poly(binary,llo, lhi, process.old_left_points)
  File "advanced_lane_finding(1).py", line 462, in fit_poly
    poly = np.poly1d(np.polyfit(pts[0],pts[1],2))
  File "<__array_function__ internals>", line 5, in polyfit
  File "/usr/lib/python3/dist-packages/numpy/lib/polynomial.py", line 601, in polyfit
    raise TypeError("expected non-empty vector for x")
TypeError: expected non-empty vector for x

I want to run with my webcam my code


text:
Q: How can I find out if a user has an iPhone in portrait mode? I'm still confused with these changes in iOS8. I need to know if a user uses an iPhone in portrait mode. If so I want to change one constraint. Otherwise I leave it as set as in the interface builder. So how can I determine the device?
Thx!

A: Select the constraint you want to define screen layouts for:

Select the screen layouts you need your constraint installed.

A: How about this one: UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]
?


text:
Q: Laravel Carbon issue on certain date only I have a problem that occurs only with a specific date ... I have tried the code with a wide variety of dates and they all work, except 2020-03-14, when trying to display that date in local format using formatLocalized () no information is displayed.
Here is the code:
setlocale(LC_ALL, 'es_ES');
$date= "2020-03-13 06:30:00";
$fecha = \Carbon\Carbon::parse($date);
$fecha = $fecha->formatLocalized('%A, %d de %B del %Y');
$fecha = ucfirst($fecha);

Shows:
Viernes, 13 de marzo del 2020.
But when I change it to $date to "2020-03-14 06:30:00", it shows nothing.
Please try to reproduce it, thanks!

A: I replicated this code block and used "2020-03-14 06:30:00" and I got this output "Sábado, 14 de marzo del 2020".
setlocale(LC_ALL, 'es_ES');
$date= "2020-03-14 06:30:00";
$fecha = \Carbon\Carbon::parse($date);
$fecha = $fecha->formatLocalized('%A, %d de %B del %Y');
$fecha = ucfirst($fecha);

Are you sure there isn't something you are missing?

A: I have found it, the problem was not only on that date but on all dates corresponding to Wednesday and Saturday, due to the accent (miércoles / sábado). I added a line to encode utf-8 and the problem has been resolved. Thank you!.
setlocale(LC_ALL, 'es_ES');
$date= "2020-03-14 06:30:00";
$fecha = \Carbon\Carbon::parse($date);
$fecha = $fecha->formatLocalized('%A, %d de %B del %Y');
$fecha = utf8_encode($fecha);
$fecha = ucfirst($fecha);


text:
Q: what's wrong with this method for csrf token with ajax form post in django? I've been looking for few days now how to convert form submissions to ajax with jquery, and the csrf token issue is puzzling me.
I solved the problem by adding the javascript snippet found here :
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
But when stumbling on stackoverflow, I found simpler answers (not the first one):
Django CSRF check failing with an Ajax POST request
Some answers suggest to simply add the following to the post data:
csrfmiddlewaretoken: '{{ csrf_token }}'
But this seems too good to be true, if that was that easy, why would we need to copy the long snippet from the django website ? Also there's a quick comment to one of the replies about static JS. I don't really get it.
Could anyone please explain why the simplest solution isn't the best, and give some practical examples ?
Thanks

A: The two solutions are effectively doing exactly the same thing. Supplying the csrftoken to Django in the request. They're just doing it in different ways.
'Simpler' option
For a single jQuery call in a Django template, it may be simpler to use the {{ csrf_token }} tag to add to the post data. However as soon as there are multiple calls in multiple places, it becomes harder to maintain.
jQuery Code
On the other hand, the jQuery code:

*

*Can be included in one place, in a static .js file

*Doesn't need to be in a django template

*Can be included in multiple pages

*Works for all jQuery Ajax calls without modifying the individual calls

*Includes working with any third party jQuery libraries

*Is the same everywhere, so easy to share in the Django documentation

How it works
The extra complexity of the jQuery code is due to it running in the browser, without access to any Django variables.
The code works by attaching to a jQuery event used for every Ajax call. It looks up csrftoken from a cookie stored in the browser, determines whether to send the token, based on the request type and host, and sends the token as a HTTP header, instead of including it in the POST data.


text:
Q: making first letter of input uppercase with split in python I got most of the code down but I am having issues getting the string to space back out after making the first letter of each word uppercase
here's what I have so far:
message = input('Write a short message.')
new_message = message.split()
glue = ""
for item in new_message:
glue += item[0].upper() + item[1:]
print(glue)

A: try with:
message.capitalize()

A: If you want to capitalize each word you can try capitalize() and the code will look like this:
  message = input('Write a short message.')

  new_message = message.split()
  cap_message = [x.capitalize() for x in new_message]
  print(cap_message)

*

*message.split() - split the string into a list using default separator which is any whitespace. The result is a list of words.

*capitalize each word in the list using List Comprehention. The list of capitalized words is saved in cap_message variable for code clarity.

*print the list of capitalized words


text:
Q: Attempt to present  on  whose view is not in the window hierarchy I am attempting to fetch lat long coordinates from a postcode/zipcode using google api:
func getLatLngForZip(zipCode: String, completion: CLLocationCoordinate2D -> ())  {

    let url: NSURL = NSURL(string: "\(baseUrl)address=\(zipCode)&key=\(apikey)")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: url)
    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(urlRequest) {
        data, response, error -> Void in

        var locationCoordinates = CLLocationCoordinate2D()

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode
        if (statusCode == 200) {
            print("Everything is fine, GoogleAPI downloaded successfully.")

            do{
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                if let result = json["results"] as? NSArray, let status = json["status"] as? String {

                    if status == "OK" {
                        if let geometry = result[0]["geometry"] as? NSDictionary {
                            if let location = geometry["location"] as? NSDictionary {
                                let latitude = location["lat"] as! Double
                                let longitude = location["lng"] as! Double
                                print("\n\(latitude), \(longitude)")
                                locationCoordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
                            }
                        }
                        dispatch_async(dispatch_get_main_queue()) {
                            completion(locationCoordinates)
                        }
                    } else {
                        let vc = PostCodeController()
                        let alert = UIAlertController(title: "Alert", message: "", preferredStyle: .Alert)
                        let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
                        alert.addAction(action)
                        vc.presentViewController(alert, animated: true, completion: nil)

                    }
                }
            } catch let error {
                print("Error with GoogleAPI: \(error)")
            }
        }
    }
    task.resume()
}

simply, if the status from the json is "OK", then the postcode/zipcode entered is correct and the lat long can be fetched.  Otherwise, the postcode is invalid for one reason or another and I want to display an alert telling the user that the postcode entered is invalid.
I understand that the code inside the else clause should not be there.  I feel like I should be calling the alert from inside PostCodeController(), not where it is now.
This is how its called from in PostCodeController()
func tappedFindSalonButton(sender: UIButton!) {
    self.postCode = self.finderView.textField.text!
    fetchGoogleAPI()
}

func fetchGoogleAPI() {
    GoogleAPI().getLatLngForZip(finderView.textField.text!) {
        location in
        self.presentListControllerWithLocation(location)
    }
}
func presentListControllerWithLocation(locationCoordinate: CLLocationCoordinate2D) {

    let listController = ListController()
    listController.currentLocation = CLLocation(latitude: locationCoordinate.latitude, longitude: locationCoordinate.longitude)
    listController.postCode = postCode
    let vc = UINavigationController(rootViewController: listController)
    presentViewController(vc, animated: true, completion: nil)
}

Why am I getting in this situation 'Attempt to present "" on "" whose view is not in the window hierarchy'? I've come across it before but haven't fully grasped the meaning of it.
How can I change my code to display an alert when the postcode entered is invalid?


text:
Q: How to group different rewrite rules in nginx? I would like to have a lighter code for one of my NGINX configurations. I need to write the following four lines in only one (if possible!):
location /en/contact {
    rewrite ^/.* https://$server_name/contact permanent;
}

location /en/quality {
    rewrite ^/.* https://$server_name/quality permanent;

location /de/contact {
    rewrite ^/.* https://$server_name/contact permanent;
}

location /de/quality {
    rewrite ^/.* https://$server_name/quality permanent;
}

Thanks!

A: Using minimal typing, you could use a rewrite statement outside of any location block:
rewrite ^/(en|de)/(contact|quality) https://$server_name/$2 permanent;

If the scheme and server name does not change, the second parameter can be replaced with just /$2. See this document for more.
Alternatively, you could use a regular expression location block:
location ~ ^/(en|de)/(contact|quality) {
    return 301 https://$server_name/$2;
}

Same as above, regarding the scheme and server name. Note that the evaluation order for regular expression location blocks is significant - the first rule that matches wins. See this document for more.


text:
Q: Record answer label of the choice for randomization in Qualtrics using javascript I am designing a survey in Qualtrics. each question has multiple choice answers, 5 fixed and 8 random, the 5 multiple choices will be constant and render all the time. I'll throw only one choice out of the 8 randomize choices to be presented with the 5 constant choices, so total multiple choices will be render is 6. Finally I need to capture in the embedded data field which choice of the 8 random was associated with the 5 fixed choices. I found this code and it works perfect But so far its capturing the IDs of the choices. however, I need to capture the label name of the item instead of the IDs.

//get the div containing the choices, then get all input child elements of that div
var choices = this.getChoiceContainer().getElementsByTagName("input");
//initialize an array for the IDs of the choices
var choiceIDs = []
//add the ID of each choice to the array
for (var i=0; i < choices.length; i++) {
 choiceIDs.push(choices[i].id);

}
//get the current choice order from embedded data and add this loop to it.
//Add a | to distinguish between loops.
var choiceOrder = "${e://field/choiceorder}" + choiceIDs.toString() + "|";
//set the embedded data with the new value
Qualtrics.SurveyEngine.setEmbeddedData("choiceorder", choiceOrder);

A: You don't need JavaScript for this.  You can just pipe the displayed choices into an embedded variable in the survey flow:
choiceorder = ${q://QIDxx/ChoiceGroup/DisplayedChoices}


text:
Q: How can I decode a JSON response with an unknown key in Swift? I would like to split up the data in https://blockchain.info/ticker so that each line is its own String in an array.
I'm making an app that gets the price of the selected currency. So if someone wants AUD then it will get the second string in the array and then show the price which is in the last tag.
I currently just have it downloading the json..
func reloadJson(){

    if globalVariables.currencySelected == "" {
        globalVariables.currencySelected = globalVariables.currencySelected + "AUD"
    }
    print(globalVariables.currencySelected)

    if let blockchainTickerURL = URL(string: "https://blockchain.info/ticker") {

        let request = NSMutableURLRequest(url: blockchainTickerURL)
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            var message = ""

            if error != nil {
                print("error")
            } else {
                if let unwrappedData = data {
                    let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

Thats just a copy and paste of what I currently have, its not exactly formatted right.
Thanks

A: You should take a look at Swift4 Codable protocol.
Create a structure for the currency dictionary values that conforms to Codable with the corresponding properties:
struct Currency: Codable {
    let fifteenM: Double
    let last: Double
    let buy: Double
    let sell: Double
    let symbol: String
    private enum CodingKeys: String, CodingKey {
        case fifteenM = "15m", last, buy, sell, symbol
    }
}

To decode your JSON data you need to use JSONDecoder passing the dictionary with custom values [String: Currency] as the type to be decoded:
let url = URL(string: "https://blockchain.info/ticker")!
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    do {
        let currencies = try JSONDecoder().decode([String: Currency].self, from: data)
        if let usd = currencies["USD"] {
            print("USD - 15m:", usd.fifteenM)
            print("USD - last:", usd.last)
            print("USD - buy:", usd.buy)
            print("USD - sell:", usd.sell)
            print("USD - symbol:", usd.symbol)
        }
    } catch { print(error) }

}.resume()

This will print

USD - 15m: 11694.03
USD - last: 11694.03
USD - buy: 11695.01
USD - sell: 11693.04
USD - symbol: $


text:
Q: Print the maximum element with their index position I'm printing the maximum element in the array with their index. I tried this.
int[] a = {10,20,30,40,40};
int index = 0;
int max = a[0];
for(int i = 0; i < a.length; i++)
{
    if(a[i] > max)
    {
         max = a[i];
         index = i;
    }
}
System.out.print(max + " " + index);

This prints " 40 3". But I need "40 3 40 4". How can I change the code to print both maximum element 40 with their index?

A: You can find the max value and check the array for it e.g.
int[] a = {10, 20, 30, 40, 40};
int max = Arrays.stream(a).max().getAsInt();
for (int i = 0; i < a.length; i++) {
      if (a[i] == max) {
        System.out.print(max + " " + i);
     }
}

A: If you want to find all the max values and also store them in a way you can reuse them later you can use a Map with the max and index set as the Value and Key respectively.  Below is one way to implement this:
    //Max is the value, Key is the index
    Map<Integer, Integer> m = new HashMap<>();

    int [] a={10,20,30,40,40};

    int max=a[0];

    for(int i=0;i<a.length;i++)
    {
        if(a[i] >= max)
        {
            max=a[i];
            //If the value is not inside the map, empty the map
            if (!m.containsValue(max))
            {
                m.clear();
            }
            //Place the value into the map
            m.put(i, max);
        }
    }
    System.out.print(m.toString());

This will output (you can change the way you print to anything to want):
{3=40, 4=40}


text:
Q: Netsuite Suitetalk service reference not working in ASP.NET and Visual Studio I can't get Visual Studio (VS) to recognize the methods from the Netsuite sample code or other posts here. I'm attaching a screenshot (http://www.rpmex.com/img/Untitled-1.jpg) of my VS screen. The code is mostly from page 24 of the Netsuite documentation.
I have imported the WSDL in VS as a service reference. Was this wrong? I see a post (What is the difference between NetSuitePortType and NetSuiteService?) that says there is a distinction between a service reference and a web reference. The Netsuite documentation does say to import a web reference, but VS doesn't seem to have anything with that terminology.
VS is recognizing some methods like RecordRef, but it doesn't recognize calls to NetsuiteService or Passport, as you can see on the screenshot because those terms are underlined. Because there is a functioning namespace for the Netsuite Service Reference I assume I don't need to put a "using netsuiteServiceReference.com.netsuite.webservices; " line, but I did because the documentation says so.
My understanding is that VS should be recognizing any function call that is valid. Where am I going wrong?
In the following code I bolded (it is putting it bracketed in **) what VS has underlined as a syntax error
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using **netsuiteServiceReference.com**.netsuite.webservices;

namespace WebApplication5
{
    namespace netsuiteServiceReference
    {
        **NetSuiteService** service = new **NetSuiteService**();
        service.CookieContainer = new **CookieContainer**();
        //invoke the login operation
        Passport passport = new **Passport**();
        passport.account = "TSTDRV96";
        passport.email = "username@netsuite.com";
        RecordRef record = new **RecordRef**();
        role.id = "3";
        passport.record = record;
        passport.password = "mypassword";
        Status status = service.login( passport ).status;
    }
    public partial class ThursdayTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

A: Sounds like you created a Service Reference. You must create a Web Reference.

*

*Right click on project in solution explorer.

*Click Add > Service reference.

*On Service Reference screen, click Advanced button.

*On next screen, click Add Web Reference box.

*On next screen, enter NetSuite WSDL, e.g. https://webservices.netsuite.com/wsdl/v2014_1_0/netsuite.wsdl

*This will take a moment to load. Click through the warnings, and Add Reference.

*Now replace your includes, should look like
using MySolution.com.netsuite.webservices;

A: You may start from the SuiteTalk sample application that can be found here: http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml
This loads fine in Visual Studio.