Q: How should I pass a String argument to clojure.core/apply I have the following piece of code:
  (condp apply "string argument"
    predicate1? "Result1"
    predicate2? "Result2"
    predicate3? "Result3"
                "Else")

Currently, "string argument", when passed to apply gets interpreted as a seq, therefore each character becomes a parameter to the predicate:
(apply predicate1? \s \t \r \i \n ...)

A simple solution would be to wrap the argument in a vector:
(condp apply ["string argument"] ...)

I'm not sure this is very idiomatic. Is there a better solution?

A: I don't think there is a more idiomatic way than using cond directly, binding "string argument" to a symbol and passing it to each predicate. Everything else looks confusing to people reading your code and involves extra function calls.
Extra magic could be achieved with the following helper macro:
(defmacro pcond
  "Translates clauses [pred result-expr] to a cond form:

   (cond
    (pred expr) result-expr
    ...)

   A single result-expr can follow the clauses, and it will be appended
   to the cond form under a generated test expression that returns logical
   true."
  [expr & clauses]
  (let [expr-sym (gensym "expr")
        else-kw (keyword (gensym "else"))
        step (fn [[pred-form clause-form]]
               (if (= else-kw clause-form)
                 [else-kw pred-form]
                 [(list pred-form expr-sym) clause-form]))
        body (->> clauses
                  (partition 2 2 [else-kw])
                  (mapcat step))]
    `(let [~expr-sym ~expr]
       (cond ~@body))))

You can use it so
(pcond "String argument"
    predicate1 "Result1"
    predicate2 "Result2"
    "Else")

It macroexpands directly to cond:
(clojure.core/let [expr13755 "String argument"]
   (clojure.core/cond
     (predicate1 expr13755) "Result1"
     (predicate2 expr13755) "Result2"
     :else13756 "Else"))

A: You can use the anonymous function #(%1 %2) for what you are trying to do. IMO it's better than wrapping the condp expression in a vector, but either way works, neither is really straigthforward.
(condp #(%1 %2) "string argument"
    string? "string"
    map?    "map"
    vector? "vector"
    "something else")

;= Result1

EDIT (copied from the comments)
I'm no expert on macros, but what I've heard over and over is that you shouldn't write a macro if a function will do and condp provides all the elements to use the power of Clojure functions. An approach that doesn't involve macros and improves readability could be defining a function (def apply-pred #(%1 %2)) and use it with condp.


Q: bypassing javascript to get page source 1)I am building an app for downloading all my pictures from my instagram profile.
2)I don't want to use instagram api so i searched and i find Selenium Webdriver and i add this package to my project
3)I am using c# to build android app (Xamarin)  check below Code.
    string url = "https://www.instagram.com/" + _theUsername;
    IWebDriver driver = new FirefoxDriver();
    driver.Url = url;
    string source = driver.PageSource;

4)By Using above code i am getting below error :-
 OpenQA.Selenium.DriverServiceNotFoundException: The geckodriver file does not exist in the current directory or in a directory on the PATH environment variable

5)Is it possible to use this in xamarin? i need to find a way to do this
any help will be greatly appreciated

A: I am not familiar with Selenium, but getting the page source for a url is easy with HttpClient:
string url = "https://www.instagram.com/" + _theUsername;
using (var httpClient = new HttpClient()){
    var response = await httpClient.GetStringAsync(url);
    Debug.WriteLine(response);
}

and response will have your page source. And if you do not want to show the web page then there is no need for a WebView anyway.


Q: An Azure function works from Postman but not from web browser and javascript I have a C# Azure function that manipulates an image file and returns a . Following is the complete code.
[FunctionName("ImageHandler")]
        public static async Task<IActionResult> GetHandledImage([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
        {
            int CaseID = Convert.ToInt32(req.Query["CaseID"]);
            int ImageID = Convert.ToInt32(req.Query["ImageID"]);
            int ApplyAngle = Convert.ToInt32(req.Query["RotationAngle"]);
            string ImagePath = req.Query["ImagePath"].ToString();

            string ImageServer = "https://localhost:44331/training/Images";

            string FullImagePath = string.Format("{0}{1}", ImageServer, ImagePath);
            string Format = "";
            MemoryStream ms;

            using (WebClient wc = new WebClient())
            {
                var imageData = await wc.DownloadDataTaskAsync(new Uri(FullImagePath));

                using (var BitmapStream = new MemoryStream(imageData))
                {
                    Bitmap b = new Bitmap(BitmapStream);
                    ImageFormat ImageFormat = b.RawFormat;

                    b = RotateImage(b, ApplyAngle, true);

                    using (ms = new MemoryStream())
                    {
                        if (ImageFormat.Equals(ImageFormat.Png))
                        {
                            Format = "image/png";
                            b.Save(ms, ImageFormat.Png);
                        }

                        if (ImageFormat.Equals(ImageFormat.Jpeg))
                        {
                            Format = "image/jpg";
                            b.Save(ms, ImageFormat.Jpeg);
                        }
                    }
                }
            }
            return new FileContentResult(ms.ToArray(), Format);
        }

The problem I am facing is that this function works ok when invoked from Postman but not from my own code. Also, I am hosting the function on http://localhost:7001/api/
Following is my local.settings.json file:
    {
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "EmailScheduleTriggerTime": "0 0 */6 * * *",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "SqlConnectionString": "***",
    "URL": "*****"
  },
  "Host": {
    "LocalHttpPort": 7071,
    "CORS": "*",
    "CORSCredentials": false
  }
}

Can someone please help me understand what I could do so I can this function from my browser too.
I am getting HTTP 404 error when accessing from my browser.
Thanks.


Q: Linkify hashtags based on match.group(1) I am trying to Linkify hashtags in a TextView.
Thats is working as sample code I provided but I need to underline found hashtags based on match.group(1).
Linkify seems to underline based on match.group(0).
With TransformFilter I can only change hashtag click destination not the preview of underline link.
As a summary, Linkify creates underlines on match.group(0) but I want underlines on match.group(1)
TextView tv_body = (TextView) view.findViewById(R.id.tv_body);
final Pattern pattern = Pattern.compile(
    "(?:^|\\W)#([A-Za-z\\d\u00E7\u011F\u0131\u015F\u00F6\u00FC\u00C7\u011E\u0130\u015E\u00D6\u00DC]+)");
String scheme = "search://";

TransformFilter filter = new TransformFilter()
{
    public final String transformUrl(final Matcher match, String url)
    {
        Log.d(Constants.TAG, "transformUrl - match.group(0):" +
            match.group(0) + " - match.group(1):" + match.group(1));
        return match.group(1);
    }
};
Linkify.addLinks(tv_body, pattern, scheme, null, filter);

transformUrl - match.group(0):##dene    - match.group(1):dene
  transformUrl - match.group(0):#hashreal - match.group(1):hashreal
  transformUrl - match.group(0):+#arti    - match.group(1):arti
  transformUrl - match.group(0):(#de      - match.group(1):de
  transformUrl - match.group(0):#feriştah - match.group(1):feriştah

/*
tv_body text content:
nb#dnkjd
##dene
#hashreal
1#2
+#arti
%d(#de
#feriştah
şah#in
*/

A: If you want to exclude the text matched by (?:^|\\W)#, enclose it in a look-behind:
(?<=(?:^|\\W)#)

Then you can drop the capturing group, and the main match will contain only the content after the #.

Before, I'd suggest this:
(?<=\B#)

However, after looking at this bug report and this question about inconsistency between \w and \b in Java, I'd say you need to be careful when using the shorter one, since \b and \B's definition in default mode is not synced with \w.


Q: How make div not scrolling, fixed and keeps there width base on parent container I have page that contains three elements: a header, an article, and a aside.
I want the scroll to only affect the article, and I’d like the header and aside to stay fixed.
I can make header fixed by using position: fixed; and it works.
But when I do the same to aside, its width swaps from being 30% of the width of the container to 30% of the browser width.
So I need the aside to be fixed (not scroll), but at the same time have a width of 30% of its container.
Snippet below, JSFiddle Link

.body-header {
  background: blue;
  height: 50px;
  position: fixed;
  width: 100%;
  top: 0px;
}

.body-content {
  width: 60%;
  margin: auto;
}

article {
  width: 70%;
  display: inline-block;
  float: left;
  margin-top: 60px;
}

aside {
  width: 30%;
  background: black;
  height: calc(100vh - 50px);
  display: inline-block;
  float: left;
  margin-top: 45px;
}

    header

Introduction t ththth tht

Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse risus, lacinia sit amet aliquet sit amet, ultricies nec ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris scelerisque vestibulum facilisis. Curabitur hendrerit a libero id ullamcorper. Nam scelerisque felis non nunc tempus fringilla. Proin ullamcorper, massa vitae elementum aliquam, lectus velit imperdiet mauris, nec blandit justo leo ut nisl. Etiam sollicitudin, urna eget malesuada convallis, augue nunc molestie erat, fringilla fringilla augue purus ac lacus. Donec sagittis nisl quis rhoncus fermentum. Sed a velit sem. Suspendisse tempor tempus dolor, ac porta velit porta at. Integer mi est, commodo non aliquam et, venenatis id felis.Sed venenatis diam est, ut volutpat nisl laoreet sed. Sed ut quam sed nibh pharetra congue. Donec ullamcorper, arcu vel finibus dictum, urna purus congue libero, quis fringilla erat ante maximus mauris. Suspendisse odio sem, mollis ac mauris non, viverra bibendum elit. Phasellus malesuada augue nulla, vitae eleifend sapien vehicula et. Aliquam pharetra imperdiet mauris non scelerisque. Donec dictum fringilla ante ac accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut id tempus nisi, ut aliquet justo. Duis a pretium ligula. Morbi facilisis urna sed lacus feugiat, nec laoreet purus fermentum. Proin semper nisi nec sapien porta, quis dapibus tellus auctor Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus.

      g

A: I'd think the easiest way to achieve this would be to use some JavaScript.
Using the example code below should do the trick:
var aside = document.getElementsByTagName("aside")[0],
    parent = document.getElementsByClassName("body-content")[0];

aside.style.width = ((parent.offsetWidth / 10) * 3) + "px";

Using this code and having the position set to fixed should give the desired effect.

A: So you want aside to be 30% of body-content which is also a percentage?
With a bit of maths, you can do the following:
You want 30% of 60%, which works out at 18%.
60 divided by (10/3) = 18
So change your aside to this (add position: fixed and change width to width: 18%):
aside {
  width: 18%;
  background: black;
  height: calc(100vh - 50px);
  display: inline-block;
  float: left;
  margin-top: 45px;
  position: fixed;
}

And you will have the result you wanted.

.body-header {
  background: blue;
  height: 50px;
  position: fixed;
  width: 100%;
  top: 0px;
}

.body-content {
  width: 60%;
  margin: auto;
}

article {
  width: 70%;
  display: inline-block;
  float: left;
  margin-top: 60px;
}

aside {
  width: 18%;
  background: black;
  height: calc(100vh - 50px);
  display: inline-block;
  float: left;
  margin-top: 45px;
  position: fixed;
}

    header

Introduction t ththth tht

Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse risus, lacinia sit amet aliquet sit amet, ultricies nec ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris scelerisque vestibulum facilisis. Curabitur hendrerit a libero id ullamcorper. Nam scelerisque felis non nunc tempus fringilla. Proin ullamcorper, massa vitae elementum aliquam, lectus velit imperdiet mauris, nec blandit justo leo ut nisl. Etiam sollicitudin, urna eget malesuada convallis, augue nunc molestie erat, fringilla fringilla augue purus ac lacus. Donec sagittis nisl quis rhoncus fermentum. Sed a velit sem. Suspendisse tempor tempus dolor, ac porta velit porta at. Integer mi est, commodo non aliquam et, venenatis id felis.Sed venenatis diam est, ut volutpat nisl laoreet sed. Sed ut quam sed nibh pharetra congue. Donec ullamcorper, arcu vel finibus dictum, urna purus congue libero, quis fringilla erat ante maximus mauris. Suspendisse odio sem, mollis ac mauris non, viverra bibendum elit. Phasellus malesuada augue nulla, vitae eleifend sapien vehicula et. Aliquam pharetra imperdiet mauris non scelerisque. Donec dictum fringilla ante ac accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut id tempus nisi, ut aliquet justo. Duis a pretium ligula. Morbi facilisis urna sed lacus feugiat, nec laoreet purus fermentum. Proin semper nisi nec sapien porta, quis dapibus tellus auctor Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus.

      g


Q: read data from excel in perl I am trying to read data from excel, i have below code.
    #!/usr/bin/perl
    use strict;
    use warnings;
    use 5.010;
    use feature 'say';
    use Spreadsheet::XLSX;
    use Spreadsheet::Read qw(ReadData);
    my $book = ReadData ('/tmp/simple.xlsx');

    say 'A1: ' . $book->[1]{A1};

    my @row = Spreadsheet::Read::row($book->[1], 1);
    for my $i (0 .. $#row) {
        say 'A' . ($i+1) . ' ' . ($row[$i] // '');
    }

    my @rows = Spreadsheet::Read::rows($book->[1]);
    foreach my $i (1 .. scalar @rows) {
        foreach my $j (1 .. scalar @{$rows[$i-1]}) {
        say chr(64+$i) . " $j " . ($rows[$i-1][$j-1] // '');
        }
    }

getting the error as:
        Can't locate OLE/Storage_Lite.pm in @INC (@INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at /usr/local/share/perl5/Spreadsheet/ParseExcel.pm line 21.
    BEGIN failed--compilation aborted at /usr/local/share/perl5/Spreadsheet/ParseExcel.pm line 21.
    Compilation failed in require at /usr/local/share/perl5/Spreadsheet/XLSX.pm line 14.
    BEGIN failed--compilation aborted at /usr/local/share/perl5/Spreadsheet/XLSX.pm line 14.
    Compilation failed in require at read_excel.pl line 6.
    BEGIN failed--compilation aborted at read_excel.pl line 6.

I have every related module. but as per error when i am going to download OLE/Storage_Lite.pm from the CPAN, page is going blank, and from metacpan below error is coming.
        https://cpan.metacpan.org/authors/id/M/MS/MSCHWARTZ/OLE-Storage-0.386.tar.gz
    Resolving cpan.metacpan.org... 151.101.128.249, 151.101.192.249, 151.101.64.249, ...
    Connecting to cpan.metacpan.org|151.101.128.249|:443... connected.
    ERROR: certificate common name “a.ssl.fastly.net” doesn’t match requested host name “cpan.metacpan.org”.
    To connect to cpan.metacpan.org insecurely, use ‘--no-check-certificate’.

A: Try downloading the module tar zip from cpan or metacpan. Then build the module locally using any make utility(e.g.dmake). You can find more info for building module locally from here.


Q: DialogFlow error when launching Google Assistant Console I'm using DialogFlow to build a Action for Google Assistant. I want to build this for pt-BR language, but when I am going to test the actions on Actions on Google console I'm getting the following error "Request contains an invalid argument. Locale pt-br selected but the language pt-BR has not been selected." as in the following image:

The steps for reproduce this issue:

*

*Create a agent pt-BR language

*Click on "See how it works on Google Assistant"

And the error appers at bottom of the browser window.
So guys, do anyone know the solution for this issue or a workaround?

A: The Google Issue haven't closed yet, but the problem was fix by the Google Team.


Q: how to define in svelte.js a global variable over several pages using svelte-router-spa I'm trying to learn svelte and build a card-solution with routing through svelte-router-spa. On each view (index and productdetails) i import my variable basket. This should contain my card-array over the different pages. Unfortunately on every page my array is empty again. How can I define a global var through every page?
thanks for your help.

A: This sounds like a problem that can be solved using a writable store. Stores (if you don't know) are essentially storage for things such as variables and other data which apply across all your components (if imported from your stores file).
The documentation can be found here: https://svelte.dev/tutorial/writable-stores


Q: Right Approach to Call Web Service(API) from Fragment in Android I have an activity which has a fragment and a dialog. And I am calling an API from the fragment in the onCreateView method. And when I am on the fragment and opens the dialog then fragment again hits the API. I want to prevent it.I want that my app do not hit when I am opening a dialog.
// code
    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_news, container, false);

        callApi()

         }

A: call your api in onViewCreated like this.
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

           callApi();  //here call your function.

    }


Q: How to add Background color for JOptionPane Completely? I am not getting a complete background color for JOptionPane.
Below there is one of my output screen:
http://i.stack.imgur.com/i4tvh.png
And my code:
JFrame frame1 = new JFrame("Showing Error Message");
                    UIManager UI=new UIManager();
                    UI.put("OptionPane.background", Color.BLUE);
                    UI.put("OptionPane.messagebackground", Color.BLUE);
                    UI.put("Panel.background", Color.BLUE);
                    JOptionPane.showMessageDialog(frame1,errorMessage1);

A: First of all, the public methods of UIManager are static. It is incorrect, misleading, and pointless to create an instance of UIManager. The correct way to invoke those methods is:
UIManager.put("OptionPane.background", Color.BLUE);
UIManager.put("OptionPane.messagebackground", Color.BLUE);
UIManager.put("Panel.background", Color.BLUE);

This is the whole sample.
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class Main extends JFrame
{
   public static void main(String []args) {
      UIManager.put("OptionPane.background", Color.blue);
      UIManager.put("Panel.background", Color.blue);
      UIManager.put("Button.background", Color.white);

      String value = JOptionPane.showInputDialog("Enter your name");
      System.out.println("Hello " + value);

      // exit awt thread
      System.exit(1);
   }
}

A: In nimbus look and feel these all codes are not usable.
So solution is,
UIManager.put("control", new Color(0, 0, 0));

This is also call "Dark Nimbus" add this top of your main frame's main method.
So it will automatically change All JOptionPane's background.
And also you can't change button background with
UIManager.put("OptionPane.buttonBackground", BLACK);

So you should use,
UIManager.put("nimbusBase", new Color(0, 0, 0));

Remember - but unfortunately, this code will change all your buttons etcs' background. So you have to add *.setBackground(...); to all other objects.
If you want to change foreground of JOptionPane you should use
UIManager.put("text", new Color(255, 255, 255));

Again unfortunately this will change your all of text's foreground.
These all codes are called Dark Nimbus.
If you're using nimbus you can try these UIManager codes to customize nimbus look and feel.
UIManager.put("control", new Color(0, 0, 0));
UIManager.put("info", new Color(0, 0, 0));
UIManager.put("nimbusBase", new Color(0, 0, 0));
UIManager.put("nimbusAlertYellow", new Color(248, 187, 0));
UIManager.put("nimbusDisabledText", new Color(255, 255, 255));
UIManager.put("nimbusFocus", new Color(115, 164, 209));
UIManager.put("nimbusGreen", new Color(176, 179, 50));
UIManager.put("nimbusInfoBlue", new Color(66, 139, 221));
UIManager.put("nimbusLightBackground", new Color(0, 0, 0));
UIManager.put("nimbusOrange", new Color(191, 98, 4));
UIManager.put("nimbusRed", new Color(169, 46, 34));
UIManager.put("nimbusSelectedText", new Color(255, 255, 255));
UIManager.put("nimbusSelectionBackground", new Color(18, 134, 175));
UIManager.put("text", new Color(255, 255, 255));

You can try these codes. In my project the nimbus seem as
But I always recommend using "Flatleaf" (Search google "FlatLafLookAndFeel" or go to jar.download.com"). It is a professional and you can change all to your own.


Q: Extracting trees from image without picking up background vegetation? I do not have a background in image recognition/feature extraction, but I am in need of a way to extract trees from an image without the background vegetation.

Seen above is a small example of the kind of imagery I'm working with. I have access to multi-spectral imagery as well (though I haven't seen it yet) including NDVI, NIR, Red-edge.
From researching the problem at hand, I am aware that feature extraction is an active area of research and it seems that often supervised and unsupervised machine learning is employed in combination with statistical voodoo such as "PCA". Being able to differentiate between trees and background vegetation has been noted as an area of difficulty in some papers I skimmed over in my research.
There are notable features about the imagery I am working with. First of all, the palm trees have a very distinctive shape. Not only this, but there are obvious differences in the texture of the trees vs the texture of the background vegetation.
I am not an academic, and as such I only have access to publicly available papers for my research. I am looking for relevant algorithms that could help me extract the features of interest to me (trees) that either have an implementation (ideally in C or bindings to C, though I'm aware that it is not a commonly used language in this field) or with publicly available papers/tutorials/sites/etc. detailing the algorithm so that I could implement it myself.
Thanks in advance for any help!

A: Look into OpenCV, It has a lot of options for supervised/semi supervised Learning methods. As you have mentioned there is a visible texture difference between the tress and background vegetation, a good place for you would be to start would be color based segmentation and evolving it to use textures as well. OpenCV ML tutorial is a good starting point. Moreover you can also combine the NDVI data to create a stronger feature set.


Q: How do I create a #define mapping to the spacebar character in C? I'm looking for the equivalent of this, without the surrounding single quotes:
#define SPACEBAR ' '

How do I do this? For any other character I would use either the character itself or its corresponding escape character. To my knowledge, however, there's no escape character for the spacebar. Is there some sort of hex code I can use? Please help.

A:
Is there some sort of hex code I can use?

The ASCII code for Space is 32 or 0x20. If you want to use SPACEBAR like a constant, you can #define it to be:
#define SPACEBAR 32

or
#define SPACEBAR 0x20

Caveat
The above encoding will work for systems that use ASCII and UTF-8 encoding. For systems that use EBCDIC encoding, the decimal value to encode Space is 64 (Thanks are due to @BasileStarynkevitch for pointing that out).

A: #define SPACEBAR 32

OR
char ch = 0x20

Hope it helps

A: Depending of what you exactly want to do, you may be able to use:
#define SPACEBAR \040

It is the octal value of the space char, like it may appear in a string.


Q: Config multi display in lockscreen I have an Asus VivoBook S532FL, when I boot Kubuntu 20.04, the lock screen shown in screenpad, and the config of the display are wrong, I mean when I move left to right it's move cursor up to the bottom
I fix screenpad problem in Kubuntu environment by config multi display in setting, I can disable screenpad too but it doesn't affect on boot and lockscreen
how can I config multi display for lock screen?

A: Finally by putting following config to /usr/share/sddm/scripts/Xsetup you can turn screen pad off:
#!/bin/sh

# to find display
# xrandr | grep ' connected'

# Xsetup - run as root before the login dialog appears

if [ -e /sbin/prime-offload ]; then
    echo running NVIDIA Prime setup /sbin/prime-offload
    /sbin/prime-offload
fi
xrandr --output HDMI-1 --off
xrandr --output eDP-1 --mode 1920x1080 --pos 0x0 --rotate normal
xrandr --output HDMI-1-1 --off
xrandr --output eDP-1-1 --mode 1920x1080 --pos 0x0 --rotate normal


Q: Google Sheets: Sheets as filtered views of data I'm creating a financial spreadsheet that has an All Transactions sheet, which contains entries from multiple people. I would like to also have have dedicated sheets for each person (John's Transactions, Jane's Transactions), where they can see and edit the categories for their own expenses.
I know I can use a filter to accomplish this but only one filter can be applied at a time.
Is there any way to create a duplicate view of a sheet where I can show a subset of entries, but changes made to one will also change the other?
Here is my example sheet


Q: Switch workspace on dual monitor 22.04 I run Ubuntu 22.04 on a dual monitor setup.
When I switch workspace only my main-monitor is switching. I want both to switch.
On older releases there was and option in gnome-tweaks to turn this feature on.
In my gnome-tweaks there is no workspace-section at all.
Are there any other settings available in 22.04 to make this happen?

A: This setting now made it into the "Settings" tool on the "Multitasking" tab:


Q: How can Excel file and website server interact?
I have a working excel calculator and a website server. My goal is to present the result generated by the calculator on the website. And to feed input received by the website My question is that how should I implement this because excel and website server can not seem to interact directly.
I am looking for some language that the excel can be converted to and the language can also be interactive with a website.
Any help would be appreciated!

A: You can embed excel documents on a website using one drive or google docs.
Sync your doc to your one drive, then embed the doc on the page.


Q: React Native CLI uses autolinking for native dependencies, but the following modules are linked manually I am getting Error while running my project using react-native run-ios

error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:

*

*react-native-document-picker (to unlink run: "react-native unlink react-native-document-picker")

*react-native-fast-image (to unlink run: "react-native unlink react-native-fast-image")

*react-native-image-picker (to unlink run: "react-native unlink react-native-image-picker")

*react-native-maps (to unlink run: "react-native unlink react-native-maps")

*react-native-navigation (to unlink run: "react-native unlink react-native-navigation")

*react-native-permissions (to unlink run: "react-native unlink react-native-permissions")

*react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")

This is likely happening when upgrading React Native from below 0.60 to 0.60 or above. Going forward, you can unlink this dependency via "react-native unlink " and it will be included in your app automatically. If a library isn't compatible with autolinking, disregard this message and notify the library maintainers.
Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
info Found Xcode workspace "JustHelper.xcworkspace"
info Building (using "xcodebuild -workspace JustHelper.xcworkspace -configuration Debug -scheme JustHelper -destination id=BB2D702A-3FF7-4C11-863C-445B97ACFB83 -derivedDataPath build/JustHelper")
..

.. error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code null. To debug build logs further, consider building your app with Xcode.app, by opening JustHelper.xcworkspace***


Q: element implicitly has an 'any' type error in vue 3 app I am trying to use lucidev icons in my component but I am really new in typescript
Here is lucidev: https://github.com/lucide-icons/lucide
<template>
  <component :is="icon" />
</template>

<script lang="ts">
import * as icons from 'lucide-vue-next';
import { defineComponent } from 'vue';

export default defineComponent({
  props: {
    name: {
      type: String,
      required: true,
    },
    size
  },

  computed: {
    icon() {
      return icons[this.name];
    },
  },
});
</script>

But I am getting element implicitly has an 'any' type because expression of type 'string' can't be used to index type in icons[this.name]
How can I fix this?
icons:

A: This error usually means that the icons variable is not the type that you expect it to be.
Often it's because it's an array. In that case, a string can't be used to index the type of the array because a number is needed to do that. e.g. icons[2].
I would try console logging the icons variable and seeing what comes out, from there you can figure out what you need to use to index it :)
I hope this helps!


Q: How to show MQ client list by Java? Is it possible to show all clients of a MQ server (or MQ queue manager, or channel) by Java? Because there are too many connections sometimes and I need to monitor it.
I checked the API of com.ibm.mq.MQQueueManager
(https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_7.5.0/com.ibm.mq.javadoc.doc/WMQJavaClasses/com/ibm/mq/MQQueueManager.html)
I can use it to get queue depth, but I cannot get the client connection information (ex: IP address) of it.
If it's impossible to get IP address, could we get "connection count" only?

A: You need to use MQ PCF via Java.
request = new PCFMessage(CMQCFC.MQCMD_INQUIRE_CHANNEL_STATUS);
request.addParameter(CMQCFC.MQCACH_CHANNEL_NAME, "TEST.CHL");
request.addParameter(CMQCFC.MQIACH_CHANNEL_INSTANCE_TYPE, CMQC.MQOT_CURRENT_CHANNEL);
request.addParameter(CMQCFC.MQIACH_CHANNEL_INSTANCE_ATTRS,
                     new int []
                     {
                        CMQCFC.MQCACH_CHANNEL_NAME,
                        CMQCFC.MQCACH_CONNECTION_NAME,
                        CMQCFC.MQIACH_CHANNEL_STATUS,
                        CMQCFC.MQIACH_CHANNEL_SUBSTATE,
                        CMQCFC.MQIACH_MSGS,
                        CMQCFC.MQCACH_LAST_MSG_DATE,
                        CMQCFC.MQCACH_LAST_MSG_TIME,
                        CMQCFC.MQCACH_CHANNEL_START_DATE,
                        CMQCFC.MQCACH_CHANNEL_START_TIME,
                        CMQCFC.MQIACH_BYTES_SENT,
                        CMQCFC.MQIACH_BYTES_RECEIVED,
                        CMQCFC.MQIACH_BUFFERS_SENT,
                        CMQCFC.MQIACH_BUFFERS_RECEIVED,
                        CMQCFC.MQIACH_MCA_STATUS,
                        CMQCFC.MQCACH_MCA_JOB_NAME,
                        CMQCFC.MQCACH_MCA_USER_ID
                     } );

responses = agent.send(request);


Q: Winsock Отправить пакет клиенту Как отправить из клиента клиенту же данные, чтобы клиент считал их функцией Recv?
Заранее прошу прощения за глупо поставленный вопрос.
Клиент и Сервер обмениваются данными, мне нужно передать данные клиенту якобы от сервера.
A: Recv читает из сокета, появляющегося после connect - по указанному адресу.
Подменить сокет скорее всего не удастся...
Так что проще всего проксировать трафик в вашем случае по моему мнению.


Q: No exception with SqlDataReader.ExecuteReader while SQL Server returns converstion error When I execute the following statement in SQL Server Management Studio
exec sp_executesql N'select 1 where 1 = @p1',N'@p1 nvarchar(3)',@p1=N'a'
go
I get the below error
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value 'a' to data type int.
But when I use ExecuteReader, I don't get any exception
Why?
How can I get and handle this error as exception in app
Imports System.Data.SqlClient
Module Module1
Sub Main()

    Dim TestSqlConnection As SqlConnection = Nothing

    Dim TestSqlCommand As SqlCommand = Nothing

    Dim TestReader As SqlDataReader = Nothing

    Dim TestGetSchemaTable As DataTable = Nothing

    TestSqlConnection = New SqlConnection
    TestSqlConnection.ConnectionString = "Data Source=(local);Database=master;Integrated Security=true"
    TestSqlConnection.Open()
    TestSqlCommand = New SqlCommand()
    TestSqlCommand.Connection = TestSqlConnection
    TestSqlCommand.CommandType = CommandType.Text
    TestSqlCommand.CommandText = "select 1 where 1 = @p1"

    Dim TestSqlParameter As SqlParameter = New SqlParameter
    TestSqlParameter.ParameterName = "@p1"
    TestSqlParameter.SqlDbType = SqlDbType.NVarChar
    TestSqlParameter.Size = 3
    TestSqlParameter.Direction = ParameterDirection.Input
    TestSqlParameter.Value = "a"
    TestSqlCommand.Parameters.Add(TestSqlParameter)

    Try
        TestReader = TestSqlCommand.ExecuteReader()
    Catch ex As Exception
        Console.WriteLine("Exception")
    Finally
        Console.WriteLine("Finally")
    End Try
End Sub

End Module

A: ExecuteReader doesn't actually perform the query.  The first call to .Read() will throw the error.
If you want to only catch the SqlException you can do the following:
Try
    TestReader = TestSqlCommand.ExecuteReader()
    TestReader.Read()
Catch ex As SqlException
    Console.WriteLine("SQL error.")
Catch ex As Exception
    Console.WriteLine("Exception")
Finally
    Console.WriteLine("Finally")
End Try

A: For me this fixes the SSMS
exec sp_executesql N'select 1 where N''a'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'

exec sp_executesql N'select 1 where N''1'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'

I totally disagree with Rene Reader.
On my system it executes on ExecuteReader.
ExecuteReader would be a real bad name if it did not actually execute.
Did you consider that it is not catching and exception because it is not throwing an exception.
I know you see an error in SQL Profiler but if I introduce a syntax error it is caught.
This is C# but is is not throwing an exception for me.
And if I change it to:
"select 1 where N'a' = @p1";
Then it returns a row.
If I introduce a syntax error:
"select 1 whereX 1 = @p1";
Then it does throw an exception and it throws it on the ExecuteReader line.
If you want 1 to be a literal you should use:
"select 1 where '1' = @p1";
SQLcmd.CommandType = CommandType.Text;
SQLcmd.CommandText = "select 1 where N'1' = @p1";
SqlParameter TestSqlParameter = new SqlParameter();
TestSqlParameter.ParameterName = "@p1";
TestSqlParameter.SqlDbType = SqlDbType.NChar;
TestSqlParameter.Value = "a";
SQLcmd.Parameters.Add(TestSqlParameter);
try
{
    rdr = SQLcmd.ExecuteReader();
    Int32 waste;
    if (rdr.HasRows)
    {
        while (rdr.Read())
        {
            waste = rdr.GetInt32(0);
        }
    }
}
catch (Exception Ex)
{
    Debug.WriteLine(Ex.Message);
}

A: I solved this problem if the sql string passed used EXEC sp_executesql by ensuring I read every result and result set... like so:
  ....
        using (var conn = new SqlConnection(_connectionString))
        {
            try
            {
                conn.Open();
                using (var cmd = new SqlCommand(sql, conn))
                {
                    cmd.CommandTimeout = 0;
                    using (var rdr = cmd.ExecuteReader())
                    {

                       // TODO: Do stuff with the rdr here.

                        FlushReader(rdr);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Fatal("Exception: {0}\r\nSQL:\r\n{1}", ex.Message, sql);
                throw;
            }
            finally
            {
                conn.Close();
            }
        }
    ...

    /// <summary>
    /// Continue trying to read in case the server threw an exception.
    /// </summary>
    private static void FlushReader(IDataReader rdr)
    {
        while (rdr.Read())
        {
        }

        while (rdr.NextResult())
        {
            while (rdr.Read())
            {
            }
        }
    }

Without calling the FlushReader method the application continues without throwing an exception of any kind. Even if I use a SQL THROW statement. Running the same sql in SQL management studio will show the error.
Hope this helps.


Q: How to silently provide initial settings for Visual Studio I'm looking for a way to provide initial settings for Visual Studio 2017 through a script. Copying a *.vssettings file to the %USERPROFILE%\Documents\Visual Studio 2017\Settings path doesn't work since Visual Studio will rewrite the file on startup while creating a user profile.
There is the /resetsetting switch vor devenv.exe which can be used to reset the settings to a specified .vssettings file, but this will also open Visual Studio IDE.
Is there a way to silently provide initial settings for Visual Studio from a PowerShell script? Or any safe way to detect at which time Visual Studio has created the profile and imported the settings when using /resetsetting, so that the devenv process can be killed?

A: When using /resetsettings, you could:

*

*Check whether default settings file exists. Get modified date if it does.

*Run devenv.exe /resetsettings <filepath> The modified date on the default settings file will be changed to match the file specified.

*Check modified date has changed, or file now exists.

*Close devenv.exe
I've given this a go; the settings file after step 3 isn't identical to the one specified in /resetsettings, although it's clearly different from the previous default one. I don't know the criteria for which tags are kept.
Related, not a PowerShell solution: A team settings file can be specified by going to Tools > Options > Environment > Import and Export Settings. More info on Enviornment Options.
Note from link: "When applied, these team settings would not override any category not specified in the .vssettings file"


Q: How to compare 2 List objects to get the missing value from the List How do I use the "NOT IN" to get the missing data, to be added to "foo" List.
var accessories = new List<string>();
var foo = new List<string>();

accessories.Add("Engine");
accessories.Add("Tranny");
accessories.Add("Drivetrain");
accessories.Add("Power Window");

foo.Add("Engine");
foo.Add("Tranny");
foo.Add("Power Window");

foreach(var v in foo.Where(x => x??).???)
{
    foo.Add(v);  //Add the missing "Drivetrain" to it...
}

A: You can use .Except() to get the difference between two sets:
var difference = accessories.Except(foo);
// difference is now a collection containing elements in accessories that are not in foo

If you then want to add those items to foo:
foo = foo.Concat(difference).ToList();

A: Use List.Except:
foo.AddRange(accessories.Except(foo));

From MSDN:

Except Produces the set difference of two sequences.

A: There's a LINQ method to do this for you, it looks like this; accessories.Except(foo);

A: You can combine Concat and Distinct to do this:
foo = foo.Concat(accessories).Distinct().ToList();

Edit: Or Except as others have pointed out, which seems to be the superior choice for this case.

A: If you just want foo to be the distinct combination of all elements in foo and accessories (i.e., the union of the two lists),
List<string> foo = foo.Union(accessories).ToList();


Q: Default seeds in Stata I gather from the Stata manual on the RNG seed that the value for the seed is 123456789 every time Stata is launched. My questions are

*

*Was it always this way or was the default seed different in older versions (I'm particularly concerned with version 8)

*Is the default sortseed also 123456789?

A: To answer my own questions:
Going back to at least version 8 the default seed was 123456789 but as Nick Cox points out in comments above this doesn't mean all versions of Stata would produce the same sequence of random numbers based on that seed because the random number generator has changed over time.
The default sortseed seems to be 1001:
. query sortseed
. di r(sortseed)
1001


Q: Application in CloudFoundry is able to access Redis even when Redis service is un-binded from that app I have deployed an application in CloudFoundry with Redis service binded to it. In this app I have autowired StringRedisTemplate and have provided couple of endpoints for inserting, deleting and listing data from Redis.
Now when I am un-binding Redis service from my app , I am still able to perform all the operations to Redis. Whenever a service is un-binded its credentials ( Ip/port/username/password ) will not be there in the environment variables of that app. So my question is how still my app is able to access redis DB when redis service is un-binded from it ?

A: Did you restage the app after un-binding? Changes to bindings don't take affect until after an app has been restaged. You can verify by running cf env app-name and seeing of the VCAP_SERVICES environment variable is still set.


Q: Is there a way to set a score range (or a max score) for a query I have a very simple query :
match: {
  field => {
    boost: 4,
    query: term,
    fuzziness: 'AUTO',
  }
}

Composed with several (about 10) others queries most of them using constant_score. The problem is that on specific terms, my query has a too big score that cancel all others queries results.
Here is a part of the explain :
"details" => [
[0] {
      "value" => 63.656006,
"description" => "sum of:",
    "details" => [
    [0] {
              "value" => 63.656006,
        "description" => "weight(title.de:kandinsky in 1694239) [PerFieldSimilarity], result of:",
            "details" => [
            [0] {
                      "value" => 63.656006,
                "description" => "score(doc=1694239,freq=1.0 = termFreq=1.0\n), product of:",
                    "details" => [
                    [0] {
                              "value" => 4.0,
                        "description" => "boost",
                            "details" => []
                    },
                    [1] {
                              "value" => 11.3820715,
                        "description" => "idf, computed as log(1 + (docCount - docFreq + 0.5) / (docFreq + 0.5)) from:",
[...]

Has you can see, I have a score of 11.38 due to the IDF.
My others queries (with scores between 1 and 3) are totally useless.
My question is :
How can I set a max possible score for a query ?
Or, even better, can I set a range of score for my query ?
I would like to avoid a constant_score query for this field, I need a few TF/IDF and score notion for this field but not that strong.
I tried this :
function_score: {
  query: { match: {
    field => term,
  }},
  score_mode: :avg,
  script_score: {
    script: {
      inline: "4 * (1 + Math.log(2 + _score))",
    }
  },
}

It's better but it can still perform a very high score on certain cases.

A: Finaly I used a function score with a script score using a 1 - (1/x) function in script_score
GET _search
{
  "query": {
    "function_score": {
      "query": {
        "match": {
          "postgresql.log.message": "alter"
        }
      },
      "script_score" : {
                "script" : {
                    "params": {
                        "max_score": 5
                    },
                    "source": "params.max_score * (1 - 1 / _score)"
                }
            }
    }
  }
}

This way, I will have a score between 0 and  nearly 5 (max_score).
You can try it here with the word alter (score 3.9150627) or alter table pgbench_branches add primary key (bid) (score 4.8539715).
You can adapt the 1 - (1/x) function to approach the asymptote faster.

A: have u tried using Function score query ?
 Here is the link for the same
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html


Q: Как получить название файла, в котором находится вызываемая функция? Python Нужно получить название файла, в котором находится вызываемая функция.
Пример:
В файле my_func.py находится функция func, обернутая в декоратор:
from decorator import my_decorator

@my_decorator
def my_func():
   pass

my_func()

В файле decorator.py находится следующий декоратор:
def my_decorator(func):
   def wrapper():
      print(<Тут должно быть название my_func.py>)
      func()
   return wrapper

A: Попробуйте так:
import inspect

def my_decorator(func):
   def wrapper():
      print(inspect.getfile(func))
      func()
   return wrapper

на 2.х работает.

A: def my_decorator(func):
   def wrapper():
      print(func.__module__)
      func()
   return wrapper


Q: Initialize integer value while declaration vb6 How should I initialize variable value during the declaration.
I am using VB6,
I tried
public i as integer = 0
but i got error

Expected: End of statement, and "=" is highlighted

I want to set initial value to 0.
Edit from comments:
I want to create a login form without the help of the database..
Module: So i created a user_name(1 to 10)-- array and password(1 to 10) array
form1 I want to register upto 10 users each time the value of i increments //form// i=1 register_user(i)=uname register_pass(i)=upass i=i+1 //end// but each time I go to that form value is set again to 1 what should I do.

A: In VBA and VB6 you can't initialize variables. You must use an executable statement.
However, each variable does have a default initialization value.
From  the VB6 documentation:

When variables are initialized, a numeric variable is initialized to
  0, a variable-length string is initialized to a zero-length string
  (""), and a fixed-length string is filled with zeros. Variant
  variables are initialized to Empty. Each element of a user-defined
  type variable is initialized as if it were a separate variable.

So actually, in your case,
public i as integer = 0

doesn't work, but the next stement does work, and does just that:
public i as integer

A: I think the issue is that you are attempting to instantiate a public variable at declaration...Dim i As Integer: i = 1 works, but is not public.  You can either do this or declare the public variable then instantiate it in the first line of of the sub.

A: Vacip answered it in terms of setting it to 0 like you asked, but to build on it... If you need a public variable to start as something other than the default value you would set it to that value the first time it is called in a sub.
If you have multiple subs that might call it for the first time and then it gets passed back and forth, you need to check to ensure that it hasn't already been set. you can do that with a public boolean.
If you turn on your locals and step through this you can see one way to do it.
Public iTesti As Integer 'defaults to 0
Public bTesti As Boolean 'defaults to FALSE

Public Sub testi()
If bTesti = False Then 'btesti is false and iteseti is 0
    iTesti = 1
    bTesti = True
End If
iTesti = 2
testi2
End Sub

Public Sub testi2()
If bTesti = False Then 'btesti is true and itesti is 2
    iTesti = 1
    bTesti = True
End If
iTesti = 3
End Sub


Q: Clojure thread-first macro (->) vs thread-last macro (->>) What are the practical differences? I still do not fully understand the difference between the two Clojure arrow macros thread-first -> and thread-last macro ->>.
While reading through https://clojure.org/guides/threading_macros I understand that thread first -> is an alternative expression for nested operations on a single object, each datastep using the object as input argument, performing an independent operation.
(defn transformation [object]
  (transform2 (transform1 object)))

becomes
(defn transformation [object]
  (-> object
      (transform1)      ;; object as implicit argument
      (transform2)))    ;; object as implicit argument

When using threat-last ->> operator, each tranformation uses output of the preceding transformation as implicit argument:
(defn transformation [object]
  (->> object
       (transform1)      ;; object as implicit argument
       (transform2)))    ;; (transform1 object) as implicit argument

What are the practical implicantions of these differences? I understand that it makes sense to use threat -first -> for operations on maps and dictionaries, where each transformation creates a new copy of the original instance, which has to be supplied for the next operation.
However, in many cases, both operators actually behave the same:
(->> [2 5 4 1 3 6] (reverse) (rest) (sort) (count)) ;; => 5
(->  [2 5 4 1 3 6] (reverse) (rest) (sort) (count)) ;; => 5

A: The practical difference is where the macro "inserts" the variable (and the subsequent results) into the expressions:
(ns so.example)

(defn example-1 [s]
  (-> s
      (str "foo")))

(defn example-2 [s]
  (->> s
      (str "foo")))

(example-1 "bar")
;=> "barfoo"

(example-2 "bar")
;=> "foobar"

So (-> "bar" (str "foo")) is the same as (str "bar" "foo") and (->> "bar" (str "foo")) is the same as (str "foo" "bar"). With unary functions -> and ->> do the same thing.
When you need more flexibility as to where these results should be inserted, you would use as->:
(ns so.example)

(defn example-3 [s]
  (as-> s v
      (str "foo" v "foo")))

(example-3 "bar")
;=> "foobarfoo"

A: Following up on as-> as an answer purely because I can't format code in a comment.
Here's a usage of as-> from our codebase at work:
                    (-> date
                        (.getTime)
                        (as-> millis
                          (/ (- (.getTime (java.util.Date.)) millis)
                             1000 60 60 24))
                        (long)
                        (min days))

That computation could be unrolled, and ->> used to place the threaded value at the end of the - expression, but would probably be harder to read. It would also be possible to unroll it in such a way that -> alone would be enough (by negating the threaded value and then adding it to (.getTime (java.util.Date.))) but that would make it even harder to read I think.

A: I think there is a misunderstanding on your part on how -> works.
You say

*

*-> is an alternative expression for nested operations on a single object, each datastep using the object as input argument, performing an independent operation.

and then about ->> you say

*When using threat-last ->> operator, each tranformation uses output of the preceding transformation as implicit argument

but statement 1 is not true, and statement 2 is true for both, -> and ->>.
This is very easy to test, like this:
cljs.user=> (-> [2 5 4 1 3 6] reverse rest)
(3 1 4 5 2)
cljs.user=> (-> [2 5 4 1 3 6] rest reverse)
(6 3 1 4 5)

If you add sort to the end of the call chain, like in your example, you wouldn't notice this difference, because both results would be sorted.
Like cfrik said, when you are passing only one argument to a function, then the first argument and the last argument are the same (because there's just one), so that's why it's easy to get confused when all the functions in your call chain accept only one argument, which is the case with your example where you have used count, sort, rest, and reverse.
Another thing you might have missed from the documentation in https://clojure.org/guides/threading_macros is the fact that many functions that work with sequences, like filter, map, and reduce, take the sequence as the last argument as a convention, and that makes it possible to chain calls to them using ->>, like
(->> (range 10)
     (filter even?)
     (map #(+ 3 %))
     (reduce +))

which becomes
(reduce + (map #(+ 3 %) (filter even? (range 10))))

whereas -> is more suitable for functions like assoc and update, which (like you said) work with single objects and take the object as their first argument (and "transformations/update" on that object as the rest of the arguments), so then you can do the following
(-> person
    (assoc :hair-color :gray)
    (update :age inc))

which becomes
    (update (assoc person :hair-color :gray) :age inc)

To better understand how macros work, try using macroexpand-1, like this
user> (macroexpand-1 '(->> (range 10)
                      (filter even?)
                      (map #(+ 3 %))
                      (reduce +)))
(reduce + (map (fn* [p1__21582#] (+ 3 p1__21582#)) (filter even? (range 10))))

The argument macroexpand-1 should be a quoted version of the function call, and the result will be the expanded function call.


Q: What does tf.nn.embedding_lookup function do? tf.nn.embedding_lookup(params, ids, partition_strategy='mod', name=None)

I cannot understand the duty of this function. Is it like a lookup table? Which means to return the parameters corresponding to each id (in ids)?
For instance, in the skip-gram model if we use tf.nn.embedding_lookup(embeddings, train_inputs), then for each train_input it finds the correspond embedding?

A: When the params tensor is in high dimensions, the ids only refers to top dimension. Maybe it's obvious to most of people but I have to run the following code to understand that:
embeddings = tf.constant([[[1,1],[2,2],[3,3],[4,4]],[[11,11],[12,12],[13,13],[14,14]],
                          [[21,21],[22,22],[23,23],[24,24]]])
ids=tf.constant([0,2,1])
embed = tf.nn.embedding_lookup(embeddings, ids, partition_strategy='div')

with tf.Session() as session:
    result = session.run(embed)
    print (result)

Just trying the 'div' strategy and for one tensor, it makes no difference.
Here is the output:
[[[ 1  1]
  [ 2  2]
  [ 3  3]
  [ 4  4]]

 [[21 21]
  [22 22]
  [23 23]
  [24 24]]

 [[11 11]
  [12 12]
  [13 13]
  [14 14]]]

A: Yes, the purpose of tf.nn.embedding_lookup() function is to perform a lookup in the embedding matrix and return the embeddings (or in simple terms the vector representation) of words.
A simple embedding matrix (of shape: vocabulary_size x embedding_dimension) would look like below. (i.e. each word will be represented by a vector of numbers; hence the name word2vec)

Embedding Matrix
the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862
like 0.36808 0.20834 -0.22319 0.046283 0.20098 0.27515 -0.77127 -0.76804
between 0.7503 0.71623 -0.27033 0.20059 -0.17008 0.68568 -0.061672 -0.054638
did 0.042523 -0.21172 0.044739 -0.19248 0.26224 0.0043991 -0.88195 0.55184
just 0.17698 0.065221 0.28548 -0.4243 0.7499 -0.14892 -0.66786 0.11788
national -1.1105 0.94945 -0.17078 0.93037 -0.2477 -0.70633 -0.8649 -0.56118
day 0.11626 0.53897 -0.39514 -0.26027 0.57706 -0.79198 -0.88374 0.30119
country -0.13531 0.15485 -0.07309 0.034013 -0.054457 -0.20541 -0.60086 -0.22407
under 0.13721 -0.295 -0.05916 -0.59235 0.02301 0.21884 -0.34254 -0.70213
such 0.61012 0.33512 -0.53499 0.36139 -0.39866 0.70627 -0.18699 -0.77246
second -0.29809 0.28069 0.087102 0.54455 0.70003 0.44778 -0.72565 0.62309

I split the above embedding matrix and loaded only the words in vocab which will be our vocabulary and the corresponding vectors in emb array.
vocab = ['the','like','between','did','just','national','day','country','under','such','second']

emb = np.array([[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.044457, -0.49688, -0.17862],
   [0.36808, 0.20834, -0.22319, 0.046283, 0.20098, 0.27515, -0.77127, -0.76804],
   [0.7503, 0.71623, -0.27033, 0.20059, -0.17008, 0.68568, -0.061672, -0.054638],
   [0.042523, -0.21172, 0.044739, -0.19248, 0.26224, 0.0043991, -0.88195, 0.55184],
   [0.17698, 0.065221, 0.28548, -0.4243, 0.7499, -0.14892, -0.66786, 0.11788],
   [-1.1105, 0.94945, -0.17078, 0.93037, -0.2477, -0.70633, -0.8649, -0.56118],
   [0.11626, 0.53897, -0.39514, -0.26027, 0.57706, -0.79198, -0.88374, 0.30119],
   [-0.13531, 0.15485, -0.07309, 0.034013, -0.054457, -0.20541, -0.60086, -0.22407],
   [ 0.13721, -0.295, -0.05916, -0.59235, 0.02301, 0.21884, -0.34254, -0.70213],
   [ 0.61012, 0.33512, -0.53499, 0.36139, -0.39866, 0.70627, -0.18699, -0.77246 ],
   [ -0.29809, 0.28069, 0.087102, 0.54455, 0.70003, 0.44778, -0.72565, 0.62309 ]])

emb.shape
# (11, 8)

Embedding Lookup in TensorFlow
Now we will see how can we perform embedding lookup for some arbitrary input sentence.
In [54]: from collections import OrderedDict

# embedding as TF tensor (for now constant; could be tf.Variable() during training)
In [55]: tf_embedding = tf.constant(emb, dtype=tf.float32)

# input for which we need the embedding
In [56]: input_str = "like the country"

# build index based on our `vocabulary`
In [57]: word_to_idx = OrderedDict({w:vocab.index(w) for w in input_str.split() if w in vocab})

# lookup in embedding matrix & return the vectors for the input words
In [58]: tf.nn.embedding_lookup(tf_embedding, list(word_to_idx.values())).eval()
Out[58]:
array([[ 0.36807999,  0.20834   , -0.22318999,  0.046283  ,  0.20097999,
         0.27515   , -0.77126998, -0.76804   ],
       [ 0.41800001,  0.24968   , -0.41242   ,  0.1217    ,  0.34527001,
        -0.044457  , -0.49687999, -0.17862   ],
       [-0.13530999,  0.15485001, -0.07309   ,  0.034013  , -0.054457  ,
        -0.20541   , -0.60086   , -0.22407   ]], dtype=float32)

Observe how we got the embeddings from our original embedding matrix (with words) using the indices of words in our vocabulary.
Usually, such an embedding lookup is performed by the first layer (called Embedding layer) which then passes these embeddings to RNN/LSTM/GRU layers for further processing.

Side Note: Usually the vocabulary will also have a special unk token. So, if a token from our input sentence is not present in our vocabulary, then the index corresponding to unk will be looked up in the embedding matrix.

P.S. Note that embedding_dimension is a hyperparameter that one has to tune for their application but popular models like Word2Vec and GloVe uses 300 dimension vector for representing each word.
Bonus Reading word2vec skip-gram model

A: Another way to look at it is , assume that you flatten out the tensors to one dimensional array, and then you are performing a lookup
(eg) Tensor0=[1,2,3], Tensor1=[4,5,6], Tensor2=[7,8,9]
The flattened out tensor will be as follows
[1,4,7,2,5,8,3,6,9]
Now when you do a lookup of [0,3,4,1,7] it will yeild [1,2,5,4,6]
(i,e) if lookup value is 7 for example , and we have 3 tensors (or a tensor with 3 rows) then,
7 / 3 : (Reminder is 1, Quotient is 2) So 2nd element of Tensor1 will be shown, which is 6

A: Since I was also intrigued by this function, I'll give my two cents.
The way I see it in the 2D case is just as a matrix multiplication (it's easy to generalize to other dimensions).
Consider a vocabulary with N symbols.
Then, you can represent a symbol x as a vector of dimensions Nx1, one-hot-encoded.
But you want a representation of this symbol not as a vector of Nx1, but as one with dimensions Mx1, called y.
So, to transform x into y, you can use and embedding matrix E, with dimensions MxN:
y = E x.
This is essentially what tf.nn.embedding_lookup(params, ids, ...) is doing, with the nuance that ids are just one number that represents the position of the 1 in the one-hot-encoded vector x.

A: Yes, this function is hard to understand, until you get the point.
In its simplest form, it is similar to tf.gather. It returns the elements of params according to the indexes specified by ids.
For example (assuming you are inside tf.InteractiveSession())
params = tf.constant([10,20,30,40])
ids = tf.constant([0,1,2,3])
print tf.nn.embedding_lookup(params,ids).eval()

would return [10 20 30 40], because the first element (index 0) of params is 10, the second element of params (index 1) is 20, etc.
Similarly,
params = tf.constant([10,20,30,40])
ids = tf.constant([1,1,3])
print tf.nn.embedding_lookup(params,ids).eval()

would return [20 20 40].
But embedding_lookup is more than that. The params argument can be a list of tensors, rather than a single tensor.
params1 = tf.constant([1,2])
params2 = tf.constant([10,20])
ids = tf.constant([2,0,2,1,2,3])
result = tf.nn.embedding_lookup([params1, params2], ids)

In such a case, the indexes, specified in ids, correspond to elements of tensors according to a partition strategy, where the default partition strategy is 'mod'.
In the 'mod' strategy, index 0 corresponds to the first element of the first tensor in the list. Index 1 corresponds to the first element of the second tensor. Index 2 corresponds to the first element of the third tensor, and so on. Simply index i corresponds to the first element of the (i+1)th tensor , for all the indexes 0..(n-1), assuming params is a list of n tensors.
Now, index n cannot correspond to tensor n+1, because the list params contains only n tensors. So index n corresponds to the second element of the first tensor. Similarly, index n+1 corresponds to the second element of the second tensor, etc.
So, in the code
params1 = tf.constant([1,2])
params2 = tf.constant([10,20])
ids = tf.constant([2,0,2,1,2,3])
result = tf.nn.embedding_lookup([params1, params2], ids)

index 0 corresponds to the first element of the first tensor: 1
index 1 corresponds to the first element of the second tensor: 10
index 2 corresponds to the second element of the first tensor: 2
index 3 corresponds to the second element of the second tensor: 20
Thus, the result would be:
[ 2  1  2 10  2 20]

A: Here's an image depicting the process of embedding lookup.

Concisely, it gets the corresponding rows of a embedding layer, specified by a list of IDs and provide that as a tensor. It is achieved through the following process.

*

*Define a placeholder lookup_ids = tf.placeholder([10])

*Define a embedding layer embeddings = tf.Variable([100,10],...)

*Define the tensorflow operation embed_lookup = tf.embedding_lookup(embeddings, lookup_ids)

*Get the results by running lookup = session.run(embed_lookup, feed_dict={lookup_ids:[95,4,14]})

A: embedding_lookup function retrieves rows of the params tensor. The behavior is similar to using indexing with arrays in numpy. E.g.
matrix = np.random.random([1024, 64])  # 64-dimensional embeddings
ids = np.array([0, 5, 17, 33])
print matrix[ids]  # prints a matrix of shape [4, 64]

params argument can be also a list of tensors in which case the ids will be distributed among the tensors. For example, given a list of 3 tensors [2, 64], the default behavior is that they will represent ids: [0, 3], [1, 4], [2, 5].
partition_strategy controls the way how the ids are distributed among the list. The partitioning is useful for larger scale problems when the matrix might be too large to keep in one piece.

A: Adding to Asher Stern's answer,
 params is
  interpreted as a partitioning of a large embedding tensor. It can be a  single tensor representing the complete embedding tensor,
      or a list of X tensors all of same shape except for the first dimension,
      representing sharded embedding tensors.
The function tf.nn.embedding_lookup is written considering the fact that embedding (params) will be large. Therefore we need partition_strategy.

A: The existing explanations are not enough.
The main purpose of this function is to efficiently retrieve the vectors for each word in a given sequence of word indices. Suppose we have the following matrix of embeddings:
embds = np.array([[0.2, 0.32,0.9],
        [0.8, 0.62,0.19],
        [0.0, -0.22,-1.9],
        [1.2, 2.32,6.0],
        [0.11, 0.10,5.9]])

Let's say we have the following sequences of word indices:
data=[[0,1],
     [3,4]]

Now to get the corresponding embedding for each word in our data:
tf.nn.embedding_lookup(
    embds, data
)

out:
array([[[0.2 , 0.32, 0.9 ],
        [0.8 , 0.62, 0.19]],

       [[1.2 , 2.32, 6.  ],
        [0.11, 0.1 , 5.9 ]]])>

Note If embds are not an array or tensor, the output will not be like this (I won't go into details). For example, if embds were a list, the output would be:
array([[0.2 , 0.32],
       [0.8 , 0.62]], dtype=float32)>


Q: RUSAGE_SELF returns memory usage in bytes? I am still not very clear about the unit of RUSAGE_SELF after going through the documentation of Python resource.
What actually RUSAGE_SELF returns? Memory usage of the whole program in bytes?
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

What exactly is the unit?

A: Sometimes CPython documentation needs to be used in conjunction with the C documentation, since CPython builds on C.  In this case, you might find what you need in http://linux.die.net/man/2/getrusage - or perhaps the getrusage doc for some other *ix variant.
HTH


Q: task scheduler not working for python win32 I am running the following Python code from jupyter and powershell and it is running flawlessly.
When I put this in window scheduler, it doesn't run. It doesn't show any error either. Could you please help solve the problem? Are there better options to schedule my Python code in window?
I am running python 3.10.
My code was running before:
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'dsrigyan@yahoo.com'
mail.Subject = 'data'
# mail.Body = 'data'
mail.HTMLBody = '''

    Hi Deepa,

    Please find the data for yesterday.

    Let me know if you has any questions.

                    Deepankar Srigyan

                    BI & Analytics Manager

            '''

attachment  = attachment_file
mail.Attachments.Add(attachment)

mail.Send()

A: See creating a bat file for python script to understand how to launch your script with a .bat file, then launch that via windows scheduler rather than launching the python script directly.


Q: Permutation induced by multiplication of finite field elements Consider a finite field $\mathbb F$. Let $a \in \mathbb F$. Then multiplication by $a$ induces a permutation on the field elements. $0 \rightarrow 0$, $1 \rightarrow a$, $2 \rightarrow 2a$, etc.
Is there any easy way to determine whether this permutation is even or odd?
Suppose $\mathbb F$ is simply the finite field with $p$ elements, where $p$ is prime. Then the answer to this question defines a function of $a$ and $p$, $f(a,p)=\pm 1$. Does $f(a,p)$ have a simple number theoretic interpretation?
Sorry if this is an obvious question.


Q: CSS Ordering Convention for which tags to specify first I typically place the rules in my CSS in the same order as they are in the HTML. But what about global rules like how I format my input,textarea,p,tr,th and stuff like that? Is there a convention on which order the rules should go in?
Obviously there are situations when the rules have to be in a certain order to work.

A: I just put "global" properties of CSS in their own stylesheet all together. So for instance: put in tr, td, input, table, etc in their own stylesheet and the rest of custom .classes and #divs in their own.
This simplifies it the best and keeps it organized.

A: Global CSS rules can go on a file (i.e. global-style.css) - these will apply to all pages.
Specific CSS rules can go a separate file (i.e. login-style.css) - on this second file, you can override the default look-feel of the global CSS if desired.
You would only include the second file in the HTML files you need the different look-feel (from the global one)

A: I use one line per rule notation now, try to keep it organized and easy to read. It minimizes scrolling and it is easier to sort the rules that way.


Q: Chrome not animating until css are loaded In my head I include very small css file for loading animation. I am downloading large Angular2 application, and I want to display loading.
What I experience is that animation does not start until all css are loaded from server.
<link rel="stylesheet" href="~/dist/load.css" />
<link rel="stylesheet" href="~/dist/vendor.css" />

I tried to load vendor.css with async, defer, async defer. Tried to place it before </body> tag. I even try to replace animation with gif. Same thing, gif is displayed when vendor.css is loaded.
In network tab in Developer tools I choose Slow 3G. The moment that vendor.css file is loaded animation starts.
If I remove vendor.css from html animation starts immediately.
How can I start animation before other css file is loaded?

A: I found solution in placing this code before </body> tag:
<script type="text/javascript">
   const head = document.head, link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = "/dist/vendor.css";
    head.appendChild(link);
</script>

But it does not explain Chrome (possible other browsers too) behaviour I described in question.


Q: Best way to update a list of structs Let's say that I have a list of structs, with an id as one of its keys:
users = [
  %User{id: 1, attempts: 5},
  %User{id: 2, attempts: 12},
  %User{id: 3, attempts: 2}
]

What would the best way (the most elixir way) to update the number of attempts to 99 of the user with id == 2 to get a new users list:
updated_users = [
  %User{id: 1, attempts: 5},
  %User{id: 2, attempts: 99},
  %User{id: 3, attempts: 2}
]

Thanks for helping!

A: Enum.map(users, fn
  %User{id: 2} = user -> %User{user | attempts: 99}
  user -> user
end)

You can encapsulate it into some module and give it nice name :)

A: Arguably, most elixirish approach would be to use Access behaviour and Kernel.put_in/3:
put_in users,
  [Access.filter(&match?(%User{id: 2}, &1)),
   Access.key(:attempts)],
  99
#⇒ [
#  %User{attempts: 5, id: 1},
#  %User{attempts: 99, id: 2},
#  %User{attempts: 2, id: 3}
#]

This might be easily extended to update multiple elements by changing the filter function.

A: If you are doing many updates, it's probably best to build a map, so that you don't have to iterate the list for each update.
[
  %User{attempts: 5, id: 1},
  %User{attempts: 12, id: 2},
  %User{attempts: 2, id: 3}
]
|> Map.new(fn user -> {user.id, user} end)
|> Map.update!(2, &%User{&1 | attempts: 99})
|> Map.values()

You can do as many Map.update!/3 calls as you need, to update different ids.


Q: Background image not displaying in JLabel/JFrame in Java game I am making a java game and at it's heart, it consists of a JFrame that holds a a JLabel that holds the background image. Early in the project this was being displayed. However, after I implemented a Game render method that put healthbars and a character on screen, the background image no longer displays. Here is the Game's render() and main() methods.
public class Game extends Canvas implements Runnable{
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 1200, HEIGHT = 600, SCALE = 1;
    public static boolean running = false;
    public Thread gameThread;

    private BufferedImage playerSpriteSheet;
    private ImageManager im;

    private static Player player;
    private static HealthBar healthBars;

    public void init(){
        ImageLoader loader = new ImageLoader();
        playerSpriteSheet = loader.load("/spriteSheet.png");
        SpriteSheet pss = new SpriteSheet(playerSpriteSheet);

        im = new ImageManager(pss);

        player = new Player(0, 0, im);
        healthBars = new HealthBar(200, 200);

        this.addKeyListener(new KeyManager());
    }

    public synchronized void start() {
        if(running)return;
        running = true;
        gameThread = new Thread(this);
        gameThread.start();
    }

    public synchronized void stop() {
        if(!running)return;
        running = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run() {
        init();
        long lastTime = System.nanoTime();
        final double amountOfTicks = 60D;
        double ns = 1_000_000_000/amountOfTicks;
        double delta = 0;
        long now = System.nanoTime();

        while(running)
        {
            delta += (now - lastTime)/ns;
            lastTime = now;
            if(delta >= 1)
            {
                tick();
                delta--;
            }
            render();
        }
        stop();
    }

    public void tick() {
        player.tick();
    }

    public void render() {

        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null)
        {
            createBufferStrategy(3); //Use 5 at most
            return;
        }
        Graphics g = bs.getDrawGraphics();

        //RENDER HERE
        player.render(g);
        healthBars.render(g);

        //END RENDER
        g.dispose();
        bs.show();
    }

    public static void main(String[] args)
    {
        JLabel backgroundImage;
        JLabel controlKeyPanel;
        JLabel statusLabel;

        Game game = new Game();
        game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
        game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
        game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

        JFrame frame = new JFrame("Java Game");
        frame.setResizable(false);
        frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
        frame.setLayout(new BorderLayout());

        backgroundImage = new JLabel(new ImageIcon("/background.png"));

        String htmlButtonGuide = "&#8592   -   Move Left
&#8594   -   Move Right
A  -  Attack
S  -  Fire Gun
P  -  Position
esc -   Exit";
        controlKeyPanel = new JLabel(htmlButtonGuide);

        statusLabel = new JLabel("Game Status");

        frame.add(backgroundImage, BorderLayout.CENTER); //This should be displaying the background image
        frame.add(controlKeyPanel, BorderLayout.EAST);
        frame.add(statusLabel, BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(game);

        frame.setVisible(true);

        game.start();
    }

    public static Player getPlayer() {
        return player;
    }

}

Here is the catch, and where I think part of the issue is visible. Inside the render() method there are these 2 lines:
player.render(g);
healthBars.render(g);

If I put player.render(g) first, then both the player and health bars appear on the screen. However, if I put healthBars.render(g) before player.render(g), then the player doesn't appear. This really confuses me, because I would expect the one that renders second causes the first one to be hidden behind, but the opposite happens. Could anyone point me in the right direction?

A: *

*BufferStrategy doesn't play well with Swing, as you've taken control of the painting process

*Canvas can't be transparent, so it will hide anything beneath it...

*When you use frame.add(game) you are replaceing what ever use to be at BorderLayout.CENTER
Instead of mixing lightweight (Swing) and heavy weight (AWT) components, paint the background image as part of your render process
public void render() {

    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null)
    {
        createBufferStrategy(3); //Use 5 at most
        return;
    }
    Graphics g = bs.getDrawGraphics();

    //RENDER HERE
    // Paint background here...
    player.render(g);
    healthBars.render(g);

    //END RENDER
    g.dispose();
    bs.show();
}


Q: Android UI issue after update the ConstraintLayout to 1.1.0 After updating the ConstraintLayout to 1.1.0 the layout is showing white background only.its working fine in constraint-layout:1.0.2'.Please check my XML.In constraint-layout:1.0.2' it show the result. in 1.1.0 is  showing only the outline card view only.plese refer my XML for more details.I want to  update my ConstraintLayout

  Please check image

    -->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mCardviewPropertytype"
    android:layout_width="160dp"
    tools:background="@color/gray_black"
    android:layout_height="180dp"
    android:layout_margin="8dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="2dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="160dp"
        android:layout_height="180dp"
        android:layout_gravity="center"
        android:layout_margin="8dp">

        <android.support.constraint.ConstraintLayout
            android:id="@+id/ImgPropertySelect"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@drawable/half_circle"
            app:layout_constraintRight_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                tools:visibility="visible"
                android:layout_marginLeft="10dp"
                android:layout_marginBottom="10dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_centerInParent="true"
                app:srcCompat="@drawable/ic_done_white_" />

        </android.support.constraint.ConstraintLayout>

        <!-- <ImageView
             android:id="@+id/ImgPropertySelect"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:src="@drawable/selection_curve"
             app:layout_constraintRight_toLeftOf="parent"
             app:layout_constraintTop_toTopOf="parent" />-->

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.5" />

        <ImageView
            tools:visibility="visible"
            android:id="@+id/imageViewPropertyType"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@drawable/residential_villa_img"
            android:layout_marginLeft="16dp"
            app:layout_constraintBottom_toTopOf="@+id/guideline"
            app:layout_constraintLeft_toRightOf="parent"
           />

        <TextView
            tools:text="@string/nearResidentialArea"
            android:id="@+id/textViewTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:text="TextView"
            android:textColor="@color/gray_black"
            android:textSize="20dp"
            app:layout_constraintLeft_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/guideline" />
  </android.support.constraint.ConstraintLayout>
   </android.support.v7.widget.CardView>

A: The question is why the layout worked under 1.0.2 at all. What you see under 1.1.0 is how the layout is really defined. There are a couple of constraints that moved the images and text out of the layout and produced the blank area that you see. I made the corrections to the following XML and all looks OK. (I changed the colors and drawables used since I didn't have ready access to what you used, but you can change them back easily enough.)
<android.support.v7.widget.CardView
    android:id="@+id/mCardviewPropertytype"
    android:layout_width="160dp"
    tools:background="@android:color/darker_gray"
    android:layout_height="180dp"
    android:layout_margin="8dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="2dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="160dp"
        android:layout_height="180dp"
        android:layout_gravity="center"
        android:layout_margin="8dp">

        <android.support.constraint.ConstraintLayout
            android:id="@+id/ImgPropertySelect"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@mipmap/ic_launcher"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                tools:visibility="visible"
                android:layout_marginLeft="10dp"
                android:layout_marginBottom="10dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_centerInParent="true"
                app:srcCompat="@mipmap/ic_launcher" />

        </android.support.constraint.ConstraintLayout>

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.5" />

        <ImageView
            tools:visibility="visible"
            android:id="@+id/imageViewPropertyType"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@mipmap/ic_launcher"
            android:layout_marginLeft="16dp"
            app:layout_constraintBottom_toTopOf="@+id/guideline"
            app:layout_constraintLeft_toLeftOf="parent"
            />

        <TextView
            tools:text="Near residential area"
            android:id="@+id/textViewTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:text="TextView"
            android:textColor="@android:color/darker_gray"
            android:textSize="20dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/guideline" />
    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>

A: Use this
app:cardBackgroundColor="@color/gray_black"

Instead of
tools:background="@color/gray_black"

Also
Use android:text="@string/nearResidentialArea"
instead of tools:text="@string/nearResidentialArea"


Q: Given a covarince matrix, generate a Gaussian random variable Given a $M \times  M$ desired covariance, $R$, and a desired number of sample vectors, $N$ calculate a $N \times M$ Gaussian random vector, $X$.
Not really sure what to do here. You can calculate the joint pdf given a mean, $\mu$, and covariance. So for $2 \times 2$ covariance matrix is defined as:
$$ \text{Cov}[X] = \begin{bmatrix}\text{Cov}(X_1) & \text{Cov}(X_1,X_2) \\ \text{Cov}(X_2,X_1) & \text{Cov}(X_2)\end{bmatrix} $$
But not sure how to get the mean from that.

A: To generate one vector $u\in\mathcal{R}^M$, first of all generate any vector $v$ from $\mathcal{N}(0,I)$ (or M independent normally distributed variables with mean $0$, varaince $1$).
We now need to get a matrix $L$ such that $LL^T=R$, easiest way is a cholesky decomposition. Now $u=Lv\sim\mathcal{N}(0,R)$


Q: Concentration in Gauss space This is a theorem called Concentration in Gauss space. Let $f$ be a real valued Lipschitz function on $\mathbb {R}^{n}$ with Lipschitz constant $K$, i.e. $\left|f(x)-f(y)\right|\leq K\|x-y\|_{2}$ for all $x,y\in \mathbb {R}^{n}$ (such functions are also called K-Lipschitz). Let $X$ be the standard normal random vector in $\mathbb {R}^{n}$. Then for every $t\geq 0$ one has
\begin{align*}
    \mathbb {P}\left\{f(X)-\mathbb {E}f(X)>t\right\}\leq \text{exp}(-t^{2}/2K^{2}).
\end{align*}
We have
\begin{align*}
\mathbb {P}\left\{f(X)-\mathbb {E}f(X)>t\right\}=\mathbb {P}\left\{e^{\lambda(f(x)-\mathbb {E}f(x))}>e^{\lambda t}\right\}\leq \mathbb {E}e^{\lambda(f(x)-\mathbb {E}f(x))}/e^{\lambda t}
\end{align*}
I wonder how to continue from here. Or maybe just inform me where to find the proof. Thanks a lot.


Q: Expression performance of overload operator?
*

*(i++) and (i = i + 1)

*(i += n) and (i = i + n)
which is better (performance)?

A: It doesn't matter
The compiler will convert statements like that to (what it thinks, and often is) their most efficient form.
I'd recommend you write statements like this in the same way as the rest of your code base in order to keep consistency.
If you are just doing your own thing on a personal project you can either do what you prefer or what is common for your particular language.

A: It does not matter, the performance is the same. In 1978 when C was invented these would map to different PDP-11 instructions, resulting in faster performance of ++ and +=. These days, however, the operations are optimized into the same exact sequences of instructions.


Q: How to properly apply filter for the query presented? I have a table as under
declare @t table(bucket bigint null)

insert into @t select 1 union all select 2 union all select -1 union all select 5

Now let me write the below query (filter by Bucket 0  - All values are coming)
declare @Bucket bigint = 0 –filter by 0

select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)

Result
1
2
-1
5

But if I filter Bucket by 2 or any other value, I get the results properly
declare @Bucket bigint = 2 –filter by 2
select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)

Result
2

If I filter by null or blank I get proper result
declare @Bucket bigint = '' –filter by ''

select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)

Result
1
2
-1
5

Why this behavior for bucket 0? And how to solve?

A: You can try to use @Bucket bigint = NULL for @Bucket default value.

because NULL mean unknow

or you can set a value which should not in bucket column be the default value.
declare @Bucket bigint = NULL

select *
from @t
where (@Bucket is Null or bucket = @Bucket)

NOTE
but If @Bucket bigint is bigint it should not be ''

Edit
CREATE TABLE T(
   Bucket bigint
);

declare @Bucket bigint = 0

INSERT INTO T VALUES (1);
INSERT INTO T VALUES (2);
INSERT INTO T VALUES (-1);
INSERT INTO T VALUES (5);
INSERT INTO T VALUES (0);

select * from T
where  (@Bucket is Null or (@Bucket ='' and @Bucket <> 0)  or bucket=@Bucket)

A: FIXED
declare @t table(bucket bigint);

INSERT INTO @t VALUES (1);
INSERT INTO @t VALUES (2);
INSERT INTO @t VALUES (-1);
INSERT INTO @t VALUES (5);
INSERT INTO @t VALUES (0);

declare @Bucket bigint = 0 --filter by 0

select * from @t
where 1=1
AND (@Bucket is Null or cast(@Bucket as nvarchar) = '' or bucket=@Bucket)


Q: Switching threads multiple times in Rx chain Let's assume I have a following case for Android:

*

*Request list of groups from network

*Show some UI elements for each group

*Request items for each group

*Show UI elemets for
each item

I want to do this using RxJava:
webService.requestGroups()
        .flatMap(group -> {
            view.showGroup(group);
            return webService.requestItems(group);
        })
        .toList()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())

        .subscribe(items -> view.showItems(items));

As you can see I have 2 calls for view objects, each of them must be executed on main thread. And 2 calls for webService, which must be executed on background thread.
The problem with this code: first call to view will be executed on background which cause an Android RuntimeException (Only original thread may touch views or something) If I transfer .observeOn to the beginning of chain - second webService call will be executed in main thread.
How can I "swim" through threads multiple times in RxJava chain?

A: From the Rx doc for SubscribeOn:

The SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called. ObserveOn, on the other hand, affects the thread that the Observable will use below where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate.

The SubscribeOn operator can only be applied once and sets the starting thread. ObserveOn can be used to go from one thread to another at any point in the stream. So I think the following should do what you want:
webService.requestGroups()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .flatMap(group -> {
        view.showGroup(group);
        return webService.requestItems(group)
                         .subscribeOn(Schedulers.io());
    })
    .toList()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(items -> view.showItems(items));

But in my opinion this is too complicated. I would just subscribe to the first observable, and then start a new chain for each group, like this:
webService.requestGroups()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(group -> {
        view.showGroup(group);
        webService.requestItems(group)
            .subscribeOn(Schedulers.io()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(items -> view.showItems(items));
    });

A: Building on Samuel's answer, you could do it with an even simpler, non-nested syntax:
webService.requestGroups()
.subscribeOn(Schedulers.io()) // the first operator (requestGroups) on the IO thread
.observeOn(AndroidSchedulers.mainThread()) //everything below on the main thread
.map(group -> {
    view.showGroup(group);
    return group;
})
.observeOn(Schedulers.io()) //everything below on the IO thread
.flatMap(group -> {
    return webService.requestItems(group);
})
.toList()
.observeOn(AndroidSchedulers.mainThread()) //everything below on the main thread
.subscribe(items -> view.showItems(items));

Two rules of thumb here:

*

*subscribeOn dictates on which thread the observable will begin executing, its placement in the chain is irrelevant and it should appear only once.

*observeOn tells on which thread all subsequent operators will execute (until another observeOn is encountered); it may appear multiple times in the chain, changing execution thread of different code pieces (like in the example above).


Q: Android ClickableSpan not calling onClick I am creating a ClickableSpan, and it is displaying properly with
the proper text underlined. However, the clicks are not registering.
Do you know what I am doing wrong???
Thanks, Victor
Here is the code snippet:
view.setText("This is a test");
ClickableSpan span = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
        log("Clicked");
    }
};
view.getText().setSpan(span, 0, view.getText().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

A: After some trial and error, the sequence of setting the tv.setMovementMethod(LinkMovementMethod.getInstance()); does matter.
Here's my full code
String stringTerms = getString(R.string.sign_up_terms);
Spannable spannable = new SpannableString(stringTerms);
int indexTermsStart = stringTerms.indexOf("Terms");
int indexTermsEnd = indexTermsStart + 18;
spannable.setSpan(new UnderlineSpan(), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ClickableSpan() {
    @Override
    public void onClick(View widget) {
        Log.d(TAG, "TODO onClick.. Terms and Condition");
    }
}, indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

int indexPolicyStart = stringTerms.indexOf("Privacy");
int indexPolicyEnd = indexPolicyStart + 14;
spannable.setSpan(new UnderlineSpan(), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ClickableSpan() {
    @Override
    public void onClick(View widget) {
        Log.d(TAG, "TODO onClick.. Privacy Policy");
    }
}, indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView textViewTerms = (TextView) findViewById(R.id.sign_up_terms_text);
textViewTerms.setText(spannable);
textViewTerms.setClickable(true);
textViewTerms.setMovementMethod(LinkMovementMethod.getInstance());

A: Direct Approach in Kotlin
  val  textHeadingSpannable = SpannableString(resources.getString(R.string.travel_agent))

           val clickSpan = object : ClickableSpan(){
               override fun onClick(widget: View) {

                // Handel your click
               }
           }
            textHeadingSpannable.setSpan(clickSpan,104,136,Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

            tv_contact_us_inquire_travel_agent.movementMethod = LinkMovementMethod.getInstance()
            tv_contact_us_inquire_travel_agent.text = textHeadingSpannable

A: Have you tried setting the MovementMethod on the TextView that contains the span? You need to do that to make the clicking work...
tv.setMovementMethod(LinkMovementMethod.getInstance());

A: Kotlin util function:
fun setClickable(textView: TextView, subString: String, handler: () -> Unit, drawUnderline: Boolean = false) {
    val text = textView.text
    val start = text.indexOf(subString)
    val end = start + subString.length

    val span = SpannableString(text)
    span.setSpan(ClickHandler(handler, drawUnderline), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

    textView.linksClickable = true
    textView.isClickable = true
    textView.movementMethod = LinkMovementMethod.getInstance()

    textView.text = span
}

class ClickHandler(
        private val handler: () -> Unit,
        private val drawUnderline: Boolean
) : ClickableSpan() {
    override fun onClick(widget: View?) {
        handler()
    }

    override fun updateDrawState(ds: TextPaint?) {
        if (drawUnderline) {
            super.updateDrawState(ds)
        } else {
            ds?.isUnderlineText = false
        }
    }
}

Usage:
Utils.setClickable(textView, subString, {handleClick()})


Q: c# EF Model has foreign key to another model Consider the following two models:
public class Category
{
  public int Id {get;set;}
  public string Name {get;set;}
  public int Type {get; set;}
  ..other properties
}

public class Person
{
  public int PersonId {get; set;}
  public string Name {get; set;}
  public int CategoryId {get; set;}
  [ForeignKey["CategoryId"])
  public virtual Category Category {get; set;}
}

I have a repository class that carries out something like the following to get all Person thats have a category of a particular type:
var result = repo.FindBy<Person>(p=>p.Category.Type == 1).ToList()

My repository method as requested by Ivan:
 public IQueryable<T> FindBy<T>(Expression<Func<T, bool>> filter) where T : class
    {

            return _context.Set<T>().Where(filter).AsQueryable();
    }

I get an "Object Not set to" error on the .Type property because I believe it is not linking the two models. I believe this is because the foreign keys do not match (is it using Reflection?).
I am not able to rename Category.Id to Category.CategoryId in the database.
Is there anything i can do on either models to be able to link the Category whenever I select from the Person table by setting a data annotation on either property?


Q: Is there a chance that street and zipcode data wasn't enough to populate full address I have a form where I ask the user to input their mailing address. Would there be any issues with asking only street address and zipcode and omitting city and state?
User zipcode in conjunction with zipcode database would result in having full address of the user. Would that be reliable considering that zipcode database is accurate?

A: I wouldn't do that.

*

*A ZIP code can contain two different towns, each with a "#123 Main Street" address.

*A ZIP code may cross state lines, which means you don't have enough information for shipping/tax details.

*You'll have a very hard time dealing with any customers who live outside of the USA.

A: Marcin,
There is not a one to one relationship between city and zipcode.  A city can have multiple zipcodes.  A zipcode can cross city lines.
Brian