text:
Q: Question(s) Regarding the Lindhard Function As a theoretical chemist, I'm slightly outside of my element on a project my advisor gave me, so I come to your for help and direction.
Basically, he wants me to integrate the imaginary part of the Lindhard Function (over both q and omega). He says that doing so will give me the exchange energy of the uniform electron gas. He keeps telling me that Dirac wrote this down somewhere but I can't seem to find any evidence of that.
Furthermore, whenever I try to do this integral, I get infinity. I've used Vignale and Giuliani as a reference for the formula, as well as Mahan. Each book reports the integrand differently, the former opting for the use of step functions, whereas the latter just breaks up the integrand for various values of omega and q. Both give me the same issue.
Also, I'm wondering what the difference is between a response function and a dielectric function. Both phrases are thrown around a lot and I can't make heads or tails of how they are related.


text:
Q: How to configure Apache Cordova with OData? I'll develop an application with Apache cordova but I don't know much about this. To start, I have to do this. I will use OData as the protocol. With the Apache cordova mobile application, I want to write data somewhere(sqlite, mongodb etc.) and print the data I wrote on the screen.
Is there any document or video I can use on this subject? Can you help me?
Thank you.

A: As Apache Cordova is just a tool to bundle web applications into native applications you wont need a special tutorial for Cordova. You can just follow instructions how to work with OData in general web applications.

redpajama_set_name: RedPajamaStackExchange


text:
Q: google script add link in UI text I have a google script designed to create a PDF. I have it set on completion to provide a pop up showing the location of the file.
> ui.alert('Quote made check folder https://drive.google.com/drive/folders/......')

However this is just text and not a clickable link, could someone please guide me on how to make this a clickable link.
Thanks in advance.

A: this could work for you:

function onEdit(e) {
var htmlApp = HtmlService
     .createHtmlOutput('Quote made check folder LINK')
     .setTitle('My HtmlService Application')
     .setWidth(250)
     .setHeight(80);

 SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);

}


text:
Q: How to fix "static assertion failed: template argument not an integral type" error? I want to generate any number between 0 and max value of given type(T). There is no problem with generating numbers for int, short, long, etc, but i cannot do this for float and double. I get this error: "static assertion failed: template argument not an integral type".My code:
#include <iostream>
#include <limits>
#include <random>

template<class T>
T questGenerator()
{
    std::random_device rd;
    std::default_random_engine generator(rd());
    std::uniform_int_distribution<T> distribution(0, std::numeric_limits<T>::max());

    return distribution(generator);
}

int main()
{
    std::cout << questGenerator<float>();
}

This is an input and output example that I was given: input:
std::cout << generateQuest<short>() << std::endl;
std::cout << generateQuest<short>() << std::endl;
std::cout << (short)generateQuest<char>() << std::endl;
std::cout << (short)generateQuest<char>() << std::endl;
std::cout << generateQuest<float>() << std::endl;
std::cout << generateQuest<float>() << std::endl;

output:
10105
5332
52
110
3.39889e+38
2.7026e+38

A: It is undefined behaviour to use std::uniform_int_distribution<T> for any T different than: short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long.
You might want to consider std::uniform_real_distribution<T>.
Additionally, it's generally a bad idea to have multiple generators per thread. You'd be better of sticking to using a reference to a single one.


text:
Q: Hudson plugin warning I see the message in hudson console
WARNING: Faild to load hudson.plugins.groovy.GroovyTokenMacro
java.lang.HoClassDefFoundError:    org/jenkinsci/plugin/tokenmacro/DataBoundTokenMacro .....

I have re downloaded  .hdi file and got same warning. I am not sure that it was before.
How can I solve it? My hudson is in unsecured mode.
Thanks!


text:
Q: How to add a separator to a listBox from code AND cast it to not selectable
This is what I do and it works:
 if (condition...)
 {
   ComboBoxItem cbi2 = new ComboBoxItem();
   cbi2.Content = new TextBox() { Background= Brushes.Red, HorizontalAlignment= HorizontalAlignment.Stretch, Margin=new Thickness(0) , Height = 5, IsHitTestVisible=false, BorderBrush=null};
   ibw.cmbOptions.Items.Add(cbi2);
 }

the only problem is that the textBox despite not being IsHitTestVisible is selectable and that is a problem. So I'm open also to totally different solution. The only constraint is to act from code.

A: I can see 2 options here:
First, simply use the Separator element:
ibw.cmbOptions.Items.Add(new Separator());

Or, you could disable the ComboBoxItem, which would make it non-selectable for the ComboBox.
ComboBoxItem cbi2 = new ComboBoxItem();
cbi2.IsEnabled = false;
cbi2.Content = new TextBox() { Background= Brushes.Red, HorizontalAlignment= HorizontalAlignment.Stretch, Margin=new Thickness(0) , Height = 5, IsHitTestVisible=false, BorderBrush=null};
ibw.cmbOptions.Items.Add(cbi2);


text:
Q: Detecting most frequently recurring symbol from ASCII-characters on C How do I write an implementation for a function that takes as input a sequence of ASCII-characters, and gives the most frequently recurring symbol? I need make it on C, Where my bad?
  char mostFrequentCharacter(char* str, int size);

 char value;
 int valueCount = 0;
 for (int i =0; i < strlen(str); i++)
 {
       char oneChar = str[i];
       var totalCount = source.Split(oneChar).Length - 1;;
      if (totalCount >= valueCount)
      {
       valueCount = totalCount;
       value = oneChar;
      }
 }
  return value;

The function to be optimized to run on a device with a dual-core ARM-based processors and infinite amount of memory.

A: If the memory is not an issue as you noted, then you shoud create lookup table where you will store number of occurences for each character. Since input is sequence of ASCII characters, size of the structure should be 256. After checking input and initializing lookup table, in the main for loop, increment number of occurences in the corresponding place in the lookup table, check if the number of occurences exceeded the current maximal count, if so, update current maximal count and current most frequent character. In the end, just return most frequent character. Time complexity of this solution is O(N) and space complexity O(1).
char mostFrequentCharacter(char* str, int size) {
    char mosfFrequent;
    int counts[256], i, maxCount = 0;

    // in the case of invalid input, return some invalid character
    if(!str || size < 1)
        return '\0';

    for(i = 0; i < 256; i++)
        counts[i] = 0;

    for (i = 0; i < size; i++)
    {
        counts[str[i]]++;

        if(counts[str[i]] > maxCount) {
            maxCount = counts[str[i]];
            mostFrequent = str[i];
        }
    }
    return mostFrequent;
}

A: Here is an algorithm outline:

*

*Declare a 256 element array of integers (pick your size), zero it.

*Loop over the string:
2a.   Use each char as index into your array and increment element.
2b.   If incremented element is largest so far record index.

All done in one pass over the string. Storage 256 * size of integer bytes, but you have "infinite memory" and that's minuscule in comparison ;-)


text:
Q: Запустить Open Cover UI Доброго времени суток. Скачал OpenCoverUI
При запуске проекта на VS2015 вылезла ошибка

Проект, создающий библиотеку классов, не может быть непосредственно запущен.
  Для отладки данного проекта добавьте к решению проект, создающий приложение и ссылающийся на эту библиотеку, и сделайте его запускаемым.

Это я ещё запускал от имени администратора.
До этого была ошибка

Не удаётся начать отладку, так как отсутствует объект отладки "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe". Перестройте проект и попробуйте ещё раз, или установите свойства OutputPath и AssemblyName так, чтобы они указывали на правильное расположение целевой сборки.

Подскажите, пожалуйста, как запустить решение.


text:
Q: Multiple left joins and combining equals and not equals in Linq I'm trying to join two DataTables so that the first table is LEFT-joined to the second table twice on the CustID column.  The first plant table must match the PlantID from the animal table and the second plant table in the join must NOT match the PlantID from the animal table.  However when I try this in Linq, it seems to ignore the where clause altogether.
Animals:
ID | CustID | PlantID
=====================
1  |   1    | <null>
2  |   2    |    1
3  |   2    | <null>

Plants:
ID | CustID | Name
==================
 1 |    2   |  b1
 2 |    2   |  b2

In SQL the query I want would be:
SELECT    a.id, a.custid, p1.id AS PlantID1, p2.id AS PlantID2
FROM      animals a
LEFT JOIN plants p1 on a.custid = p1.custid AND a.plantid = p1.id
LEFT JOIN plants p2 on a.custid = p2.custid AND a.plantid != p2.id

Here is my code when trying it with linq to dataset:
        DataTable animals = new DataTable();
        animals.Columns.Add("id", typeof(int));
        animals.Columns.Add("custid", typeof(int));
        animals.Columns.Add("plantid", typeof(int));
        animals.Rows.Add(1, 1, DBNull.Value);
        animals.Rows.Add(2, 2, 1);
        animals.Rows.Add(3, 2, DBNull.Value);

        DataTable plants = new DataTable();
        plants.Columns.Add("id", typeof(int));
        plants.Columns.Add("custid", typeof(int));
        plants.Columns.Add("name", typeof(string));
        plants.Rows.Add(1, 2, "b1");
        plants.Rows.Add(2, 2, "b2");

        var test = from al in animals.AsEnumerable()
                   join bl in plants.AsEnumerable()
                   on new { x = al["custid"], y = al["plantid"] } equals new { x = bl["custid"], y = bl["id"] } into gj
                   join bl2 in plants.AsEnumerable()
                   on al["custid"] equals bl2["custid"] into gj2
                   from subbl in gj.DefaultIfEmpty()
                   from subbl2 in gj2.DefaultIfEmpty()
                   select new
                   {
                       aid = al["id"],
                       custid = al["custid"],
                       plantid1 = subbl == null ? DBNull.Value : subbl["id"],
                       plantName = subbl == null ? DBNull.Value : subbl["name"],
                       plantid2 = subbl2 == null ? DBNull.Value : subbl2["id"],
                       plantName2 = subbl2 == null ? DBNull.Value : subbl2["name"]
                   };
        var result = test.Where(st => st.plantid1 != st.plantid2).Cast<object>().ToList();

The result I get includes the following row, which I thought would be excluded by the Where clause:
aid | custid | plantid1 | plantid2
==================================
 1  |   1    |
 2  |   2    |    1     |   1
 2  |   2    |    1     |   2
 2  |   2    |          |   1
 2  |   2    |          |   2

When I try it with linq to objects, the second row isn't present, which I expect.  Here is my code using objects:
    class animal
    {
        public int id, custid;
        public int? plantid;
    }
    class plant
    {
        public int id;
        public int custid;
        public string name;
    }
    List<object> testStructs()
    {
        List<animal> animals = new List<animal>()
        {
            new animal() { id = 1, custid = 1, plantid = 0 },
            new animal() { id = 2, custid = 2, plantid = 1 },
            new animal() { id = 3, custid = 2 }
        };
        List<plant> plants = new List<plant>()
        {
            new plant() { id = 1, custid = 2, name = "col1" },
            new plant() { id = 2, custid = 2, name = "col2" }
        };
        var test = from al in animals.AsEnumerable()
                   join bl in plants.AsEnumerable()
                   on new { x = al.custid, y = al.plantid } equals new { x = bl.custid, y = (int?)bl.id } into gj
                   join bl2 in plants.AsEnumerable()
                   on al.custid equals bl2.custid into gj2
                   from subbl in gj.DefaultIfEmpty()
                   from subbl2 in gj2.DefaultIfEmpty()
                   select new
                   {
                       aid = al.id,
                       custid = al.custid,
                       plantid1 = subbl == null ? null : (int?)subbl.id,
                       plantName = subbl == null ? string.Empty : subbl.name,
                       plantid2 = subbl2 == null ? null : (int?)subbl2.id,
                       plantName2 = subbl2 == null ? string.Empty : subbl2.name
                   };

        return test.Where(st => st.plantid1 != st.plantid2 || st.plantid1 == null || st.plantid2 == null).Cast<object>().ToList();
    }

A: I worked out what I was doing wrong.  My where clause is comparing fields of an anonymous type, which are compared by reference.  The where clause should be
Where(st => !st.plantid1.Equals(st.plantid2))

to compare the values of those fields.


text:
Q: Failure delivering result ResultInfo{who=null, request=0, result=0, data=Intent { }} to activity java.lang.NullPointerException Here is my code i m writing for opening gallery and camera in my application . App crashes when back btutton is pressed without setting
image. Suggest me solutions to it.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == RESULT_OK) {
            if (data != null) {

                // this is image view where you want to setimage
                bmp = (Bitmap) data.getExtras().get("data");

                ivKidsProfilePicture.setImageBitmap(bmp);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bmp.compress(CompressFormat.JPEG, 100, baos);
                childpic = baos.toByteArray();

                Log.d("camera ---- > ", "" + data.getExtras().get("data"));
            }
            masterDatabaseAdapter.insertProfilePicture(childpic);

        }

        else {
            Uri selectedImage = data.getData();

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            if (bmp != null && !bmp.isRecycled()) {

                bmp = null;

            }

            bmp = BitmapFactory.decodeFile(filePath);
            ivKidsProfilePicture.setBackgroundResource(0);
            ivKidsProfilePicture.setImageBitmap(bmp);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(CompressFormat.JPEG, 100, baos);
            childpic = baos.toByteArray();

        }
        masterDatabaseAdapter.insertProfilePicture(childpic);
    }


text:
Q: How to solve ChunkLoadError: Loading hot update chunk second_app failed in webpack 5? while setup a new project for development, the app is not hot reloading. The app consists of multiple apps separated in its different folders.Currently, there are 2 apps html_nodes_prototype and second_app in src/apps folder. Each app consist of index.html, style.css and main.js when I visit the link     http://localhost:8080/second_app/second_app.html, the app shows but If I change something in src/apps/second_app/main.js. It doesn't hot reload, I've to manually reload to get changes. I've set up a webpack-dev-server. Error prompts in the console. I couldn't figure out what's wrong with the config file.
Error in console
[HMR] Update failed: ChunkLoadError: Loading hot update chunk second_app failed.
(missing: http://localhost:8080/second_app.5b0047c2bf2b48c8a084.hot-update.js)
    at http://localhost:8080/second_app/second_app.bundle.js:987:26
    at new Promise (<anonymous>)
    at loadUpdateChunk (http://localhost:8080/second_app/second_app.bundle.js:982:20)
    at http://localhost:8080/second_app/second_app.bundle.js:1411:29
    at Array.forEach (<anonymous>)
    at Object.__webpack_require__.hmrC.jsonp (http://localhost:8080/second_app/second_app.bundle.js:1406:22)
    at http://localhost:8080/second_app/second_app.bundle.js:819:45
    at Array.reduce (<anonymous>)
    at http://localhost:8080/second_app/second_app.bundle.js:815:53

paths.js
const path = require("path");

module.exports = {
  // Source files
  src: path.resolve(__dirname, "../src"),

  // Production build files
  build: path.resolve(__dirname, "../dist"),

  // public path
  public: path.resolve(__dirname, "../public/"),
};

webpack.dev.js
const common = require("./webpack.common");
var HtmlWebpackPlugin = require("html-webpack-plugin");
const merge = require("webpack-merge").merge;
const paths = require("./paths");

module.exports = merge(common, {
  mode: "development",

  output: {
    filename: "[name]/[name].bundle.js",
    path: paths.build,
  },

  module: {
    rules: [
      { test: /\.scss$/, use: ["style-loader", "css-loader", "sass-loader"] },
      { test: /\.css$/, use: ["style-loader", "css-loader"] },
    ],
  },

  devServer: {
    historyApiFallback: true,
    // contentBase: paths.build,
    open: true,
    compress: true,
    hot: true,
    port: 8080,
  },

  plugins: [
    new HtmlWebpackPlugin({
      filename: "html_nodes_prototype/html_nodes_prototype.html",
      title: "HTML Nodes",
      template: "src/apps/html_nodes_prototype/index.html",
      chunks: ["html_nodes_prototype", "vendor"],
    }),
    new HtmlWebpackPlugin({
      filename: "second_app/second_app.html",
      title: "Second app",
      hot: true,
      template: "src/apps/second_app/index.html",
      chunks: ["second_app", "vendor"],
    }),
  ],
});

webpack.common.js
const paths = require("./paths");

module.exports = {
  mode: "development",

  entry: {
    html_nodes_prototype: paths.src + "/apps/html_nodes_prototype/main.js",
    second_app: paths.src + "/apps/second_app/main.js",
    vendor: paths.src + "/apps/_vendor/vendor.js",
  },

  module: {
    rules: [{ test: /\.m?js$/, use: ["babel-loader"] }],
  },
};

A: Adding runtimeChunk: 'single' to webpack.dev.js works for me. Found the answer here
module.exports = {
    ...,
    optimization: {
        runtimeChunk: 'single'
    },
    ...
}


text:
Q: Find a specific directory on Apache server I have access to the server in question. I know the name of the directory I'm looking for on the server, but don't know the full path to it.
Is there a way for me to retrieve the full file path to the directory by using the the directory name?
Edit: I don't have shell access.

A: if you have shell access you can use find like the following
find / -type d -name DIRECTORYNAME

where / is the search starting point and replace DIRECTORYNAME obviously, also try man 1 find for more information.

A: You can use locate command
locate DirectoryName
Its format is something like this
locate [option] [search-pattern]
Note: In the command below, the option --basename or -b tells locate to only match the file (directory) basename (which is exactly pkg) but not the path (/path/to/pkg). Where \ is a globbing character, it disables the implicit replacement of pkg by pkg.
locate --basename '\pkg'


text:
Q: What are the differences between "less" and "more"? As I understand it, less is more + the ability to scroll up. Is it correct? Is there any reason to use more instead of less? Are there any significant differences I'm missing out?

A: less is a full-screen application that gives you a searchable, scrollable window and clears the screen after you exit, less can also be backgrounded and restored like other full screen terminal applications.  less also has a command to open the currently viewed file in your default editor.
more just prints the text as is, stopping for page breaks, and does not clear the screen, it can be backgrounded but it doesn't clear the screen.  more also only reads in the file as it displays where less may read the file into memory first.  each handles line wrapping differently which gives different results when selecting and pasting text.
both tools fulfill the same function but they do it in different ways, so you can pick whichever one you want for the situation at hand.

A: From my less(1):

DESCRIPTION
Less  is a program similar to more
  (1), but which allows backward
  movement in the file as well as
  forward movement.  Also, less does not
  have to read the entire input file
  before starting, so with large input
  files it starts up faster than text
  editors like vi (1).
[...]
COMPATIBILITY WITH MORE
If the environment variable
  LESS_IS_MORE is set to 1, or if the
  program is invoked via a file link
  named "more", less behaves (mostly) in
  conformance with the POSIX "more"
  command specification.

If you check, you may find that on your system, less is in fact precisely more, with compatibility as described above:
$ shasum $(which less) $(which more)
268084f9ca3528888f01010b1f4f49100177f553  /usr/bin/less
268084f9ca3528888f01010b1f4f49100177f553  /usr/bin/more


text:
Q: A bug about PrecisionModel in NTS(C#)? I use PrecisionModel in NTS(C#) to specify a fixed decimal place (i.e. 0.1, 0.01, 0.001 ... ) for Coordinates in a Geometry.
I tried three fixed decimal place : 0.1, 0.01, 0.001 for the same LineString. But the precision of 0.1 always got error when I do some union operations, while 0.01 and 0.001 works well.
The source code are as follows:
//Obviously, the precision of the line and the point is is 0.1
var lineStr = "LINESTRING (1667.8 1368.6, 1741.1 4274.5, 1902.5 578, 1902.5 578.1, 1867.6 1377.3, 1667.8 1368.6)";
var ptStr = "POINT (1741.1 4274.5)";

//scale is 1000d, which means 0.001 precision
var f3 = new GeometryFactory(new PrecisionModel(1000d));
var wktReader3 = new WKTReader(f3);

//scale is 100d, which means 0.01
var f2 = new GeometryFactory(new PrecisionModel(100d));
var wktReader2 = new WKTReader(f2);

//scale is 10d, which means 0.1
var f1 = new GeometryFactory(new PrecisionModel(10d));
var wktReader1 = new WKTReader(f1);

//wkt strings to geometry objects
var line3 = wktReader3.Read(lineStr);
var pt3 = wktReader3.Read(ptStr);

var line2 = wktReader2.Read(lineStr);
var pt2 = wktReader2.Read(ptStr);

var line1 = wktReader1.Read(lineStr);
var pt1 = wktReader1.Read(ptStr);

var lines3 = line3.Union(pt3);
//result: MULTILINESTRING ((1667.8 1368.6, 1741.1 4274.5, 1869.307 1338.211),
//(1869.307 1338.211, 1902.5 578, 1902.5 578.1, 1869.307 1338.211),
//(1869.307 1338.211, 1867.6 1377.3, 1667.8 1368.6))

var lines2 = line2.Union(pt2);
//result: MULTILINESTRING ((1667.8 1368.6, 1741.1 4274.5, 1869.31 1338.21),
//(1869.31 1338.21, 1902.5 578, 1902.5 578.1, 1869.31 1338.21),
//(1869.31 1338.21, 1867.6 1377.3, 1667.8 1368.6))

var lines1 = line1.Union(pt1);
//result: NetTopologySuite.Geometries.TopologyException:
//"found non-noded intersection between LINESTRING(1741.1 4274.5, 1869.3 1338.2)
//and LINESTRING(1867.6 1377.3, 1667.8 1368.6) [ (1867.59289230568, 1377.2996905058, NaN) ]"

Obviously, the decimal place of the initial lineStr is 0.1, so I think specifying 0.1 for the PrecisionModel is enough, and I really hope the accuracy of the result is also in 0.1, otherwise I have to do some rounding operations.
Is it a correct way to use PrecisionModel?
Thanks for your help.


text:
Q: SImple XML Framework: XPath matching based on attribute value Given XML like this:
...
<Sport SportId="1">
    <Name language="en">Soccer</Name>
    <Name language="fi">Jalkapallo</Name>
     ...
</Sport>
...

How can I, using the Simple XML Framework, read the two values into fields in a Java class? (The <Sport> element is already correctly mapped to the corresponding class.)
public class Sport {
    ...
    String nameEn;
    String nameFi;
    ...
}

I've tried approaches like:
@Element(name = "Name")
@Path("Name[@language='en']")
String nameEn;

But the parsing fails with:
Exception in thread "main" org.simpleframework.xml.core.PathException:
  Invalid index for path '[@language='en']' in field 'nameEn'

Also, omitting @Element like this:
@Path("Name[@language='en']")
String nameEn;

...parsing doesn't crash, but nameEn value stays null.
I'd like the matching to be based on the language attribute (instead of ordering), but I'm wondering if that's possible (maybe XPath support in Simple Framework is limited?).

A: Have you tried getting the text of the element explicitly? i.e. Name[@language='en']/text()
Your Xpath is selecting the element, not the text of the element, which can cause some XML engines to choke.


text:
Q: TFS 2013 on windows server 2012 R2 and Analysis Services error: TF400069 I have two machines: one is the host and the other is the Hyper-v VM. Both have Windows Server 2012 R2 installed.
I installed the domain controller and SQL Server 2012 SP1 with CU7 and SharePoint 2010 on the host. I installed SharePoint 2013 on the VM, and I want to install TFS 2013 in Advanced Configuration (I logged in as Administrator to VM Machine). It seemed to work, but when I click on the Test button in the Analysis Services Section the Wizard gave me this error:

TF400069: You must install either SQL Server Analysis Services version
  11.0 or the SQL Server Client Tools on the application tier to ensure that the Analysis Services object model is present for warehouse
  processing.  Once you have installed the necessary components, rerun
  the readiness checks.

I installed both Analysis Services and Client Tools, and Analysis Services works just fine. And I can Access it via Management Studio and change its properties. I also Disabled the Firewall on both Machines.
I googled and find nothing related. What else can I try?

A: In next paragraph of my question just after the error message i mentioned that i installed both Analysis Services and Client Tools, but what i didn't mentioned was i didn't install neither of them on VM Machine which is my TFS on it.
So i think we all get it now and that is i should have installed one of Analysis Services or Client Tools on the VM Machine where my TFS 2013 going to Configure.


text:
Q: Old timer's luck vs Newcomer's work Once in a while I stumble on some question or answer with HUGE amount of upvotes (thousands for a question and multiple hundreds for an answer).
Here is the perfect example:
How to modify existing, unpushed commit messages?
What I found that most of such questions/answers are:

*

*Quite old (dating back to 2008, 2009, sometimes to 2010)

*Very often these super high voted answers could be googled in 10 seconds in some other resources (meaning that both the question and the answer aren't THAT valuable).

Another thing which I found that there are users (Old timer's) who answered literally one such question 5 years ago. And these users can get more reputation each week doing nothing than a newcomer (like me) answering couple of questions each several days.
So, I decided to investigate a little bit and wrote a query which calculates a ratio of Total reputation / number of posts (Answers + Questions). Here is it:
https://data.stackexchange.com/stackoverflow/revision/96666/115919/old-timers-luck
It's interesting to see how people got into 5k+ with 1 contribution to SO and there are even people with 10k+ (admin rights) with just 10 questions/answers.
Generally speaking, I have nothing against old reputation. However, a person doing nothing for 5 years and still beating me in daily reputation - kind of pisses me off :)
I just want to hear your opinion on this thing. Especially, it would be interesting to hear from other members who become active recently (I understand that for an admin with 30k reputation and thousands of answered questions it's not that big deal that somebody got 7k reputation from one answer).
P.S. 8 years passed since this post. I am old timer now and I can sit and accumulate points (and badges) without doing anything, while some new comers are fighting to get their first 1000 points. On top of that I stopped contributing to SO probably 4 years ago.

A: My two most upvoted answers both took about five minutes to write.
Many answers that I spent ages on didn't get any rep at all - no upvotes, no acceptance. However, while the rep from the simple answers is great, I've gained a lot in thinking about how to answer the question.
In other words, if all you're getting out of StackOverflow is rep points, it's a waste of time - they're worthless. There's much more value to be had here.

A: It's really no different than stock options in a startup company.

*

*In a startup, the earlier you are there, the bigger portion of the company shares you get;

*On Stack Overflow, the earlier you were here to snatch up all the common questions, the more passive rep you get in the long run.

Yes there's an effort imbalance. It was never entirely fair in real-life. And it definitely isn't entirely fair on Stack Overflow.
You are right that old users have a huge advantage in this rep-game. You basically learn to live with it. Try not to sweat too much about that number.

That said, the game isn't over for us.
Programming and (computers in general) is a fast changing field. Things get outdated very quickly and new things come in. If you stick around long enough, you may get lucky enough to snatch the next "common question" for the next technology.
Then you will be able to sit back and enjoy passive rep just like many of the old-timers before us.
Newcomers like us also have one advantage over the old-timers: we have much less to fear about the deletion of many highly-voted posts now that the rules have more or less stabilized.

A:
Very often these super high voted answers could be googled in 10 seconds in some other resources (meaning that both the question and the answer aren't THAT valuable).

Stack Overflow is a beast in Google results, that's probably how the questions/answers got so many upvotes - because they turned up after a search and were useful. Sure they may be basic, but it doesn't mean they aren't valuable.

Generally speaking, I have nothing against old reputation. However, a person doing nothing for 5 years and still beating me in daily reputation - kind of pisses me off :)

Keep contributing, and you'll one day become an "old-timer" yourself and be gaining rep every  day for doing nothing.
Don't think of Stack Overflow as a competition, think of it  as a collaboration.

A: What counts are not the points but the road that you walk to reach them.
I would like to tell you that I have seen some users here that started after me and beat me, passed me and they are higher ranked than me, and they deserve it. They have given more help, more answers, and they worked a lot to help the community.
Second, the reputation is one metric, but there are more, like the many answers you have given, like the tags, the badges, the present on top of some language that you may be, and maybe you are in top 20 of some kind of language.
And now the question, what you do after your reputation reaches 30k with only ten questions?
I can tell you what you do before it reaches 30k with 2000 answers: you help people by giving answers, learning from other questions and improving your software too. Be part of a community that allows you to test your skills and your know how.
This is the road that I am talking about, this road that improves you as programmer, is not the numbers, is not the reputation, is not if you new or old.

A: I don't think you need to worry. If somebody gains moderator powers despite answering only a couple of ancient questions, they are hardly likely to be a major influence on the site. I think it's telling that the top of your list hasn't been seen since Feb 2010.
Anyway, StackExchange lets you measure your reputation per quarter. Perhaps that's a number you can take more pride in? That certainly can't be "cheated".

A: I think a decay function would be good. Not a fast one, perhaps an exponential decay one like e^(-x/5), which yields observable decays in a contributor's rep after 1.5-2.0 years or so.
This way, old, experienced contributors would be stimulated to keep on contributing to answers and questions as well, not just moderating.
Unfortunately, it may be well the case that the users who are in the position of deciding to do this are also the ones which would be negatively influenced by such a decision, so they won't want to lose their advantage over the others.
Oh well, that's how it works in real life too.
On the other hand, such a mechanism would encourage new users too, who would be less intimidated by such high reps.
e^(-x/5) is not that much, actually. A question/answer would decrease by approx. 0.8 in one year, and it could only be applied to questions or answers over a threshold, not to every contribution.

A: This topic has been discussed quite a few times, which can be seen by linked questions here and on Meta Stack Overflow as well. One thing isn't mentioned yet (as far as I can tell) and I can't really post it at the question which has been marked as the original question for this one: Diminishing returns / non-linear reputation from "great" answers, so here is my observation:
Back in 2008, we didn't have Hot Network Questions. We do have them now and they cause a lot of reputation gain across the network for new posts, up to the point that users complain about other users getting reputation (or at least privileges) faster than is good for the community. The effect is probably not that great for Stack Overflow (which has a net outflow of Hot Network Questions traffic and is even penalized for appearing on the list) but it is for sites like Worldbuilding and Role-Playing Games.
I'm not saying that this makes life fair; good old questions and answers will still be more rewarding, but at the very least it makes life a little bit fairer for new posts.


text:
Q: $a>b$, then prove $a^b > b^a$ Let $a > b$ be fractions of the form $\frac{x}{y}$ with $x < y,\  x,y \in \mathbb{N}\setminus\{0\}$. Take as an example $a=\frac{1}{2}, b = \frac{2}{5}$.
Prove that $a^b > b^a$.
Thanks
Good weekends
Charlie

A: For $a,b>0$ it is $a^b>b^a\iff b\ln{a}>a\ln{b}\iff \dfrac{\ln{a}}{a}>\dfrac{\ln{b}}{b}$
You have to study the function $f(x)=\dfrac{\ln{x}}{x}$
EDIT
$f$ is continous and its derivative is $f'(x)=\dfrac{\frac{1}{x}x-\ln{x}}{x^2}=\dfrac{1-\ln{x}}{x^2}$ so $f$ is increasing in $(0,e)$ and decreasing in $(e,+\infty)$
So if $a<b\in (0,e) $ then $f(a)<f(b)$
if $a<b\in (e,+\infty)$ then $f(a)>f(b)$


text:
Q: Galerkin method + FEM - clarification for Poisson equation with mixed boundary conditions I will be refering to this link, but I am interested in slightly easier equation:
$$
-\Delta c = f, \quad (x, y) \in \Omega
$$
with the following (mixed) boundary condition:
$$
\begin{aligned}
1. & \; c = g_1, \quad (x, y) \in \Gamma_1 \\
2. & \; \frac{\partial c}{\partial n} = g_2, \quad (x, y) \in \Gamma_2 \\
3. & \; \sigma c + \frac{\partial c}{\partial n} = g_3, \quad (x, y) \in \Gamma_3
\end{aligned} \quad \quad \Gamma = \Gamma_1 \, \cup \; \Gamma_2 \, \cup \; \Gamma_3
$$
To my understanding the derivation goes like this:
First, we multiply both sides of the equation by some test function $v$ and integrate over $\Omega$
$$
\int \limits_\Omega \left( -\Delta c \right) v \, \mathrm{d} \Omega = \int \limits_\Omega f v \, \mathrm{d} \Omega
$$
Then we use per partes + Gauss thm to obtain
$$
\int \limits_\Omega \left( \vec{\nabla} c \right) \cdot \left( \vec{\nabla} v \right) \, \mathrm{d} \Omega - \int \limits_\Gamma \frac{\partial c}{\partial n} v \: \mathrm{d} \Gamma = \int \limits_\Omega f v \, \mathrm{d} \Omega
$$
Now we divide integral over $\Gamma$ to three parts
$$
\int \limits_\Omega \left( \vec{\nabla} c \right) \cdot \left( \vec{\nabla} v \right) \, \mathrm{d} \Omega - \int \limits_{\Gamma_1} \frac{\partial c}{\partial n} v \: \mathrm{d} \Gamma - \int \limits_{\Gamma_2} \frac{\partial c}{\partial n} v \: \mathrm{d} \Gamma - \int \limits_{\Gamma_3} \frac{\partial c}{\partial n} v \: \mathrm{d} \Gamma = \int \limits_\Omega f v \, \mathrm{d} \Omega
$$
The first integral over $\Gamma_1$ obtains $c$ with essential BC, so we require $v = 0$ on $\Gamma_1$ and this integral will drop out. In the second one, Neumann BC can be directly substituted from (2.) and in the third one, Robin BC can be substituted from (3.):
$$
\int \limits_\Omega \left( \vec{\nabla} c \right) \cdot \left( \vec{\nabla} v \right) \, \mathrm{d} \Omega - \int \limits_{\Gamma_2} g_2 v \: \mathrm{d} \Gamma - \int \limits_{\Gamma_3} ( g_3 - \sigma c ) \, v \: \mathrm{d} \Gamma = \int \limits_\Omega f v \, \mathrm{d} \Omega
$$
This is just cosmetic; we separate terms with $c$ and without $c$
$$
\int \limits_\Omega \left( \vec{\nabla} c \right) \cdot \left( \vec{\nabla} v \right) \, \mathrm{d} \Omega + \int \limits_{\Gamma_3} \sigma c \, v \: \mathrm{d} \Gamma = \int \limits_\Omega f v \, \mathrm{d} \Omega + \int \limits_{\Gamma_2} g_2 v \: \mathrm{d} \Gamma + \int \limits_{\Gamma_3} g_3 v \: \mathrm{d} \Gamma
$$
Now we expand the solution $c$ to piecewise (linear, quadratic, ...) basis functions:
$$
c(x,y) = \sum_i c_i \lambda_i (x, y) + c_0 (x, y)
$$
$c_0$ is there to satisfy the essential (Dirichlet) BC:
$$
\begin{aligned}
1. & \; c0 = g_1, \quad (x, y) \in \Gamma_1 \\
2. & \; \lambda_i = 0, \quad (x, y) \in \Gamma_1
\end{aligned}
$$
To work out coefficients $c_i$ we take $v = \lambda_i$ (test functions are basis functions themselves):
$$
\int \limits_\Omega \left( \vec{\nabla} \left( \sum_j c_j \lambda_j + c_0\right) \right) \cdot \left( \vec{\nabla} \lambda_i \right) \, \mathrm{d} \Omega + \int \limits_{\Gamma_3} \sigma \left( \sum_j c_j \lambda_j + c_0 \right) \, \lambda_i \: \mathrm{d} \Gamma =\\= \int \limits_\Omega f \lambda_i \, \mathrm{d} \Omega + \int \limits_{\Gamma_2} g_2 \lambda_i \: \mathrm{d} \Gamma + \int \limits_{\Gamma_3} g_3 \lambda_i \: \mathrm{d} \Gamma
$$
$$
\sum_j c_j \left[ \int \limits_\Omega \left( \vec{\nabla} \lambda_j \right) \cdot \left( \vec{\nabla} \lambda_i \right) \, \mathrm{d} \Omega + \int \limits_{\Gamma_3} \sigma \lambda_j \, \lambda_i \: \mathrm{d} \Gamma \right] = \int \limits_\Omega f \, \lambda_i \, \mathrm{d} \Omega + \int \limits_{\Gamma_2} g_2 \, \lambda_i \: \mathrm{d} \Gamma + \int \limits_{\Gamma_3} g_3 \lambda_i \, \mathrm{d} \Gamma - \\- \int \limits_\Omega \left( \vec{\nabla} c_0 \right) \cdot \left( \vec{\nabla} \lambda_i \right) \, \mathrm{d} \Omega - \int \limits_{\Gamma_3} \sigma \, c_0 \, \lambda_i \: \mathrm{d} \Gamma
$$
This is what I arrived on by following the logic. I have several questions about this:

*

*I know the data $g_1$ on $\Gamma_1$, however, this approach requires me to somehow "extend" this data to the whole domain along with its gradient (see the term $\int \limits_\Omega \left( \vec{\nabla} c_0 \right) \cdot \left( \vec{\nabla} \lambda_i \right) \, \mathrm{d} \Omega$ containing $c_0$). How am I supposed to know $c_0$ on whole $\Omega$?

*In the pdf from the beginning (page 12, formula no. 22) there is the term analogous to $\int \limits_\Omega \left( \vec{\nabla} c_0 \right) \cdot \left( \vec{\nabla} \lambda_i \right) \, \mathrm{d} \Omega$, however there is no term with $c_0$ integrated over $\Gamma_3$. Is this just a typo in the pdf, or am I missing something?

*Everyone claims that $\sigma$ in Robin BC is a positive constant. Why can't be $\sigma$ a positive function instead? I see no problem with it being a function, not just a constant - all we have to do is to treat it like every other function ($g_2$, $g_3$) that pops out under these integrals - expand it with basis functions, or if possible, obtain those definite integrals analytically. What am I missing here?

A: *

*I suspect that the author of the resource you mentioned assumes that the function $g_1(x, y)$ is known in the entire closed domain $\bar\Omega $, but only enforced at the boundary $\Gamma_1$, i.e., $c_0(x, y) \overset{!}{=} g_1(x, y) \text{ on } \Gamma_1$.

*Good question, I could imagine that the definition of $c_0(x, y)$ is somewhat incomplete in the sense that $$ c_0(x, y) = \begin{cases} g_1(x,y ) & \text{on } \Gamma_1 \\
0 & \mathrm{else} \end{cases},$$
but done in a way ensuring that you can still take the derivative $\nabla c_o $ needed for the integrals on the RHS.
I have to say that the way how $c^n$ is constructed is not very classic. Normally, you would see something like $$c^n(x, y) = \sum_i c_i \phi_i(x, y) $$ with basis functions $\phi_i(x, y)$ that are equal to $1$ at the associated node. The dirichlet boundary conditions can then be enforced by setting the coefficient to the function value $g_1(x, y)$ at that node. Possibly the author gives a formulation like that in the document to be able to formulate the problem before already discretizing it into intervals.

*The difficulty lies in showing existence for a function $\sigma$. If you are interested take a look at this or this. In the beginning of this lecture notes, it is casually stated that variable coefficients do not pose a problem, although no more in-depth discussion is given.


text:
Q: Prolog: how to write a helper that converts a result into a list? Let's assume I have something like:
% person(ID, Name, Age)
person(_, paul, Age).
person(_, Name, 20).
...

...and instead of the typical binding I would like to have a helper function get_person_list(ID, Name, Age) that calls person but returns me a list:
?- get_person_list(_, Name, 20).
[frank, jack, jane].

...to get a list for e.g. all persons with age 20. How can I achieve this?

A: Do not use findall/3 for this. This is the perfect example of how bagof/3 and setof/3 are different from findall/3.
Your example is a bit strange, so here is another database. I removed the first argument because you don't seem to be using it, and added more rows so that there can be more different ages. Note that it makes no sense to have free variables in a table of facts like person, so all rows have values at both positions.
person(abel, 20).
person(bill, 30).
person(clive, 20).
person(diana, 10).
person(evan, 200).
person(fia, 20).

people_age(Age, Ps) :-
        bagof(P, person(P, Age), Ps).

With this definition of people_age/2, you can query, for example:

Who are the people aged 20?

?- people_age(20, Ps).
Ps = [abel, clive, fia].

Group people by their age.

?- people_age(Age, Ps).
Age = 10,
Ps = [diana] ;
Age = 20,
Ps = [abel, clive, fia] ;
Age = 30,
Ps = [bill] ;
Age = 200,
Ps = [evan].

Who is at least 30 years old?

?- people_age(Age, Ps), Age >= 30.
Age = 30,
Ps = [bill] ;
Age = 200,
Ps = [evan].

The last one could be done differently, if you don't want to group by age. Here is how:
?- bagof(P, Age^( person(P, Age), Age >= 30 ), Ps).
Ps = [bill, evan].

or maybe
?- bagof(Age-P, Age^( person(P, Age), Age >= 30 ), Ps).
Ps = [30-bill, 200-evan].

... if you don't want to throw away the age completely.
But you should just read up on "collecting all solutions in Prolog" and the intended use of all three: findall/3, bagof/3, setof/3.

A: In your code, you don't provide a parameter for the resulting list.
Just call:
findall(Id, person(Id, _, 20), L).

You can make a separate predicate for this query if you really need it often, of course.
get_person_list(Id, List) :-
  findall(Id, person(Id, _, 20), List).

See also bagof/3, as explained in Boris's answer.

A: You could simply write: findall(X,person(_,X,20),L).
This will return you a list L which  is the list you asked...
Example:
person(_, name1, 20).
person(_, name2, 20).
person(_, name3, 20).
person(_, name4, 20).
person(_, name5, 20).

?- findall(X,person(_,X,20),L).
L = [name1, name2, name3, name4, name5].


text:
Q: Configure zero-to-one relationship wih E.F. Fluent Api I'm developing a C# library with .Net Framework 4.0 and Entity Framework 6.1.3.
This is what I'm trying to design:
I have one code that can have one helper code or not. In other words, a code can have zero or one helper code.
And also, I could have helper codes that are not related to any code.
These are the POCOs classes:
public class HelperCode
{
    public int HelperCodeId { get; set; }

    [ ... ]

    public virtual Code Code { get; set; }
}

public class Code
{
    public int CodeId { get; set; }

    [ ... ]

    public int? HelperCodeId { get; set; }

    public virtual HelperCode HelperCode { get; set; }
}

Yes, I know, I have another question with the same issue. Well, it is not the same question because the answer doesn't work:
class CodeConfiguration : EntityTypeConfiguration<Code>
{
  public CodeConfiguration()
 {

  //other codes

    HasOptional(c => c.HelperCode)
        .WithRequired(hc => hc.Code).HasForginKey(x=>x.HelperCodeId);
  }
}

Because it is not required to have a code and .WithRequired() doesn't have .ForeignKey().
Any idea?

A: In EF6 this type of relationship is modeled with Shared Primary Key Association.
Start by removing the HelperCodeId member from Code entity because there will not be FK from Code to HelperCode. Instead, HelperCodeId in HelperCode entity will be both PK and FK to Code.
Then change the Code entity configuration as follows:
HasOptional(c => c.HelperCode)
    .WithRequired(hc => hc.Code)
    .WillCascadeOnDelete();


text:
Q: Global variables in Python 3 class How to use a global variable inside the initialiser of a class in Python 3?
for eg
import urllib
from urllib.request import urlopen
class ABC(object):
 def __init__(self):
   x=urlopen('http://www.google.com/').read()

How do I convert x into a global variable?

A: You have to declare your variable before the class declaration and use the global statement on the init function:
import urllib
from urllib.request import urlopen

x = None

class ABC(object):

 def __init__(self):
   global x
   x=urlopen('http://www.google.com/').read()


text:
Q: How to use string parameters in an URL? I'm using Rest api, so I send a Request with URLs, my problem is when the user nome a folder with a name containing a space or special characters, it sends nothing. I used the following conversion, but it does not work:
string url = "http://localhost:8080/alfresco/service/set/folder/permission/?folderName="
             + folder
             + "&permi="
             + acces
             + "&username="
             + user
             + "&alf_ticket="
             + GetToken();

Uri url2 = new Uri(url);
Response.Write(url2);

A: You have to URL encode the variables in order to make them safe. Use HttpUtility.UrlEncode.
string urlSafeFolder = HttpUtility.UrlEncode(folder);

Use that variable in your URL and you will be fine. (You will have to do this for every parameter you pass in!)

A: When ever any user types in space or any special character in the url we need to encode it using UrlEncode method --
string urlSafeFolder = HttpUtility.UrlEncode(folder);

So if a space is present inside url it will be converted to %20 and so on.
For complete reference check http://www.w3schools.com/tags/ref_urlencode.asp


text:
Q: Line-based heatmap or 2D line histogram I have a synthetic dataset with 1000 noisy polygons of various orders and sin/cos curves that I can plot as lines using python seaborn.

Since I have quite a few lines that are overlapping, I'd like to plot some sort of heatmap or histogram of my line graphs.
I've tried iterating over the columns and aggregating the counts to use seaborn's heatmap graph, but with many lines this takes quite a while.
The next best thing that results in what I want was a hexbin graph (with seaborn jointgraph).

But it's a compromise between runtime and granularity (the shown graph has gridsize 750). I couldn't find any other graph-type for my problem. But I also don't know exactly what it might be called.
I've also tried with line alpha set to 0.2. This results in a similar graph to what I want. But it's less precise (if more than 5 lines overlap at the same point I already have zero transparency left). Also, it misses the typical coloration of heatmaps.
(Moot search terms were: heatmap, 2D line histogram, line histogram, density plots...)
Does anybody know packages to plot this more efficiently and high(er) quality or knows how to do it with the popular python plotters (i.e. the matplotlib family: matplotlib, seaborn, bokeh). I'm really fine with any package though.

A: It took me awhile, but I finally solved this using Datashader. If using a notebook, the plots can be embedded into interactive Bokeh plots, which looks really nice.
Anyhow, here is the code for static images, in case someone else is in need of something similar:
# coding: utf-8
import time

import numpy as np
from numpy.polynomial import polynomial
import pandas as pd

import matplotlib.pyplot as plt
import datashader as ds
import datashader.transfer_functions as tf

plt.style.use("seaborn-whitegrid")

def create_data():
    # ...

# Each column is one data sample
df = create_data()

# Following will append a nan-row and reshape the dataframe into two columns, with each sample stacked on top of each other
#   THIS IS CRUCIAL TO OPTIMIZE SPEED: https://github.com/bokeh/datashader/issues/286

# Append row with nan-values
df = df.append(pd.DataFrame([np.array([np.nan] * len(df.columns))], columns=df.columns, index=[np.nan]))

# Reshape
x, y = df.shape
arr = df.as_matrix().reshape((x * y, 1), order='F')
df_reshaped = pd.DataFrame(arr, columns=list('y'), index=np.tile(df.index.values, y))
df_reshaped = df_reshaped.reset_index()
df_reshaped.columns.values[0] = 'x'

# Plotting parameters
x_range = (min(df.index.values), max(df.index.values))
y_range = (df.min().min(), df.max().max())
w = 1000
h = 750
dpi = 150
cvs = ds.Canvas(x_range=x_range, y_range=y_range, plot_height=h, plot_width=w)

# Aggregate data
t0 = time.time()
aggs = cvs.line(df_reshaped, 'x', 'y', ds.count())
print("Time to aggregate line data: {}".format(time.time()-t0))

# One colored plot
t1 = time.time()
stacked_img = tf.Image(tf.shade(aggs, cmap=["darkblue", "darkblue"]))
print("Time to create stacked image: {}".format(time.time() - t1))

# Save
f0 = plt.figure(figsize=(w / dpi, h / dpi), dpi=dpi)
ax0 = f0.add_subplot(111)
ax0.imshow(stacked_img.to_pil())
ax0.grid(False)
f0.savefig("stacked.png", bbox_inches="tight", dpi=dpi)

# Heat map - This uses a equalized histogram (built-in default), there are other options, though.
t2 = time.time()
heatmap_img = tf.Image(tf.shade(aggs, cmap=plt.cm.Spectral_r))
print("Time to create stacked image: {}".format(time.time() - t2))

# Save
f1 = plt.figure(figsize=(w / dpi, h / dpi), dpi=dpi)
ax1 = f1.add_subplot(111)
ax1.imshow(heatmap_img.to_pil())
ax1.grid(False)
f1.savefig("heatmap.png", bbox_inches="tight", dpi=dpi)

With following run times (in seconds):
Time to aggregate line data: 0.7710442543029785
Time to create stacked image: 0.06000351905822754
Time to create stacked image: 0.05600309371948242

The resulting plots:

A: Although it seems you have tried this, plotting the counts seems to give a good representation of the data. However, it really depends what you're trying to find in your data, what is it supposed to tell you?
The reason for the long run time is due to plotting so many lines, a heatmap based on the counts however will plot fairly quickly.
I created some dummy data for sinus waves, based on noise, no. of lines, amplitude and shift. Added both a boxplot and heatmap.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import random
import pandas as pd

np.random.seed(0)

#create dummy data
N = 200
sinuses = []
no_lines = 200
for i in range(no_lines):
    a = np.random.randint(5, 40)/5 #amplitude
    x = random.choice([int(N/5),  int(N/(2/5))]) #random shift
    sinuses.append(np.roll(a * np.sin(np.linspace(0, 2 * np.pi, N))  + np.random.randn(N), x))

fig = plt.figure(figsize=(20 / 2.54, 20 / 2.54))
sins = pd.DataFrame(sinuses, )

ax1 = plt.subplot2grid((3,10), (0,0), colspan=10)
ax2 = plt.subplot2grid((3,10), (1,0), colspan=10)
ax3 = plt.subplot2grid((3,10), (2,0), colspan=9)
ax4 = plt.subplot2grid((3,10), (2,9))

# plot line data
sins.T.plot(ax=ax1, color='lightblue',linewidth=.3)
ax1.legend_.remove()
ax1.set_xlim(0, N)

# try boxplot
sins.plot.box(ax=ax2, showfliers=False)
xticks = ax2.xaxis.get_major_ticks()
for index, label in enumerate(ax2.get_xaxis().get_ticklabels()):
    xticks[index].set_visible(False)  # hide ticks where labels are hidden

#make a list of bins
no_bins = 20
bins = list(np.arange(sins.min().min(), sins.max().max(), int(abs(sins.min().min())+sins.max().max())/no_bins))
bins.append(sins.max().max())

# calculate histogram
hists = []
for col in sins.columns:
    count, division = np.histogram(sins.iloc[:,col], bins=bins)
    hists.append(count)
hists = pd.DataFrame(hists, columns=[str(i) for i in bins[1:]])
print(hists.shape, '\n', hists.head())

cmap = mpl.colors.ListedColormap(['white', '#FFFFBB', '#C3FDB8', '#B5EAAA', '#64E986', '#54C571',
          '#4AA02C', '#347C17', '#347235', '#25383C', '#254117'])

#heatmap
im = ax3.pcolor(hists.T, cmap=cmap)
cbar = plt.colorbar(im, cax=ax4)

yticks = np.arange(0, len(bins))
yticklabels = hists.columns.tolist()
ax3.set_yticks(yticks)
ax3.set_yticklabels([round(i,1) for i in bins])
ax3.set_title('Count')
yticks = ax3.yaxis.get_major_ticks()

for index, label in enumerate(ax3.get_yaxis().get_ticklabels()):
    if index % 3 != 0: #make some labels invisible
        yticks[index].set_visible(False)  # hide ticks where labels are hidden

plt.show()

Although the boxplot is easy to interpret, it doesn't show the actual distribution of the data very well, but knowing where the median and quantiles lie may be helpful.
Increasing the number of lines and amount of values per line will increase plotting time considerably for the line plots, the heatmap is still fairly quick though to generate. The boxplot becomes indiscernible however.

I couldn't exactly replicate your data (or know the actual size of it), but perhaps the heatmap may be helpful.


text:
Q: Can't install Anaconda 2019.10 on Ubuntu 18.04 I'm trying to install Anaconda 2019.10 using commands on the website:
bash ~/Downloads/Anaconda3-2019.10-Linux-x86_64.sh

After a few steps it says:
Anaconda3 will now be installed into this location:
/home/mrag/anaconda3

  - Press ENTER to confirm the location
  - Press CTRL-C to abort the installation
  - Or specify a different location below

[/home/sz97/anaconda3] >>>
PREFIX=/home/mrag/anaconda3
Unpacking payload...

0%

...and then stacked for hours - no progress...
Any suggestions?

A: I just created my account so can't add a comment to the answer above, but thought I would confirm that Anaconda cannot be installed if you're running on a Linux machine with only one CPU.  The Anaconda bug I found for this is https://github.com/conda/conda/issues/9345 although it's closed as fixed even though it does still exist in the current non-mini Anaconda download Anaconda3-2019.10-Linux-x86_64.sh.
In VMWare, this is solved by shutting the VM down, going to Virtual Machine > Settings > Processors and Memory and selecting 2 or more processor cores.


text:
Q: Getting the largest k elements of a double array The problem I am facing is this one:
I have an array of doubles from which I want to keep the top k greater values.

*

*I have seen some implementations involving Arrays.sort. For example in this example with relative issue it is suggested to use this approach.

*Since I am only interested in the first k elements I have also experimented with MinMaxPriorityQueue. I have created a MinMaxPriorityQueue with a maximumSize:

Of course there is again autoboxing.
Builder<Comparable> builder = MinMaxPriorityQueue.maximumSize(maximumSize);
MinMaxPriorityQueue<Double> top2 = builder.create();

The problem is that the order is the ascending one that it's the opposite of the one I want. So I cannot use it this way.
To state the problem's real parameters my arrays is about 50 elements long and I am interested in up to the top k = 5  elements.
So is there any way to bypass this problem using the second approach? Should I stay with the first one even though I don't really need all elements sorted? Do you know if there is any significant difference in speed performance (I will have to use this in a lot of situations so that's where the speed is needed)? Is there any other solution I could use?
As for the performance, I know I can theoretically check it myself but I am a bit out of time and if someone have any solution I am happy to hear it (or read it anyway).

A: If you only have like 50 elements, as noted in my comment, just sort it and take the last k elements. It's 2 lines only:
public static double[] largests(double[] arr, int k) {
    Arrays.sort(arr);
    return Arrays.copyOfRange(arr, arr.length - k, arr.length);
}

This modifies (sorts) the original array. If you want your original array unmodified, you only need +1 line:
public static double[] largests2(double[] arr, int k) {
    arr = Arrays.copyOf(arr, arr.length);
    Arrays.sort(arr);
    return Arrays.copyOfRange(arr, arr.length - k, arr.length);
}

A: You can use System.arraycopy on a sorted array:
double[] getMaxElements(double[] input, int k) {
    double[] temp = Arrays.copyOf(input, input.length);
    Arrays.sort(temp); // Sort a copy to keep input as it is since Arrays.sort works in-place.
    return Arrays.copyOfRange(temp, temp.length - k, temp.length); // Fetch largest elements
}

For 50 elements, it is much faster to sort an array than to mess with generics and comparables.
I will write up an additional "fast" algorithm...
double[] getMaxElements2(double[] input, int k) {
    double[] res = new double[k];
    for (int i = 0; i < k; i++) res[i] = Double.NEGATIVE_INFINITY; // Make them as small as possible.
    for (int j = 0; j < input.length; j++) // Look at every element
        if (res[0] < input[j]) { // Keep the current element
            res[0] = input[j];
            Arrays.sort(res); // Keep the lowest kept element at res[0]
        }
    return res;
}

This is O(N*k*log(k)) while the first one is O(N*log(N)).


text:
Q: Save BigQuery results to array I have a query that looks like this
SELECT ids FROM `table_name`

The results set is as follows
| ids |
|-----|
| 1   |
| 2   |
| 3   |

I need to save this result set to an ARRAY so that I can later loop over it. Defining the array manually is not an option since my result set will get larger over time adding 4, 5, 6, etc. That's why I can't just use:
SELECT GENERATE_ARRAY(1, 2, 3) AS my_array

I tried
SELECT GENERATE_ARRAY(SELECT ids FROM `table_name`) AS my_array

but it doesn't work.
I'm basically looking for the inverse of UNNEST.

A: Below is for BigQuery Standard SQL - usually ARRAY_AGG can be used as inverse of UNNEST
#standardSQL
SELECT ARRAY_AGG(ids) ids
FROM `project.dataset.table`

You can test, play with above using sample data from your question as in below example
#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 ids UNION ALL
  SELECT 2 UNION ALL
  SELECT 3
)
SELECT ARRAY_AGG(ids) ids
FROM `project.dataset.table`

with result
Row ids
1   1
    2
    3


text:
Q: Change letters for day name When I use this code the name of the day been writed with a small letter.
get_the_time(strtotime($DateValue)),
get_the_time('l d.m.Y H:i', $post)

I want the name of the day looking like this:   Monday, Sunday, Thursday etc.
Now it look like this  monday, sunday
What do I do wrong ?

A: In the comments, @vancoder points out that it appears day names are not capitalized in Norwegian. If you require that they be capitalized, you could do something like this:
ucfirst( get_the_date( 'l', $post ) ) .
get_the_date( ' d.m.Y', $post ) .
get_the_time( ' H:i', $post );

...using PHP's ucfirst() to force the first character to be uppercased.
(I've also split the date and time to use get_the_date() and get_the_time(), since it seemed semantically cleaner to me that way.)


text:
Q: Uploading files with Flask (running on App Engine) to Google Drive I would like to upload a file to Google Drive using Flask which runs on App Engine. I got Google Drive service (constructed with Google Drive API) up and running and was able to upload a file from the server using files().insert(...).
Now I would like to implement uploading via HTML form. This gives me a FileStorage object. How should I proceed from this point in order to get the file inside Google Drive?
Please note that I'm uploading files that exceed App Engine's 5MB limit on request size.
Thank you for your suggestions.

A: Upload the form to blobstore with a callback into your frontend.
If the file is very large you might need to go as far as a backend with resumable uploads done on chained backends (as backends could also go down in the middle of the upload for huge files)


text:
Q: AspNetCore namespace doesnt exist I'm following this course to learn ASP.NET Core.
I did exactly as they did, I can type dotnet new and dotnet restore.
I also installed the dotnetcore 1.0.1 SDK preview.
All seems fine, and I should be able to type
using Microsoft.AspNetCore.Http;

But the only things recognized after Microsoft are cSharp, visualbasic and win32?
Here is my project.json file:
 {
   "version": "1.0.0-*",
   "buildOptions": {
   "debugType": "portable",
   "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
   "netcoreapp1.0": {
    "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.1"
    },
    "Microsoft.AspNet.WebApi": "5.2.3",
    "Microsoft." **<< i cannt type AspNetCore here**
    },
   "imports": "dnxcore50"
   }
 }

There is no Microsoft."AspNetCore". The only things I do have starting with Asp are:

*

*AspNet.Identity.Owin

*AspNet.Mvc

*AspNet.Providers.Core

*AspNet.Razor

*AspNet.SignalR

*AspNet.Web.Optimization

*AspNet.WebApi

*AspNet.WebApi.Clients

*AspNet.WebApi.Core

*AspNet.WebApi.Cors

*AspNet.WebPages

A: The code completion doesn't always work when editing the project.json file, especially if you're using a lighter editor like VS Code. (Sometimes it doesn't work even in full-blown Visual Studio).
If this happens, don't worry! You can still install any packages you need. Find packages by searching on NuGet and then edit the dependencies section like this:
"PackageName": "1.0.0"   # Version from package details on NuGet

Then, use the dotnet restore command within the project directory to pull down all the packages in project.json.


text:
Q: How to remove "pause slide" from beamer-like presentation when you don't have the sources Lot's of my teachers give us some slides, built with beamer, but the sources are never included. And to print it, I like to remove the useless slides that are created using \pause-like commands.
I tried to find some solution to remove them automatically, but because I never found a good solution, I decided to write my own solution that I share in the answer. If you have a better way to proceed/a more straight forward solution, don't hesitate to add it !

A: I came up with this solution, that is a one-line bash command (you can easily change it into an alias/bash script). The idea is to take always the last slide when several slides have the same page number. The problem is that if the same slide display two different things on the same "page", then only the last one is kept.
INPUT=mpri_clp1.pdf; OUTPUT=mpri_clp1_out2.pdf; (pdftk ${INPUT} dump_data | egrep "PageLabelNewIndex" | sed 's/[^0-9]//g' | sed '1d' | sed -r 's/(.*)/echo $((\1-1))/ge') | tr '\n' ' ' | xargs -I{} echo "pdftk \"${INPUT}\" cat {} end output \"${OUTPUT}\"" | bash


text:
Q: How to zero out rows and columns in a SymPy Matrix I'm implementing a simple FEA code and I need to zero out particular rows and columns to apply boundary conditions. Example matrix:

I tried with my_matrix[:,1] = 0 but it returns an error: ValueError: unexpected value: 0
Can some one guide me on how to make columns and rows zero?

A: Sympy matrix objects don't appear to support assigning a constant to multiple entries like numpy array objects.
Try my_matrix[:,1] = [0]*my_matrix.shape[0] instead, which generates a list of 0s of length equal to the number of rows of my_matrix.


text:
Q: Does a Möbius transformation map the diameter points of a circle to diameter points? The Möbius transformation given by $(az+b)/(cz+d)$ maps a circle to circle or a line. Say we are given the unit circle centered at the origin and that the pole $-d/c$ does not touch the boundary of the circle. Under these assumptions, the Möbius transformation maps the unit circle to another circle. From all the examples I have seen, it looks like the points $-1$, $1$ which are diameter points on the unit circle gets mapped to another pair of diameter points on the image circle. Same for $-i$ and $i$. I was wondering if this is always the case?

A: Your conjecture is not correct. A simple counterexample is $T(z) = 1/(z+2)$, which maps the circle $|z| = 1$ onto the circle $|z-2/3|=1/3$.
But the diametral points $\pm i$ on the unit circle are mapped to $\frac 25 \mp \frac i 5$, which are not diametral on the image circle.
One can show that if $T(z) = \frac{az+b}{cz+d}$ has the property that diametral points on the unit circle (or any circle with center at the origin) are mapped to diametral points on the image circle, then $c=0$ or $d=0$, i.e. $T$ is of the form $T(z) = \alpha z+\beta $ or $T(z) = \alpha+\beta/z$.

A: The automorphism group of the unit circle consists of all elements of the form $e^{i\theta}\frac{\alpha-z}{1-\bar{\alpha}z}$ where $\alpha$ is an element of the open unit disc.Note that if you take a general Mobius transformation The unit disc may not always map to the unit disc. Now for the automorphisms as I've written down just take $z=e^{i\phi}$ and you'd see that it maps to a point on the unit disc.


text:
Q: How to fill a text field with an attribute using jQuery (Rails)? I have two models: Post and Tag. The Post model has an attr_accessor called :tag_name and the Tag model has an attribute called :name.
I have this form:
<%= form_for(@post) do |f| %>
  <%= render 'shared/error_messages' %>

    <%= f.label :title %>

    <%= f.text_field :title %>

    <%= f.label :content %>

    <%= f.cktext_area :content %>

    <%= f.label :tag_name %>
    <%= f.autocomplete_field :tag_name, autocomplete_tag_name_posts_path, :"data-delimiter" => ' ' %>

    <%= f.submit %>

<% end %>

This is the output of the field:
<input data-autocomplete="/posts/autocomplete_tag_name" data-delimiter=" " id="post_tag_name" name="post[tag_name]" size="30" type="text">

I want the user to see the name of the tags as soon as they enter the show view.
Any suggestions of how to accomplish this?
EDIT:
I tried putting this at the end of the form:

But nothing happens

A: $('#post_tag_name').attr('value', '<%= render @post.tags %>');


text:
Q: AWS give user access to only elastic beanstalk instances and storage How to give access to a IAM user to only access resources created by Elastic bean, i.e. The S3 bucket and the EC2 instances. The user should not be able to access any other S3 bucket or EC2 instance not created with Elastic Beanstalk.
The same policy should apply to EC2 instances created automatically via the Auto Scaling policy.

A: You can go with the "tags" approach. You can set elasticbeanstalk and autoscaling launch configuration to create instances with a predefined "tags" . And you can allow users to see only this tags.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:*"
      ],
      "Resource": "*",
      "Condition": {"StringEquals": {"ec2:ResourceTag/department": "dev"}}
    }
  ]
}

There could be better approaches, we should wait and see other responses.
best,


text:
Q: Графический интерфейс python Tkinter from tkinter import *
from tkinter.ttk import Radiobutton
import random
from tkinter.ttk import Combobox

a = ['Выпей кофе','Поговорить с близкими!','Отдохни сегодня','Хорошо бы тебе прогуляться','Напиши друзьям','Покушай здоровой еды','Сделай разминку']
def clicked():
    lbl.configure(text=random.choice(a))
def angr():
    res = "Привет {}, вот твое предсказание".format(txt.get())
    lbl.configure(text=res)

window = Tk()
window.title('Добро пожаловать в приложение "ПеЧеНьКи"')
window.geometry('1400x1250')
selected = IntVar()
txt = Entry(window,width=10)
txt.grid(column=10, row=0)
lbl1 = Label(window, text="Введите свой возраст:")
lbl1.grid(column=18, row=0)
lbl2.grid(column=20, row=0)
rad1 = Radiobutton(window,text='Понедельник', value=1, variable=selected)
rad2 = Radiobutton(window,text='Вторник', value=2, variable=selected)
rad3 = Radiobutton(window,text='Среда', value=3, variable=selected)
rad4 = Radiobutton(window,text='Четверг', value=4, variable=selected)
rad5 = Radiobutton(window,text='Пятница', value=5, variable=selected)
rad6 = Radiobutton(window,text='Суббота', value=6, variable=selected)
rad7 = Radiobutton(window,text='Воскресенье', value=7, variable=selected)
btn = Button(window, text="За печенькой!", command=clicked, bg="black", fg="yellow")
angr1 = Button(window, text="Я ввёл имя!", command=angr ,bg="black", fg="yellow")
lbl = Label(window)
rad1.grid(column=0, row=0)
rad2.grid(column=1, row=0)
rad3.grid(column=2, row=0)
rad4.grid(column=3, row=0)
rad5.grid(column=4, row=0)
rad6.grid(column=5, row=0)
rad7.grid(column=6, row=0)
btn.grid(column=3, row=3)
lbl.grid(column=0, row=1)
angr1.grid(column=13, row=0)
combo = Combobox(window)
combo['values'] = ('1-5','6-10','11-15','16-20','21-25','26-35','36-50','>50','конфиденциальная информация')
combo.current('конфиденциальная информация')
combo.grid(column=20, row=0)
window.mainloop()

A: Ошибка в упаковке:
Вы применили метод .grid к несуществующему лейблу lbl2
lbl2.grid(column=20, row=0)

Нужно его просто создать и привязать к окну или фрейму:
lbl2 = Label(window,text = 'Как то так')

Далее
Работа с combobox:
В combo.current()
в скобках задаётся индекс, а не строка
combo.current(8)

Отрицательный индекс (-1) , насколько я понял, не поддерживается
Теперь всё запускается и работает


text:
Q: Excel conditional rounding of division remainder I am building a sheet that calculates fractional quantities from preset values. The results need to be either whole numbers or have a remainder of 0.5. For example, a value of 5 will result in 2.5 for half quantities and 1 for quarter quantities.
I want to round the quantity remainder to 0.5 if a division remainder is greater than 0.25 or less than 0.75, but otherwise round to whole numbers. How do I set up such a formula?

A: With a formula and a little math trickery.
=MROUND(A1*10,5)/10


text:
Q: Объясните по-простому что такое разыменование массива и зачем это нужно? function getArray() {
    return array(1, 2, 3);
}

// в PHP 5.4
$secondElement = getArray()[1];

// ранее делали так
$tmp = getArray();
$secondElement = $tmp[1];

// или так
list(, $secondElement) = getArray();

A: Этот код из документации PHP. Раньше нельзя было написать
$secondElement = getArray()[1];

приходилось сначала присваивать результат работы функции переменной и уже работать с переменной.
Кстати, если элемент массива объект, то можно и так
$secondElementName = getArray()[1]->name;

А нужно это для удобства, меньше строк кода и понятнее сам код.


text:
Q: angular universal : npm run serve:ssr ReferenceError: window is not defined I tried every solution in the internet and it fails every time, here is wha i tried:
1-add global window to server.ts
2-domino
3-create service and inject DOCUMENT
anything can help would be advantage to me.
ReferenceError: window is not defined
at StorageService.getUser (C:\Users\dell\Desktop\projects\angular\radio_front\dist\radio_front\server\main.js:1:3847800)
at C:\Users\dell\Desktop\projects\angular\radio_front\dist\radio_front\server\main.js:1:3848390
at C:\Users\dell\Desktop\projects\angular\radio_front\dist\radio_front\server\main.js:1:4186790
at Object. (C:\Users\dell\Desktop\projects\angular\radio_front\dist\radio_front\server\main.js:1:4187022)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! radio-front@0.0.0 serve:ssr: node dist/radio_front/server/main.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the radio-front@0.0.0 serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\dell\AppData\Roaming\npm-cache_logs\2022-07-20T10_27_27_429Z-debug.log


text:
Q: Webpack: extract common modules from entry and child chunks to separate commons chunk I have an application built with webpack that uses code splitting. I now want to aggregate all common modules that match specific criteria (in this case node_modules) across all entry chunks and all child chunks (generated via code splitting) into a single separate commons chunk.
If I do this:
new webpack.optimize.CommonsChunkPlugin({
    children: true,
    async: 'vendor',
    minChunks: (module) => {
        const isVendor = module.context.split('/').some(dir => dir === 'vendor');
        return isVendor;
    },
}),

Webpack will aggregate all modules that match the minChunks function into a separate commons chunk, but only for modules from child chunks—it will not aggregate modules from the entry chunk into the commons chunk. As a result, I have duplicated modules that appear in both my entry chunk and commons chunk.
How is this possible?

Example: https://github.com/OliverJAsh/webpack-commons-vendor/blob/f524bfdb0e047161c453a6b84f89ab6d25d6c648/webpack.config.js

A: You need to create a webpack DLL that contains all your commonly used libs.
https://webpack.js.org/plugins/dll-plugin/
An example on how to set this up can be found in React-Boilerplate.
https://github.com/react-boilerplate/react-boilerplate/blob/master/internals/webpack/webpack.dll.babel.js
And here is the config for the example.
https://github.com/react-boilerplate/react-boilerplate/blob/master/internals/config.js


text:
Q: Is it possible to have multiple separate ternary expressions in ng-class for an element? I am trying to combine the following two ng-class ternary expressions into one ng-class (so I can control both the color, via btn-success/danger classes, and the width, via width-small/medium/wide class, of my button divs

 0) ? 'btn-success' : 'btn-danger'">{{rate}}

{{rate}}

I realize I could just do something along the lines of below; however, I would like to make use of the ternary expressions available in 1.1.5

 0, 'btn-danger': rate <= 0, 'width-small': priority == 'low', 'width-medium': priority == 'medium', 'width-wide': prioity == 'high'}">{{rate}}

Space separating the expressions did not work for me, nor did comma separating them within ng-class
Thanks advance for your assistance in determining if/how to have multiple ternary expressions in a single ng-class

A: I think you'd rather use a filter. You could write a rateToClass filter that would hold the logic and transform your rate in the class name that you want.
You could also put a rateToClass(rate) function in your scope, but it's ugly.
If you insist on having your logic in the view,
ng-class support multiple classes by using an object (see official doc first example, line 7):

Map Syntax Example

You can have more complexe expression like ng-class='{btn-success: rate > 0}'.

A: It is possible to add multiple ternary expressions on a single ng-class directive by putting each of the expressions into an array, as items of this array.
Example :

A: For anyone looking for the answer: Yes this is indeed possible, also as mentioned the readability is questionable.

From the ngClass documentation:

The directive operates in three different ways, depending on which of >three types the expression evaluates to:

*

*If the expression evaluates to a string, the string should be one or >more space-delimited class names.

*If the expression evaluates to an array, each element of the array >should >be a string that is one or more space-delimited class names.

*If the expression evaluates to an object, then for each key-value pair of >the object with a truthy value the corresponding key is used as a class >name.

Option 1 applies here.
From my understanding using this method will result in 2 watches while using object notation will result in 4, but I might be wrong on this one.


text:
Q: Python - YouTube API v3 - How to get video ID only? How can I get only video ID of video? As I know, I should use fields for that but I don't understand how do they work. My code:
service = build('youtube', 'v3', developerKey = api_key)
request = service.search().list(q = name, part='id',fields = *what should I type here*, maxResults = 1, type = 'video').execute()

"name" is search term variable. I get it from a file which contains list of names. By using this code I get information that I don't need. As I said, I need only video ID.

A: You can try your query here:
https://developers.google.com/youtube/v3/docs/search/list#try-it
I believe that the following query is the way in what you want to search and retrieve only the video id:
https://www.googleapis.com/youtube/v3/search?part=id&q={NAME}&type=video&fields=items%2Fid&key={YOUR_API_KEY}
If for example {NAME} is psy, then this call returns the following data, from where you can retrieve the videoId of one of the items;
{
 "items": [
  {
   "id": {
    "kind": "youtube#video",
    "videoId": "9bZkp7q19f0"
   }
  },
  {
   "id": {
    "kind": "youtube#video",
    "videoId": "Ecw4O5KgvsU"
   }
  },
  {
   "id": {
    "kind": "youtube#video",
    "videoId": "o443b2rfFnY"
   }
  },
  {
   "id": {
    "kind": "youtube#video",
    "videoId": "WOyo7JD7hjo"
   }
  },
  {
   "id": {
    "kind": "youtube#video",
    "videoId": "QZmkU5Pg1sw"
   }
  }
 ]
}

if you modify the example included in the python client library:
https://developers.google.com/api-client-library/python/
you can do that in this way:
search_response = service.search().list(
  q="google",
  part="id",
  type="video",
  fields="items/id"
).execute()

videos = []

for search_result in search_response.get("items", []):
    videos.append("%s" % (search_result["id"]["videoId"]))

print "Videos:\n", "\n".join(videos), "\n"

A: Try out below code:
import requests
import json
payload = {'part': 'snippet', 'key': DEVELOPER_KEY, 'order':'viewCount', 'q': 'A R Rahman', 'maxResults': 1}
l = requests.Session().get('https://www.googleapis.com/youtube/v3/search', params=payload)
resp_dict = json.loads(l.content)
print resp_dict['items']
for i in resp_dict['items']:
   print "VideoId: ",i['id']['videoId']


text:
Q: What Windows' programs or services might alter the LastAccessed attribute of a file? I have a license file that I wish to invalidate if any program other than ours reads the file.  My idea is to use File.GetLastAccessedTime(string) and save this value off to the file to be checked when we read the file back in.
However, I am afraid that aside from anti-virus (customers will have to exclude our license file from a scan, I know), there might be windows services or programs that might touch the files and cause the LastAccessed attribute on the file to be updated outside the context of our program, but without malicious intent.
What Windows' programs or services might access this file in the background? Is this a legitimate problem I need to worry about? And if this is something I should be worrying about, are there any common techniques to reliably achieve my end goal?
I am looking for a solution in the .NET 4 world. Thanks in advance for any help with this.

A: ANy desktop search app.  Any virus they get.  WIndow's find in files application.  All anti-virus and anti-malware tools.  A better idea is to cryptographically sign the file to detect alteration of contents, or not to leave a file you're that worried about on the client's machine (download it and use it in ram only).


text:
Q: proof that topologist sine curve is not locally connected I know that this question has been asked before, but it is still not clear to me why the topologist sine curve is not locally connected.

The topologist's sine curve: Let $S$ denote the following subset of the plane. $$S = \{ (x, \sin(1/x)) \mid 0 < x \le 1\}.$$ The set $\bar{S}$ is called the topologist's sine curve, which equals the union of $S$ and the vertical interval $0 \times [-1,1]$.

My attempt was:
Fix a point $p = (0, t)$ where $t > 0$, and consider a neighborhood $N = B(p,\delta)\cap\bar S$, where $B(p,\delta)$ denotes a ball centered at $p$ with radius $\delta$.
Then, I want to show that every open subset of $N$ is disconnected, so there can't be connected neighborhood of $p$ contained in $N$.
But, I am having a trouble with establishing that every open subset of $N$ is disconnected.
How can I prove the claim?

A: Let's stick with a particular point on the interval $0 \times [-1, 1]$, say $p = (0, 0)$. Notice that there is no need to make your neighborhoods balls centered at $p$; we could consider open squares instead (they also form a basis for the topology of the plane). Let $U_\epsilon := (-\epsilon, \epsilon) \times (-\epsilon, \epsilon)$ be some open square centered at $p$ (where $\epsilon > 0$). Then $U_\epsilon \cap \overline{S}$ consists of $0 \times (-\epsilon, \epsilon)$ and the graph of the function $\sin(1/x)$ restricted to the domain $D_\epsilon:=\{x \in (0, \epsilon) : |\sin(1/x)| < \epsilon\}$. You should be picturing a bunch of very short curve segments which are almost vertical. We can choose $\epsilon$ small enough that $D_\epsilon$ does not contain any $x$ such that $\sin(1/x) = 1$.
Now let $V$ be some nonempty open subset of $U_\epsilon$ containing $p$. It contains $U_{\epsilon'}$ for some smaller $\epsilon' > 0$. Then there exists some $x_0 \in (0, \epsilon')$ such that $\sin(1/x_0) = 1$ and $(x_0, \infty) \cap D_{\epsilon'} \neq \emptyset$ (this should be easy to see; there is a sequence of such $x_0$ which converges to $0$). It follows that $D_{\epsilon'} = (D_{\epsilon'} \cap (0, x_0)) \cup (D_{\epsilon'} \cap (x_0, \infty))$, i.e. it is disconnected.
I claim that we can use this information to prove that $V \cap \overline{S}$ is disconnected. The idea is to look at the intersections of this set with $(-\infty, x_0) \times \mathbb{R}$ and with $(x_0, \infty) \times \mathbb{R}$. Note that neither of these intersections is empty since, in either case, we can take an appropriate value of $x \in D_{\epsilon'}$ and note that $(x, \sin(1/x)) \in V$. Secondly, these open sets do indeed cover $V \cap \overline{S}$ since $(x_0, 1)$ is the only point in $\overline{S}$ whose $x$-coordinate is $x_0$, and $V$ contains no point whose $y$-coordinate is $1$. So we conclude that $V \cap \overline{S}$ is disconnected.


text:
Q: JavaScript arrays are not same Here I attach the screenshots of my console log results. Both of them are Objects. But they are not the same. What could be the problem? One is showing
(5) [{..},{..},{..},{..},{..}]

Another one just shows [].
let tmp_array = [];
    this.database.ref('/users/').once('value', (snapshot) => {
      snapshot.forEach( (childSnapshot) => {
      var key = (childSnapshot.val() && childSnapshot.key) || 'Anonymous';
      var name = (childSnapshot.val() && childSnapshot.val().name) || 'Anonymous';
      var email = (childSnapshot.val() && childSnapshot.val().email) || 'Anonymous';
      tmp_array.push({ key: key, email: email, name: name });
    });
    this.setState({ data: tmp_array });
    this.getImageList(tmp_array);
    console.log(tmp_array);
 });

let tmp_array2 = [];
    lodash.forEach(tmp_array, (value, key) => {
      this.storage.ref().child(value.key + '.jpg').getDownloadURL().then(function (url) {
        tmp_array2.push({ id: value.key, image: url });
    });
});
this.setState({ image: tmp_array2 });
console.log(tmp_array2);

A: Welcome to programming with web APIs. You have a typical async problem here. I'll explain what's happening in your code, then give you first steps to a solution, point out some further considerations, and finally provide links with more information for you to read up on this incredibly common (but initially equally confusing) topic.
The problem: the download URLs are loaded asynchronously
Your code calls getDownloadURL, which happens asynchronously. This means that your other code continues while the URL is being loaded. Then when the URL is loaded, your callback is called with the URL. This means that any code that needs the URL, must be inside the callback.
This is easiest to see if you simply the code and add some log statements:
console.log("Before starting getDownloadURL");
this.storage.ref().child(value.key + '.jpg').getDownloadURL().then(function (url) {
    console.log("Got download URL");
});
console.log("After starting getDownloadURL");

When you run this code it prints:

Before starting getDownloadURL
After starting getDownloadURL
Got download URL

That is probably not the order you expected, but it completely explains why the array is empty when you print it: the URLs haven't been loaded yet, so they haven't been added to the array yet.
The solution: put all code that needs the download URL inside the callback
To solve this problem all code that needs the download URL from the database must be inside the callback (or be called from there). So a first step would be:
let tmp_array2 = [];
lodash.forEach(tmp_array, (value, key) => {
  this.storage.ref().child(value.key + '.jpg').getDownloadURL().then(function (url) {
    tmp_array2.push({ id: value.key, image: url });
    this.setState({ image: tmp_array2 });
    console.log(tmp_array2);
  });
});

When you run this, you will see that it logs the array as often as there are child nodes/images. Each time it gets a download URL (remember: this happens asynchronously) it adds it to the array, and then tells React that the state has changed (to it can update the UI).
Some additional considerations and problems
There are more pitfalls in my last code snippet still:

*

*Calling setState() repeatedly may result in a UI that is only partially updated, or in flicker. In that case, consider checking if you've gotten all download URLs before calling setState with something like: if (tmp_array2.length === tmp_array.length) this.setState({ image: tmp_array2 });.

*The download URL calls happen asynchronously, and may (I think, it depends on the backend implementation of that API) complete in a different order than in which you call them. In other words: the download URL for the second image may be returned before the download URL for the first image. If this is a concern for your application, be sure to either replicate the other information for the image in tmp_array2 (I think you already do this), or consider storing the download URLs in a way that allows you to associate them back with the items in tmp_array.

More info
As I said at the start: this is a very common problem for developers who are new to dealing with asynchronous APIs to run into. So there are probably hundreds more relevant questions/links if you search for them. Here are some of my favorites:

*

*Doug's post on Firebase's asynchronous APIs

*Handling Asynchronous Calls (Firebase) in functions

*Best way to retrieve Firebase data and return it, or an alternative way

*Why Does Firebase Lose Reference outside the once() Function?

*JavaScript - Firebase value to global variable

*Firebase use query result outside function

A: A [] is an empty array. The other [{..},{..},{..},{..},{..}] is an array containing 5 objects. Since you didn't specify which temp array is representing which logged array, I cannot help you determine why one array is empty.


text:
Q: insert content INSIDE the  tag with jquery I want to add some content  to the
 after ipsum but before

Service: lorem ipsum Change

I want like

Service: lorem ipsum more content Change

please let me know how to do.

A: $('#service>a').before(' more content ')

http://jsfiddle.net/KnbDS/

A: Its a 3 step solution:

*

*Get the text inside the p tag

*Edit the text, using substrings

*Set the text inside the p tag to your newly formed string

EDIT:
As pointed out by several people jQuery already has this functionality (I learnt something new). So this is a much better route:
$('#service>a').before("new content");

A: Use following code :
$('#service>a').before('Your extra code added by you')


text:
Q: DataContract on entities from Entity Framework Code-First class I'm using the EF6 code-first for building a database, which I need for a WCF Service. My DbSet would be something like:
 public class Customer
{
    [Key]
    public long Id { get; set; }
    public string Name { get; set; }
    public string Town { get; set; }
    ...
    public virtual ICollection<Invoice> Invoices { get; set; }
}

I would like to get the customer's data with a get-method from my WCF service.
I came up with the idea to have the whole class as a [DataContract] with each property as a [DataMember].
So far there should be no problem and I checked online if there is any recommendation or 'best practice' in this scenario. So I found this question on stackoverflow in that Pein is saying:

First of all you should never expose the whole entity as a data contract, as it is a domain object, not the data transfer object.

So my question is: why shouldn't one have the entity as data contract? And if so, is it a better way to have different classes with data contract for receiving and sending my data from the entities?
Thanks in advance!


text:
Q: Properly create and customise a web app using Visual Studio 2015 C# MVC template I'm new to C# web, I want to know how to properly create a web app using
Visual Studio 2015 MVC templates, and being able to customise some of its code. I want to both practice C# web and clean code...
So I have 2 projects, one for Domain and another which is the Web App.
For example: in my domain I have a class named User with the following code (it is aimed at users who speak Spanish so error messages are in Spanish):
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Domain
{
    public class User
    {
        public int Id { get; set; }

        [DisplayName("Nombre de Usuario")]
        [Required(ErrorMessage = "El Nombre de Usuario es obligatorio.")]
        [StringLength(30)]
        [Index(IsUnique = true)]
        public string UserName { get; set; }

        [DisplayName("Correo Electrónico")]
        [Required(ErrorMessage = "El Correo Electrónico es obligatorio.")]
        [StringLength(45)]
        [EmailAddress]
        [Index(IsUnique = true)]
        public string Email { get; set; }

        [DisplayName("Contraseña")]
        [Required(ErrorMessage = "La Contraseña es obligatoria.")]
        [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Confirmar Contraseña")]
        [DataType(DataType.Password)]
        [NotMapped]
        [Compare("Password", ErrorMessage = "La contraseña y la contraseña de confirmación no coinciden.")]
        public string ConfirmPassword { get; set; }

        public bool Locked { get; set; } = false;

        public bool ConfirmedAccount { get; set; } = false;

        [DisplayName("Perfil")]
        [Required(ErrorMessage = "El Perfil es obligatorio.")]
        public Profile Profile { get; set; }

        private User() { }

        public User(string userName, string email, string password, string confirmPassword, Profile profile)
        {
            UserName = userName;
            Email = email;
            Password = password;
            ConfirmPassword = confirmPassword;
            Profile = profile;
        }
    }
}

Before continuing, any suggestions about this code will be very welcome!
I want to use ResetPasswordViewModel, ForgotPasswordViewModel, ExternalLoginConfirmationViewModel, and many other functionalities that come with MVC templates (you can see them inside AccountViewModels.cs) without programming them myself (that is the idea of using a template isn't it?), but I also want to have my own User class...
Reading the template code, I've found that ApplicationUser class inside IdentityModels.cs would have the logic for User the template applies, It also has a commentary telling me that if I want any other User properties added, they should be added here. But I don't think it would be a good idea to have Business bound code inside the web app, what if (hypothetically speaking) tomorrow I want to make the same application on another platform? (and by the way, why does the template encourage to have the business code inside the web app in the first place??)
I hope you get the idea by now, how to use my own User code to work properly with the MVC template? For example to work along with the class AccountViewModels.cs.
I know those are a lots of questions (I've got plenty more)... As I said, I'm new to this and want to get the hand of it, any suggestions on how to improve my code is welcome.
Regards


text:
Q: How to select parent div of a form in JQuery? here is what i got

    <from id="test">
        <input type="submit">
    </form>

and a lil jquery
    $(document).ready(function(){

        $('form').submit(function()
                         {
                             $(this).parent().html('
1
');
                         });
    });

you can play with that here,
and by clicking on submit button it should put
1
 in div#right but it don't !
Cause this is a form in this case but it works with button label or any thing else and I think that is because form is not a DOM node.
So how can I select the parent of a form, or in other words how can i select the Div that contents the form ?
Update: as it was a part of an ajax call i wanted to break it down and find the problem
but i had made a typo which cost me an hour or so, but the problem with ajax was that you $(this) inside success: is not the form any more so i did like this
    `$('form').submit(function(){
        form = $(this);//  I set the form to a varible !!

                 $.ajax({

   type: "POST", url: "ajax.php", data: $(this).serialize(),

                success: function(data){
                    $(form).parent().html(data); // I used the varible i set to form before!
                               }});`

anyways, how can i mark this question as solved ?!

A: As Chowlett says, use form rather than from.
That code will then work, because the $(this) inside the submit function will select the form element, the parent of which is is the #right div.
You could use .parent('div') to make sure you select a div, and not anything else.

A: as it was a part of an ajax call i wanted to break it down and find the problem but i had made a typo which cost me an hour or so, but the problem with ajax was that $(this) inside success: is not the form any more so i did like this
$('form').submit(function(){
        form = $(this);//  I set the form to a varible !!

                 $.ajax({

   type: "POST", url: "ajax.php", data: $(this).serialize(),

                success: function(data){
                    $(form).parent().html(data); // I used the varible i set to form before!
                               }});


text:
Q: Unable to access mongo entry by "id" I have a Mongo Document with some fields (_id, id, name, status, etc...). I wrote a typical document in a class(like a model would do):
class mod(Document):
    id=fields.IntField()
    name = fields.StringField()
    status=fields.StringField()
    description_summary = fields.StringField()
    _id = fields.ObjectIdField()

And with this model, I tried to access them:
    >>> from mongoengine import *
    >>> from api.models import *
    >>> connect('doc')
    MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())

I tried to fetch all the entries in the "mod" document: It Worked! I can get all the fields of all the entries (id, name, etc...)
    >>> mod_ = mod.objects.all()
    >>> mod_[0].name
    'Name of entry'
    >>> mod_[0].id
    102

I tried to filter and return all the entries with the field "status" = "Incomplete": It works, just like before.I tried to filter other fields: it works too
    >>> mod_ = mod.objects(status="Incomplete")
    >>> mod_[0].name
    'Name of entry'
    >>> mod_[0].id
    102

But When I try to filter with the id I don't manage to get a result:
    >>> mod_ = mod.objects(id=102)
    >>> mod_[0].name
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
        return queryset._document._from_son(queryset._cursor[key],
      File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
        raise IndexError("no such item for Cursor instance")
    IndexError: no such item for Cursor instance
    >>> mod_[0].id
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
        return queryset._document._from_son(queryset._cursor[key],
      File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
        raise IndexError("no such item for Cursor instance")
    IndexError: no such item for Cursor instance

So I tried with mod.objects.get(id=102)
>>> mod_ = mod.objects.get(id=102)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 271, in get
    raise queryset._document.DoesNotExist(msg)
api.models.DoesNotExist: mod matching query does not exist.

Mod matching query does not exist, so it doesn't recognize the id field  but when I write mod_[0].id I do have a result, so what can be wrong?
EDIT: I believe that when writing mod.objects(id=102), the field id is interpreted as the _id. How can I specify, I want to query by id and not _id? My Document is already written, so I cannot change the name of the fields.

A: So, the problem does not come from the difference between _id and id, like said @HourGlass. The values of the id field were stored as integer, I wrote fields.IntField() for the id field, and called mod.objects(id=102) (without quotes).
But for some reason, I have to write them as fields.StringField(), and call mod.objects(id='102').