text:
Q: How to open VKontakte app with a specific friend? Background
In order to open Facebook app with a specific Facebook friend, you can use this intent:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("fb://profile/%s", friendId)));

A similar solution is found for LinkedIn:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("linkedin://profile/%s",  friendId)));

I think the next one will work for Google Plus (didn't test it, but it seems promising) :
final Intent intent =new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("https://plus.google.com/%s/posts", friendId)));

The question
I've tried to find how to open VKontakte (VK) social network app using such intents, but couldn't find it.
Is there such an intent? If so, what is it?

A: The answer from developer is next:

Yes, it's done the same way:

final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("vkontakte://profile/%d", friendId)));

If you need to open a community, use the same URL but add the minus sign to the community ID.

Question answered here

A: Here is a list of url i found at VK app manifest

*

*http ://vk.com/.*

*http ://vkontakte.ru/.*

*https ://vk.com/.*

*https ://vkontakte.ru/.*

*http ://m.vk.com/.*

Note: remove space after http/https. SO won't let me post more than 2 links
you can use any of that to launch vk from your app
here is how i do that
 private void sendIntentToVkApp() {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("http://vk.com/hmrussia"));
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

and here is a part of VK Manifest where all the schemes are defined
<intent-filter>
            <category
                android:name="android.intent.category.DEFAULT"/>
            <action
                android:name="android.intent.action.VIEW"/>
            <data
                android:scheme="vklink"/>
        </intent-filter>
        <intent-filter>
            <action
                android:name="android.intent.action.VIEW"/>
            <category
                android:name="android.intent.category.DEFAULT"/>
            <category
                android:name="android.intent.category.BROWSABLE"/>
            <data
                android:scheme="http"
                android:host="vk.com"
                android:pathPattern="/.*"/>
        </intent-filter>
        <intent-filter>
            <action
                android:name="android.intent.action.VIEW"/>
            <category
                android:name="android.intent.category.DEFAULT"/>
            <category
                android:name="android.intent.category.BROWSABLE"/>
            <data
                android:scheme="http"
                android:host="vkontakte.ru"
                android:pathPattern="/.*"/>
        </intent-filter>
        <intent-filter>
            <action
                android:name="android.intent.action.VIEW"/>
            <category
                android:name="android.intent.category.DEFAULT"/>
            <category
                android:name="android.intent.category.BROWSABLE"/>
            <data
                android:scheme="https"
                android:host="vk.com"
                android:pathPattern="/.*"/>
        </intent-filter>
        <intent-filter>
            <action
                android:name="android.intent.action.VIEW"/>
            <category
                android:name="android.intent.category.DEFAULT"/>
            <category
                android:name="android.intent.category.BROWSABLE"/>
            <data
                android:scheme="https"
                android:host="vkontakte.ru"
                android:pathPattern="/.*"/>
        </intent-filter>
        <intent-filter>
            <action
                android:name="android.intent.action.VIEW"/>
            <category
                android:name="android.intent.category.DEFAULT"/>
            <category
                android:name="android.intent.category.BROWSABLE"/>
            <data
                android:scheme="vkontakte"
                android:pathPattern="/.*"/>
        </intent-filter>

A: In Kotlin. This will open the app if installed, otherwise the browser will open.
private fun openVk(profileId: String) {
        val uri = Uri.parse("http://vk.com/$profileId")
        val intent = Intent(Intent.ACTION_VIEW, uri)

        startActivity(intent)
    }


text:
Q: Значение по умолчанию при создании объекта String Имеется инициализация:
String[] newStr = new String[3];

Размер объекта newStr типа String принимает значение 3, простым языком говоря, создается массив строк размером 3 с неизвестной ещё длиной.
По умолчанию строки заполняются null-значениями, т.е. по факту:
newStr[0] = 'null';
newStr[1] = 'null';

При попытке внести что-нибудь в newStr[0] (например), к тексту добавляется ещё и 'null'. Добавляем слово "Регистр" и на выходе получаем "nullРегистр".
Вот часть моего кода, попадающего под вопрос:
char array[];

/* ТУТ КОД СОРТИРУЕТ СИМВОЛЫ И ДОБАВЛЯЕТ ИЗ В МАССИВ array[]*/

//добавление символов из переменной ch типа char в объект newStr типа String
public void connect(int i, char ch[]){
    for(int j = 0; j < ch.length; j++) {
        newStr[i] += ch[j];
    }
}

//создание объекта
public void setNewSize(String str[]){
    newStr = new String[str.length];
}

Вопрос:
Как убрать null при инициализации или вообще, как избавиться от null?

A: В элементах массива не 'null' (что это вообще такое?), а null.
Строка "null" - это то, как конвертируется null-ссылка в строку. Инициализируйте массив пустыми строками.
String[] newStr = new String[3];
java.util.Arrays.setAll(newStr, i -> ""); // or java.util.Arrays.fill(newStr, "");

или
String[] newStr = new String[] {"", "", ""};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with "a" div in css I have a bit of a problem, for the header of my website i used a styled div, called a so my http://puu.sh/d9Ax5/2817017ea2.png
but when i try to post a link i can't see it since it is already styled for the header.
Here is my code:
HTML HEADER LIST
a {
text-decoration: none;
color: #fff;
transition: all 0.2s ease-in;
}

CSS

Home

News

Content Packs

About

Help

A: Instead of giving style directly to a, use .nav a.
.nav a {
   text-decoration: none;
   color: #fff;
   transition: all 0.2s ease-in;
}

This will help you to give the styles only to the 'a' inside the nav class and not any other 'a' in your code.


text:
Q: Unable to Consume Webflux Streaming Response in React-Native client I've a reactive streaming api built on spring 5 webflux running on netty server with the following syntax -
@RequestMapping(path = "/customer/messages/stream", method = RequestMethod.POST, produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public Flux<Messages> fetchAllMessagesForCustomer(@RequestBody CustomerRequest)

Now to consume this from my react-native app, I tried using fetch Api but it didn't work because of react-native issue. So I tried with good old xhr
xhr.onreadystatechange = function() {
  console.log("state change.. state: "+ xhr.readyState);

  if(xhr.readyState == 3) {
    var newData = xhr.response.substr(xhr.seenBytes);
    console.log("newData", newData);
    xhr.seenBytes = xhr.responseText.length;
  }
};

This works to some extent but with the following issues

*

*Response consumption is not sync with publishing streams and most of the times multiple streams get combined and thrown to the client.

*xhr.responseText essentially appends all the streams and keeps growing bigger which seems like an anti-pattern as the whole idea was to break down huge responses into smaller chunks and consume them individually.

Is there any good alternative to handle the streaming response in react-native ? Suggestions are welcome.


text:
Q: XSLT: How to find the last space of TEXT but not the comment preceded by 'sup' tag XSLT: How to find the last space of TEXT but not the comment preceded by 'sup' tag
Hi, My xslt code is inserting  even after the comment text also. How to avoid this. With my coding I am getting three  tags in first para, requirement is bk should be at 'Profiling (REP'. Please suggest.
XML:

   <para>Entiostats require hands on work. This shows that Real-time Electrochemical Profiling (REP1).</para>
   <para>Entiostats require hands on work. This shows that Real-time Electrochemical Profiling (REP1).</para>
   <para>Entiostats require hands on work. This shows that Real-time Electrochemical Profiling (REP1).</para>

XSLT:
    <?xml version='1.0'?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="@* | node()">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
   </xsl:template>
   <xsl:template match="text()[following-sibling::*[1][name()='sup' or name()='inf']][not(parent::cross-ref) and not(parent::cross-refs)]">
      <xsl:variable name="varTextBeforeSUP">
         <xsl:value-of select="."/>
      </xsl:variable>
         <xsl:for-each select="tokenize($varTextBeforeSUP,' ')">
               <xsl:choose>
                  <xsl:when test="position()=last()">
                     <xsl:text disable-output-escaping="yes"><</xsl:text>?bk1?<xsl:text disable-output-escaping="yes">></xsl:text>
            <xsl:value-of select="."/>
                  </xsl:when>
                  <xsl:otherwise>
                     <xsl:value-of select="."/><xsl:text> </xsl:text>
                  </xsl:otherwise>
               </xsl:choose>
         </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

Required Out:

<?xml version="1.0" encoding="UTF-8"?>

<para>Entiostats require hands on work. This shows that Real-time Electrochemical Profiling <?bk1?>(REP1).</para>
<para>Entiostats require hands on work. This shows that Real-time Electrochemical Profiling <?bk1?>(REP1).</para>
<para>Entiostats require hands on work. This shows that Real-time Electrochemical Profiling <?bk1?>(REP1).</para>

A: You are almost there. The problem is with this part of the expression...
<xsl:template match="text()[following-sibling::*[1][name()='sup' ...

This is matching text where the first following element is a sup, but that does not meant it is the most immediate sibling. Doing * will ignore text (or comment) nodes that might come first
Try this instead:
<xsl:template match="text()[following-sibling::node()[1][name()='sup' ...

As an aside, if you want to output <?bk1?>, then instead of doing this...
<xsl:text disable-output-escaping="yes"><</xsl:text>?bk1?<xsl:text disable-output-escaping="yes">></xsl:text>

Do this instead:
<xsl:processing-instruction name="bk1" />


text:
Q: Python - BigQuery Temporary Table Is it possible to import data already in Cloud Storage to a temporary table in bigquery using Python? Can I create a BigQuery temporary table in Python and insert data into it?

A: You can only create temporary tables as part of a bigquery script or stored procedure.
What you can do is create tables with a random suffix name and a short expiry. One hour in my example. The example function create the temp table and only need a dataset as a parameter.
from google.cloud import bigquery
import datetime, pytz, random

PROJECT = "myproject"

def get_temp_table(dataset: str, table_name: str = None, project=None) -> bigquery.Table:
    prefix = "temp"
    suffix = random.randint(10000, 99999)
    if not table_name:
        table_name = "noname"

    temp_table_name = f"{dataset}.{prefix}_{table_name}_{suffix}"
    if project:
        temp_table_name = f"{project}.{temp_table_name}"
    tmp_table_def = bigquery.Table(temp_table_name)
    tmp_table_def.expires = datetime.datetime.now(pytz.utc) + datetime.timedelta(
        hours=1
    )

    return tmp_table_def

client = bigquery.Client(project=PROJECT)

tmp_table_def = get_temp_table("mydataset", "new_users", project=PROJECT)
tmp_table_def.schema = [
    bigquery.SchemaField("id", "STRING", mode="REQUIRED"),
    bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
    bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
]
tmp_table = client.create_table(tmp_table_def)  # type: bigquery.Table

data = [
    {"id": "c-1234", "full_name": "John Smith", "age": 39},
    {"id": "c-1234", "full_name": "Patricia Smith", "age": 41},
]

errors = client.insert_rows(tmp_table, data)

print(f"Loaded {len(data)} rows into {tmp_table.dataset_id}:{tmp_table.table_id} with {len(errors)} errors")

A: (this draft don't consider a temporary table, but i think can help.)
I used this with google cloud functions and Python  3.7 and works fine.
from google.cloud import storage,bigquery
import json
import os
import csv
import io
import pandas as pd

def upload_dataframe_gbq(df,table_name):
    bq_client = bigquery.Client()
    dataset_id = 'your_dataset_id'
    dataset_ref = bq_client.dataset(dataset_id)
    table_ref = dataset_ref.table(table_name)
    job = bq_client.load_table_from_dataframe(df, table_ref)
    job.result()  # Waits for table load to complete.
    assert job.state == "DONE"
    table = bq_client.get_table(table_ref)
    print(table.num_rows)

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="your_credentials.json"
client = storage.Client()
bucket = client.get_bucket('your_bucket_name')
blob = bucket.blob('sample.csv')
content = blob.download_as_string()
csv_content = BytesIO(content)
df = pd.read_csv(csv_content, sep=",", header=0 )
table_name = "your_big_query_table_name"
upload_dataframe_gbq(df,table_name)


text:
Q: How to scrape and virtually combine wiki articles? So our company has a large number of internal wiki sites for different departments and I'm looking for a way to unify them. We keep trying to get everybody to use the same wiki but it never works, they keep wanting to create new ones. What I'm wanting to do as an alternative is to scrape each wiki and create a new wiki with articles that has combined information from each source.
In terms of implementation I've looked at Nutch (http://nutch.apache.org/) and (http://scrapy.org/) to do the web crawling and using MediaWiki as the frontend. Basically I'd use the crawler as the front end to scrape each wiki, write some code in the middle (I'm thinking of using Python or Perl) to make sense of it and create new articles, writing to MediaWiki using its API.
Wasn't sure if anybody had similar experience and a better way to do this, trying to do some R&D before I get too deep into the project.

A: I did something very similar a little while back. I wrote a little Python script that scrapes a page hierarchy in our Confluence wiki, saves the resulting html pages locally and converts them into DITA XML topics for processing by our documentation team.
Python was a good choice - I used mechanize for my browsing/scraping needs, and the lxml module for making sense of the xhtml (it has quite a nice range of xml traversing/selection methods. Worked out nicely!

A: Please don't do screenscraping, you make me cry.
If you just want to regularly merge all wikis into one and have them under a "single wiki", export each wiki to XML and import the XML of each wiki into its own namespace of the combined wiki.
If you want to integrate the wikis more tightly and on a live basis, you need crosswiki transclusion on the combined wiki to load the HTML from a remote wiki and show it as a local page. You can build on existing solutions:

*

*the DoubleWiki extension,

*Wikisource's interwiki transclusion gadget.


text:
Q: Inno Setup - how to show a transparent PNG Image? I want to show it on the welcome page.
How is that possible?

A: In 5.5.7 update (28th December 2015) there was 32bit BMP with Alpha Channel function implemented.

The WizardImageFile and WizardSmallImageFile [Setup] section directives now support 32 bit bitmap files with an alpha channel. Use the new WizardImageAlphaFormat [Setup] section directive to specify if the bitmap file has its red, green and blue channel values premultiplied with the alpha channel value or not. Contributed by Honza Rameš via GitHub.

and

Pascal Scripting changes:
   Class TBitmapImage now supports 32 bit bitmap files with an alpha channel. Make sure to set the Bitmap.AlphaFormat property before loading the bitmap file.

http://www.jrsoftware.org/files/is5-whatsnew.htm

A: According to the newsgroup posting at http://news.jrsoftware.org/news/innosetup.code/msg23217.html, PNGs are not supported on Setup Forms and would also be unsupported on the Welcome Page.

A:
However, there is a workaround if your intention is mainly to show a partially transparent image:
the ReplaceColor and ReplaceWithColor properties of the TBitmapImage class allow replacing a color in the image with another color dynamically. The trick is to replace a "dummy" color (e.g. magenta) with the background color of the wizzard:

*

*Convert the png to bmp (this will remove the alpha channel)

*Replace the parts of the image which should be transparent with a color which doesn't occur in the rest of the image (e.g. magenta: #FF00FF)

*Include the image in your ISS:
[Files]
Source: "my\transparent\image.bmp"; DestDir: "{tmp}"; Flags: dontcopy

*Add the image to the wizzard page:
[Code]

procedure InitializeWizard;
var
    ImageFile: String;
    Image: TBitmapImage;
begin
    ImageFile := ExpandConstant('{tmp}\image.bmp');
    ExtractTemporaryFile('image.bmp');
    Image := TBitmapImage.Create(WizardForm);
    with Image do
    begin
        Bitmap.LoadFromFile(ImageFile);
        Parent := WizardForm.WelcomePage;
        Left := 10;
        Top := 10;
        Width := 30;
        Height := 30;
        ReplaceColor := $00FF00FF;                        // Replace magenta...
        ReplaceWithColor := WizardForm.WelcomePage.Color; // ...with the background color of the page
    end;
end;

It is not as pretty as a real alpha transparency but should be fine for simple cases.


text:
Q: How to get Data Feed length from Google Merchant Center Is that possible to get the number of product in a Google Shopping Data Feed ? Actually, we can get all of the information (name, price, category, …) about each products with this Google Merchant Center API code :
function productList() {
  var merchantId = 123456; // Replace this with your Merchant Center ID.
  var pageToken;
  var pageNum = 1;
  var maxResults = 10;

  // List all the products for a given merchant.
  do {
    var products = ShoppingContent.Products.list(merchantId, {
    pageToken: pageToken,
    maxResults: maxResults
    });
  Logger.log('Page ' + pageNum);
  if (products.resources) {
    for (var i = 0; i < products.resources.length; i++) {
      Logger.log('Item [' + i + '] ==> ' + products.resources[i]);
    }
  } else {
    Logger.log('No more products in account ' + merchantId);
  }
  pageToken = products.nextPageToken;
  pageNum++;
  } while (pageToken);
}

But it's take to much time to show all of the products and count them for each clients. Would you have an idea to get the data feed length fastly ? Is there a function ?
Thank you !


text:
Q: Async/await return Promise First of all I apologize for asking question about async/await, as I know there are lots of answers, however after reading many of them, I have not come to a working solution.
There is a search function flickr.js which searches Flickr API for a query, but that function returns Promise, but I need an object
    {query, images : [{photo1}, {photo2}, {photo3}]}
flickr.js function
window.MODULES.Flickr = async query => {
const opts = {
api_key: 'API_KEY'
};
const photos = await window.fetch(
`https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${
  opts.api_key
}&text=${query}&format=json&nojsoncallback=1
`
);
const data = await photos.json();
const pictures = data.photos.photo;
const images = [];

pictures.forEach(picture => {
return images.push({
  id: picture.id,
  url: `https://farm${picture.farm}.staticflickr.com/${picture.server}/${
    picture.id
  }_${picture.secret}_s.jpg`,
  title: picture.title
});
});

return {
  query,
  images
 };
};

and it is called from
ImageFinder.js
function() {
let ImageFinder = (window.CLASSES.ImageFinder = function() {});

 ImageFinder.prototype.search = (query, moduleId) => {
  switch (moduleId) {
   case 'static':
     return window.MODULES.Static(query);
   case 'flickr':
     return window.MODULES.Flickr(query); // Need to return object { query, images : [{photo1}, {photo2}, {photo3}] }

   default:
    throw Error('Search module not found.');
  }
 };
});

A: Your window.MODULES.Flickr(query); returns a promise and the only way you can deal with the result of that promise { query, images } is by resolving the promise. There is no other way around this.
Hence if you want to use the promise result in ImageFinder.prototype.search then you could mark it as async and use await window.MODULES.Flickr(query); in inside your search function to resolve the value.
Moreover, all functions using ImageFinder.prototype.search will also necessarily have to resolve the promise first e.g. using await or then()
var obj = await imageFinder.search(query, moduleId);

A: An async function is an ES7 wrapper for a promise. It is simply a way of expressing the same thing. In order to receive the returned value from the function, it needs to be waited for because it is asynchronous. This would be achieved by using a parent function that is also asynchronous. So let's say I have 2 functions, a and b. They are both asynchronous.
async function a () {
    console.log(await b() );
}

When called, a will print the returned value of b. When an error occurs or the function is returned, the promise is 'resolved' or 'rejected' respectively.
A promise returns its value as a regular function would, with the difference that in order to capture this result, it needs to be waited for, or using specific promise functions like then or catch.
Hope this helps


text:
Q: select one row per group with ifelse in data.table I'm grouping a data.table and want to select from each group the first row where x == 1 or, if such a row does not exist, then the first row with any value in x
d <- data.table(
           a = c(1,1,1,  2,2,  3,3),
           x = c(0,1,0,  0,0,  1,1),
           y = c(1,2,3,  1,2,  1,2)
)

this attempt
d[, ifelse(any(.SD[,x] == 1),.SD[x == 1][1], .SD[1]), by = a]

returns
   a V1
1: 1  1
2: 2  0
3: 3  1

but i expected
   a  x  y
1: 1  1  2
2: 2  0  1
3: 3  1  1

Any ideas how to get it right?

A: We can also do this with .I to return the row index and use that for subsetting the rows.
d[d[, .I[which.max(x==1)], by = a]$V1]
#   a x y
#1: 1 1 2
#2: 2 0 1
#3: 3 1 1

In the current versions of data.table, .I approach is more efficient compared to the .SD for subsetting rows (However, it could change in the future).  This is also a similar post

Here is another option with order (setkey can also be used - for efficiency) the dataset by 'a' and 'x' after grouping by 'a', and then get the first row with head
d[order(a ,-x), head(.SD, 1) ,by = a]
#   a x y
#1: 1 1 2
#2: 2 0 1
#3: 3 1 1

Benchmarks
Initially, we were thinking about benchmarking on > 1e6, but the .SD methods are taking time, so comparing on 3e5 rows using data.table_1.9.7
set.seed(24)
d1 <- data.table(a = rep(1:1e5, 3), x = sample(0:1, 1e5*3,
           replace=TRUE), y = rnorm(1e5*3))

system.time(d1[, .SD[which.max(x == 1)], by = a])
#   user  system elapsed
#  56.21   30.64   86.42

system.time(d1[, .SD[match(1L, x, nomatch = 1L)], by = a])
# user  system elapsed
#  55.27   30.07   83.75

system.time(d1[d1[, .I[which.max(x==1)], by = a]$V1])
#  user  system elapsed
#   0.19    0.00    0.19

system.time(d1[order(a ,-x), head(.SD, 1) ,by = a])
# user  system elapsed
#   0.03    0.00    0.04

A: I think it's a good use case for both match and it's nomatch argument
d[, .SD[match(1L, x, nomatch = 1L)], by = a]
#    a x y
# 1: 1 1 2
# 2: 2 0 1
# 3: 3 1 1

This is basically, in case of no-match, returns 1, and as a result gives you the first row in the group. If there is a multiple match, then it will return the first one- as per your desire

A: Another option (which.max is basically designed to do exactly what you want):
d[, .SD[which.max(x == 1)], by = a]
#   a x y
#1: 1 1 2
#2: 2 0 1
#3: 3 1 1


text:
Q: Can someone explain MySeriesHelper in influxdb, there is not much information availabe and i am new to this Currently, I am writing datapoints using client.write_points, but i want to write datapoints in batches. How should I proceed? Here is my code.
def send_measurement_to_influx(influx_measurement_payload, client):
  try:

    client.write_points(influx_measurement_payload)
    pass
except Exception as e:
    logging.exception("Error while sending measurement {} to influx host", format(str(influx_measurement_payload)),
                      e, exc_info=True)

def timeit(**kwargs):
 def timeit_helper(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        if('metric_name' in kwargs):
            metric_name = kwargs['metric_name']
            client = get_influx_client()
            if(client is not None):
              influx_measurement_payload = [(generate_influx_payload(metric_name, method.__name__,
                                                                   method.__module__, (te-ts) * 1000))]

              send_measurement_to_influx(influx_measurement_payload, client)

        if 'log_time' in kwargs:
            name = kwargs.get('log_name', method.__name__.upper())
            kwargs['log_time'][name] = int((te - ts) * 1000)
        else:
            logging.info('%r  %2.2f ms' % \
                         (method.__name__, (te - ts) * 1000))
        return result
    return timed
return timeit_helper

A: You'd pass the batch size in with the write_points call.
client.write_points(influx_measurement_payload, batch_size=1000)
Docs
https://influxdb-python.readthedocs.io/en/latest/api-documentation.html?highlight=batch#influxdb.InfluxDBClient.write_points
Here they suggest that if the payload contains more than 5000 datapoints you might want to start using the batch option. So batch_size=5000 is something like an upper limit but that would depend on the usecase and is better to derive a good batch_size through benchmarking it.
https://docs.influxdata.com/influxdb/v1.7/guides/writing_data/#writing-points-from-a-file


text:
Q: ValidationGroup doesn´t validate on a button in HTML5 My following code renders an invalid attribute in HTML, ValidationGroup, on a button.
aspx-file:
<button runat="server" id="btnSubmit" onserverclick="btnSubmit_Click" causesvalidation="true" class="button floatRight">

cs-file:
btnSubmit.ValidationGroup = UniqueID;

This renders:
<button validationgroup="ctl00$NoBody$FullContent$ctl03$ctl01" class="button floatRight" id="ctl00_NoBody_FullContent_ctl03_ctl01_btnSubmit" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate('ctl00$NoBody$FullContent$ctl03$ctl01'); __doPostBack('ctl00$NoBody$FullContent$ctl03$ctl01$btnSubmit','')">Subscribe</button>

My problem is that ValidationGroup makes the code invalid in HTML5 and I don´t know how to get around this. It seems like the attribute is only rendered on Button, other elements like Inputs doesn´t render this attribute although it has the same ValidationGroup.
Has someone got around this? Thanks.

A: Give your button a name attribute as well as the ID. Works for me and I was having the exact same issue. I then went back 10 years and remembered the good old Name tag.


text:
Q: Creating an setup.msi packing for asp.net project I need to create an asp.net setup.msi package using VS2010 and after following the instructions here Create ASP.NET deployment package using Web Deployment and Web Setup project (MSI installer)  I am still unable to create a .msi file.  I don't get any errors.
The output folder shows:
  Running aspnet_merge.exe.   Successfully merged '.\TempBuildDir'.
------ Skipped Build: Project: WebSetup1, Configuration: Release ------ Project not selected to build for this solution configuration
========== Build: 7 succeeded or up-to-date, 0 failed, 1 skipped ==========

however, I don't see a .msi file in the output.
How would create an msi deployment package?

A: If you don't need an installer, an option would be to use the "Build Deployment Package" that is built in to VS. It creates a zip file which does not contain source code files. All you would need to do is unzip and deploy the files to the appropriate environment. I find it much easier that creating an msi.


text:
Q: How To Draw line on touch event? Hey i m beginner of objective C Please Help me
i  make following code but not work.....
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

UITouch *touch = [touches anyObject];
if ([touch view] == self.view) {

    CGPoint location = [touch locationInView:self.view];
    loc1 = location;
    CGContextMoveToPoint(context, location.x, location.y);
    NSLog(@"x:%d y:%d At Touch Begain", loc1.x, loc1.y);
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{
    UITouch *touch = [touches anyObject];

        if ([touch view] == self.view)
    {
    CGPoint location = [touch locationInView:self.view];
    CGContextMoveToPoint(context, loc1.x, loc1.y);
    NSLog(@"x:%d y:%d At Touch Move", loc1.x, loc1.y);
    CGContextAddLineToPoint(context, location.x, location.y);
    NSLog(@"x:%d y:%d", location.x, location.y);
}

}

i declare contex in viewdidload method and also try to declare in touch event but not work...
My app Log file look like...

x:0 y:1079934976 At Touch Move Thu Jan 13 11:20:05 .local
  DragDrop[536] :
CGContextAddLineToPoint: invalid context 0x0 2011-01-13 11:20:05.149
  DragDrop[536:207] x:0 y:1079902208 Thu Jan 13 11:20:05 .local
  DragDrop[536] :
CGContextSetRGBStrokeColor: invalid context 0x0 Thu Jan 13 11:20:05
  .local DragDrop[536] :
CGContextDrawPath: invalid context 0x0 Thu Jan 13 11:20:05 .local
  DragDrop[536] :
CGContextMoveToPoint: invalid context 0x0 2011-01-13 11:20:05.199
  DragDrop[536:207] x:0 y:1079934976 At Touch Move Thu Jan 13 11:20:05
  .local DragDrop[536] :
CGContextAddLineToPoint: invalid context 0x0 2011-01-13 11:20:05.200
  DragDrop[536:207] x:0 y:1079885824

A: You typically don't draw directly in the touch detection methods.
Usually, you'd just store new points/lines there and draw all of them in drawRect:. Let's assume you have a custom subclass of UIView which has an instance variable paths of type NSMutableArray and a property currentPath of type UIBezierPath. You could then implement the touch detection and drawRect methods roughly like this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  self.currentPath = [UIBezierPath bezierPath];
  currentPath.lineWidth = 3.0;
  [currentPath moveToPoint:[touch locationInView:self]];
  [paths addObject:self.currentPath];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  [self.currentPath addLineToPoint:[touch locationInView:self]];
  [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
  [[UIColor redColor] set];
  for (UIBezierPath *path in paths) {
    [path stroke];
  }
}

Note that this is simplified a lot. If you draw many lines, performance will suffer and eventually, you'll want to cache the drawing in a bitmap image, but this should get you started.

A: use my this answer , it draw a line (free hand).
Not able to include undo/redo with smooth free hand drawing
hope this helps

A: You need to call CGContextStrokePath after a call to AddLineToPoint.
Make sure to define a stroke path color first though.
CGContextSetRGBStrokeColor(context,0,0,1,1);
CGContextStrokePath(context);


text:
Q: How to increase the horizontal resolution of second smaller screen attached with a laptop screen? I am using a second smaller screen (Dell) with my laptop (acer Aspire 15.6"). The resolution of my laptop is (1366 x 768) but the resolution of the second screen is ( 1024 x 768 ).
Question:  How can i have the same resolution on both the screens i.e. (1366 x 768).
PS: I ran the command xrandr and got the following output
Screen 0: minimum 320 x 200, current 2390 x 768, maximum 8192 x 8192
LVDS1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 345mm x 194mm
   1366x768       60.0*+
   1360x768       59.8     60.0
   1024x768       60.0
   800x600        60.3     56.2
   640x480        59.9
VGA1 connected 1024x768+1366+0 (normal left inverted right x axis y axis) 0mm x 0mm
   1024x768       60.0*
   800x600        60.3     56.2
   848x480        60.0
   640x480        59.9
HDMI1 disconnected (normal left inverted right x axis y axis)
DP1 disconnected (normal left inverted right x axis y axis)

A: You can do this, but the second screen will appear a little fuzzy as the pixels will be interpolated.  You will be telling xrandr to create a scaling factor for the second screen, so that the desired resolution is squished onto the display.
In a terminal, enter the following command
xrandr --output VGA1 --mode 1024x768 --scale 1.334x1 --panning 1366x768


text:
Q: Extending existing .net functionality to iPad I have this sudden out of the blue requirement for extending a part of a desktop's application functionality to the iOS/iPad platform.
At first I had identified the following possible approach.

*

*Recreate/Rewrite the relevant part of the desktop application in Win CF.

This option was a goner from the very onset because the tablet of choice turned out to be an iPad. Of course there is no way (that I know of) of running a Win CF app on iOS/iPhone
The second option was to build a small intranet based web application in asp.net. Now this brings up the following questions.
Q1. Will I require custom third party .net controls specifically designed for browsers that run in an iPhone/iOS?
Q2 Will the application be rendered properly if I use plain asp.net controls? If not, what are the likely problems? (just a quick ballpark explanation)
Any additional insights and help would be of well..great help...as i have not done a lot of mobile applications.`
I intend on finding out the best approach eventually...but any guidance will be invaluable at this stage

A: There is nothing extra that you need to do to make the asp.net controls render in an iPad.  The only thing you need to worry about in your user interface design is that anything that relies on a hover, mouseover, or mousemove event will be unusable on a touch device, because touch devices only send click events, or only send other events in conjunction with a click.

A: What about using Mono.Touch for your .Net needs on iOS ?
Note that you will have to re-implement your UI to use the Cocoa touch UI; but it will all be in C#.Net ! You can deploy your app without touching a single line of Objective-C
Now on to your other questions:

Q1. Will I require custom third party .net controls specifically
  designed for browsers that run in an iPhone/iOS?

It depends what your application is actually doing. iOS can render HTML content just like any other platform, but you may have to design your page specifically to target their small screen sizes and touch-based navigation. There are a few third party frameworks out there that target HTML 5 and that would definitely help you get started quickly but I would not say you have to use it.

Q2 Will the application be rendered properly if I use plain asp.net
  controls? If not, what are the likely problems? (just a quick ballpark
  explanation)

Given that ASP.Net pages are rendered to HTML before being served to the clients, the iOS will have no trouble rendering it (as far as HTML compliance goes of course).

A: If you decide to write a web application, you should take a look at MVC4. They've added a lot of tooling for mobile devices, and even have a mobile project template, and jQuery Mobile is baked in.
EDIT: Here's the link to the MVC4 release notes: http://www.asp.net/whitepapers/mvc4-release-notes
If you really want to stand up a web application with a small subset of features and minimal effort, and you're sure that it's not going to turn into a full-fledged port, you could give Lightswitch a try. I know it seems silly, but they've now got the ability to publish views as an HTML5 application. I recently did that, and it's stupid simple to point it at the right tables and squirt out a simple HTML view. If the result is good enough for what you need, then it's an easy win and won't chew up a lot of time that might be needed elsewhere.
EDIT: Also the link for the Lightswitch HTML client: http://msdn.microsoft.com/en-us/lightswitch/htmlclient


text:
Q: How to determine the ESD level? I would like to know how we determine the IEC 6100-4-2 level for a product.
There are 4 levels, and I don't know what level take.
It's for an encapsulated system with mechanical ground separate from the electrical ground with ESD protection capacitors.

A: When running the ESD test you need to pass all levels off the test, up to the highest for your product. It's not just picking a level and saying I'm compliant. The various levels are defined becaude the behaviour off your product can pass with the highest level but fail with a lower one.


text: Q: How to play HLS on Android < 3.0? I want to play an HLS stream on Android < 3.0. I can not use 3rd party library. I can not port FFMPEG. Is it possible to change the stream container and play the stream using only java code? Any help is greatly appreciated.


text:
Q: Trouble with cin function in C++ language i wrote a small test code:
#include <iostream>
using namespace std;

int main() {
    int a,b,c,d;
    cin>>a>>b,c>>d;
    cout<<a<<" "<<b<<" "<<c<<" "<<d;
    return 0;
}

i gave input:
1 2 3 4

and the output is:
1 2 0 0

but from my view, it should give some error because of cin>>a>>b,c
Why this code is not giving error?

A: comma is an operator, >> between integers is shift operator (cin uses overloaded version of this operator).
so your code is equivalent to:
cin>>a>>b;
c>>d;

both lines are valid, you just ignoring result of second operation

A: According to the comma operator:

In a comma expression E1, E2, the expression E1 is evaluated, its
  result is discarded, and its side effects are completed before
  evaluation of the expression E2 begins (note that a user-defined
  operator, cannot guarantee sequencing).

So your code cin>>a>>b,c>>d; is equivalent to:
cin>>a>>b;
c>>d;     // built-in bitwise shift operator. Note c and d isn't initialized yet.

which is well-formed.

A: cin>>a>>b,c>>d;

should be:
cin>>a>>b>>c>>d;

it does not gave any error because compilers takes your expression as:
cin>>a>>b;
c>>d;  // bit-wise shift operator

A: The comma is a valid operator, it separates expressions that execute one after the other, returning the result of the left-most as the value.
So:
a = b, c = d;

Is equivalent to:
a = b;
c = d;

So in your case you are doing two separate but valid things:
cin >> a >> b, c >> d;

Is equivalent to:
cin >> a >> b;
c >> d;

The c >> d is a valid binary shift operation between integers.


text:
Q: how to display data in a Combobox from MySql database table and other fields in textbox - php I am using phpMyAdmin localhost.
I have a table
Table1: fields are
BatchName, BatchID, Cource, Stream,StreamCode
values:
HS1A-2019   1   HS  Arts    1
HS1C-2019   2   HS  Commerce    3
HS1SC-2019  3   HS  Science     2

Now first I want to display BatchName in a Combobox. secondly, I want while selecting a BatchName from the Combobox it should display respective Course, Stream, StreamCode in textboxes. Thank you in advance.

A: Assuming you already got an array of objects from the SQL query, you can then put the BatchNames into the options of a select element.
All the other information you put into textboxes and hide them using CSS.
Last but not least you write an onchange handler for your select element that will unhide the textboxes.
That's the rough overview of how to tackle this problem, as I assumed you wanted help with the general concept of how to display stuff depending on the selection of your select box using PHP. (That's not possible in PHP and HTML only, you need JS as well)
If your problem was with one of the implementations, please provide an example of what you got so far and where you ran into problems.


text:
Q: Recycled View with Custom Chrome Tab I am trying to open a URL using custom chrome tabs when I click on the card in the RecyclerView. But the customTabsIntent.launchUrl()  wants the first argument to be an Activity.
How do I implement this?
Here is my code:
My ArticleViewAdapter.java
 public class ArticleViewAdapter extends RecyclerView.Adapter<ArticleViewAdapter.ViewHolder> {

        private ImageLoader imageLoader;
        private Context context;
        Intent intent;

        List<Article> articleFeed;

        public ArticleViewAdapter(List<Article> articleFeed, Context context){
            super();
            //Getting all the articles
            this.articleFeed = articleFeed;
            this.context = context;
        }

        @Override
        public ArticleViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.article_view, parent, false);
         Log.i("Errore","in viewholder");
            ViewHolder holder=new ViewHolder(v);
            return holder;
        }

        @Override
        public void onBindViewHolder(ArticleViewAdapter.ViewHolder holder, int position) {

            final Article currentArticle=articleFeed.get(position);
            imageLoader = MySingleton.getInstance(context).getImageLoader();
            imageLoader.get(currentArticle.getImageUrl(), ImageLoader.getImageListener(holder.image, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

            holder.image.setImageUrl(currentArticle.getImageUrl(), imageLoader);
            holder.title.setText(currentArticle.getTitle());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
    // set toolbar color and/or setting custom actions before invoking build()
                    CustomTabsIntent customTabsIntent = builder.build();

//THE ERROR OCCURES HERE
                    customTabsIntent.launchUrl(context,Uri.parse(currentArticle.getURL()));
                    Log.i("Errore",currentArticle.getURL());
                }
            });

        }

        @Override
        public int getItemCount() {
            return articleFeed.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder{

            TextView title;
            NetworkImageView image;
            public ViewHolder(View itemView) {
                super(itemView);
                title=(TextView)itemView.findViewById(R.id.heading);
                image=(NetworkImageView)itemView.findViewById(R.id.image);
            }

        }
    }

My NewsActivity.java
public  class NewsActivity extends AppCompatActivity {

    private static String API_KEY="xxxxxxxxxxx";
    private List<Article> listOfArticles;
    static Article curArticle ;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;
    private JSONArray jsonArticles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        Intent intent=getIntent();
        String id=intent.getStringExtra("id");
        String sortBy=intent.getStringExtra("sortBy");
        Toast.makeText(NewsActivity.this, id, Toast.LENGTH_SHORT).show();

        recyclerView = (RecyclerView) findViewById(R.id.recycview);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        //Initializing our article list
        listOfArticles = new ArrayList<>();
        final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);

        //Creating a newe json object request
        Log.i("Errore","https://newsapi.org/v1/articles?source=" + id + "&sortBy="+sortBy+"&apiKey=" + API_KEY);
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, "https://newsapi.org/v1/articles?source=" + id + "&sortBy="+sortBy+"&apiKey=" + API_KEY, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                Log.i("Errore","getting json");
                loading.dismiss();
                try {
                    jsonArticles=response.getJSONArray("articles");

                    for(int i=0;i<jsonArticles.length();i++){

                        Article article=new Article();
                        JSONObject jsonObject=jsonArticles.getJSONObject(i);
                        article.setTitle(jsonObject.getString("title"));
                     //   Log.i("Errore",jsonObject.toString());
                        article.setImageUrl(jsonObject.getString("urlToImage"));
                        article.setURL(jsonObject.getString("url"));
                        listOfArticles.add(article);

                    }

                    //Finally initializing our adapter
                    adapter = new ArticleViewAdapter(listOfArticles,NewsActivity.this);

                    //Adding adapter to recyclerview
                    recyclerView.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.i("Errore","failed getting json");
                }

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

            }
        });

        //Adding request to the queue
        MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }

}

I keep getting the error :
Wrong 1st argument type.Found:android.content.Context, required: android.app.Activity

What should I do to fix it?
Is there a better way to to use OnClick that allows custom chrome tabs?

A: customTabsIntent.launchUrl(MainActivity.activity,Uri.parse(currentArticle.getURL()));
                    Log.i("Errore",currentArticle.getURL());

in your Main Activity do this
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     activity=this;

}


text:
Q: For every abelian sheaf, $F(\phi)=\{ 0 \}$? In the book 'Sheaf theory' by Tennison, exercise 1.9 asks to prove that if $G$ is an abelian sheaf then $G(\phi)=\{ 0 \}$. I have been unsuccessfully trying to prove this and the following seems to be a counter example to me :

Let X be the space consisting of a singleton set {p}. Define an abelian sheaf $G$ by : $G(X)=\{ 0 \} $ , $G(\phi)=\mathbb{Z}$, and the restriction maps to be : $\rho^{X}_{X}=0$, $\rho^{\phi}_{\phi}=id_{\mathbb{Z}}$, $\rho^{X}_{\phi}=0$.

All the sheaf axioms seem to be valid. Where am I going wrong ? Thanks.


text:
Q: How does one build 'where' clause dynamically when projecting to Dto? When projecting results of the joins onto DTO using EF, how does one dynamically build a "where" clause? In NHibernate it was really easy to do this, but I cannot figure out how to do this with Entity Framework.
Just to clarify, I don't want to filter objects, I want sql to be built.
This is what I am trying to do.
private async Task<List<InvoiceInfo>> GetDataWithManualProjection()
{
    var query = (from i in db.Invoices
                 join cj in db.CustomerJobs on i.CustomerJobID equals cj.ID
                 join c in db.Customers on cj.CustomerId equals c.ID
                 let invoice = i
                 let customer = c
                 let customerJob = cj
                 select new InvoiceInfo()
                {
                    Number = invoice.InvoiceNumber,
                    Balance = invoice.InvoiceBalance,
                    PrePay = customer.PrepaymentBalance
                })
                .AsQueryable();

                BuildWhereClause(filter, query);

               return await q.ToListAsync();
}

private void BuildWhereClause(InvoicesFilter filter, ref IQueryable<Invoice> q)
{

    if (string.IsNullOrWhiteSpace(filter.ClientName) == false)
    {
        switch (filter.ClientNameFilterOptions)
        {
            case ClientNameFilterOptions.Contains:
                q = q.Where(x => x.ClientName.Contains(filter.ClientName));
                break;
            case ClientNameFilterOptions.EqualTo:
                q = q.Where(x => x.ClientName == filter.ClientName);
                break;
            case ClientNameFilterOptions.StartsWith:
                q = q.Where(x => x.ClientName.StartsWith(filter.ClientName));
                break;
        }
    }

    if (filter.InvoiceBalance.HasValue)
    {
        var invoiceBalance = filter.InvoiceBalance.Value;
        switch (filter.InvoiceBalanceComparisonOperator)
        {
            case ComparisonOperator.EqualTo:
                q = q.Where(x => x.InvoiceBalance == invoiceBalance);
                break;
            case ComparisonOperator.GreaterThan:
                q = q.Where(x => x.InvoiceBalance > invoiceBalance);
                break;
            case ComparisonOperator.GreatherThanOrEqualTo:
                q = q.Where(x => x.InvoiceBalance >= invoiceBalance);
                break;
            case ComparisonOperator.LessThan:
                q = q.Where(x => x.InvoiceBalance < invoiceBalance);
                break;
            case ComparisonOperator.LessThanOrEqualTo:
                q = q.Where(x => x.InvoiceBalance <= invoiceBalance);
                break;
        }
    }

    if (string.IsNullOrWhiteSpace(filter.Address) == false)
    {
        q = q.Where(x => x.CustomerJob.BillingAddress1 == filter.Address);
    }

    if (string.IsNullOrWhiteSpace(filter.City) == false)
    {
        q = q.Where(x => x.CustomerJob.BillingCity == filter.City);
    }

    if (string.IsNullOrWhiteSpace(filter.ZipCode) == false)
    {
        q = q.Where(x => x.CustomerJob.BillingZip == filter.ZipCode);
    }

    if (filter.InvoiceFrequency != InvoiceFrequency.NotSet)
    {
        q = q.Where(x => x.InvoiceFrequency == filter.InvoiceFrequency);
    }

    if (filter.InvoiceStatus != InvoiceStatus.NotSet)
    {
        q = q.Where(x => x.Status == filter.InvoiceStatus);
    }

    if (filter.StartDate.HasValue)
    {
        q = q.Where(x => x.InvoiceStartDate >= filter.StartDate.Value);
    }

    if (filter.EndDate.HasValue)
    {
        q = q.Where(x => x.InvoiceEndDate <= filter.EndDate.Value);
    }

    if (filter.PaymentMethod != MethodOfPayment.NotSet)
    {
        q = q.Where(x => x.MethodOfPayment == filter.PaymentMethod);
    }

    if (filter.InvoiceNumbers.Any())
    {
        q = q.Where(x => filter.InvoiceNumbers.Contains(x.InvoiceNumber));
    }

    if (string.IsNullOrWhiteSpace(filter.LineItemDescription) == false)
    {
        q = q.Where(x => x.LineItems.Any(l => l.InvoiceDescription.Contains(filter.LineItemDescription)));
    }

    if (filter.HasCCOnFile)
    {
        throw new NotImplementedException();
    }
}

A: You can apply the Invoice filter in advance and use the resulting IQueryable inside the LINQ query:
var invoices = db.Invoices.AsQueryable();
BuildWhereClause(filter, ref invoices);

var query = (from i in invoices
             join cj in db.CustomerJobs on i.CustomerJobID equals cj.ID
             ...

A: Your private method needs to have the following syntax:
 private  IQueryable<InvoiceInfo> BuildWhereClause(Expression<Func<InvoiceInfo,bool>> filter,
                               IQueryable<InvoiceInfo> q)
 {
    return q.Where(filter);
 }

And you don't need to call AsQueryable method at the end of your query
Update
If you want to apply the filter to your entity and not to the projection, then you need to compose your query in several steps, eg:
IQueryable<Invoice> query= db.Invoices;
BuildWhereClause(filter,ref query);
var result= (from i in query
             join cj in db.CustomerJobs on i.CustomerJobID equals cj.ID
             join c in db.Customers on cj.CustomerId equals c.ID
             select new InvoiceInfo()
            {
                Number = i.InvoiceNumber,
                Balance = i.InvoiceBalance,
                PrePay = c.PrepaymentBalance
            });

Also, there is not need to use let clause in your query, every time you are using it, an extra projection will be applied.


text:
Q: invoking method via reference variable I'm trying to understand how System.out can invoke println(). All the searches  say System.out is an instance of PrintStream class therefore it can invoke a method in that class.
BUT...
When I try to duplicate this with the following a NullPointerException results.
public class Main {
    public static void main(String[] args){
        Tasker.calc.add(1, 2);
    }
}

class Tasker{
    static Calc calc;
}

class Calc {
    public void add(int x, int y){
        System.out.println(x+y);
    }
}

Isn't Tasker.calc a similar instance of Calc?
How is System.out not a NullPointerException?
To be clear, this is not a question about NullPointerException... this is a question about why System.out doesn't require initialization.
Thanks a bunch!

A: Why doesn't System.out require initialisation?  Well ...
Deep inside the System class, there's a method called initializeSystemClass which the JVM calls. It sets System.out to the right value, so you don't have to.
Note that System.out is NOT an instance of PrintStream - it's a REFERENCE to an instance of PrintStream.

A: You haven't _initialized calc.  You could have written
static Calc calc = new Calc();

and it would have worked (depending on the definition of Calc).

A: As @LouisWasserman points out, the reason that your code gives an NPE is that you haven't initialized the calc variable.  As a result, it gets default initialized to null.  The solution: initialize it!
But the deeper question is why System.out doesn't need to be initialized.  That is because the Java runtime initializes it behind the scenes to point to a PrintStream that refers to your application's (external) standard output.

*

*You don't need to initialize System.out because the system does it.  The javadocs say so.

*You couldn't initialize it in the nromal way because System.out is declared as final.  (But there is System.setOut(...))

*Even with System.setOut(...) there is no way for an application to find out what System.out should be set to.  (Consider this java Test | wc )


text:
Q: Is there a name for position and dimension in the mathematics I'm a Software Architect who looking for a corresponding term for position and dimensions of an object at the sametime.
Is there a word or term for that in geometry or analytic geometry?

A: No, there is no such term. Dimensionality would depend on the frame of reference and the attitude/orientation of the object. Is dimensionality taken with respect to the object, or to the reference frame?
In general, in mathematical modeling you can associate with an object of interest a concept known as a state space. This is simply a set of variables that describe properties of the object, e.g. mass, acceleration, position, rotation, and so forth. Most of the time, physical spatial dimensionality is not considered for rigid objects, because those dimensions don't change with respect to the object; however, for things like morphing structures, these do change, and are considered in the state space representation.


text:
Q: Visual Studio Tab change color? Can I change back/fore color of tabs in Visual Studio 2008?

A: Now it can be done by Visual studio Productivity Power Tools Extension.
The extension can be installed through Tools => Extensions and Updates.
After installation restart Visual Studio and go to:
Options => Productivity Power Tolls => Custom Document Well, then you can choose Color tabs by project or by regular expression.

A: this visual studio 2010 addin will allow the tabs to be coloured by a specific project type- so everything in 1 project has the same colour.
read more about it and download it http://visualstudiogallery.msdn.microsoft.com/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef

A: You can change color and shape of tabs in VS 2008/2010 with Tabs Studio add-in (developed by me).


text:
Q: Progressbar in angular I want to make Progressbar in Angular.js in decimal format, simple format, times based Progressbar. Someone could pls help !
E.g.
Start Timer {{ counter }}/{{ max }} = {{ (counter/max)*100 }}%
Start Timer 20/30 = 66.66666666666666%
Here is example.js:
angular.module('plunker', ['ui.bootstrap']);

var ProgressDemoCtrl = function ($scope) {
    $scope.max = 200;
    $scope.random = function () {
        var value = Math.floor((Math.random() * 100) + 1);
        var type;

        if (value < 25) {
            type = 'success';
        } else if (value < 50) {
            type = 'info';
        } else if (value < 75) {
            type = 'warning';
        } else {
            type = 'danger';
        }

        $scope.showWarning = (type === 'danger' || type === 'warning');
        $scope.dynamic = value;
        $scope.type = type;
    };

var app = angular.module('plunker', ['ui.bootstrap']);

app.controller('ProgressDemoCtrl', function ($scope) {
    $scope.value = 40;
    $scope.state = "progress-bar-success";
    $scope.myStyle = {width: $scope.value + '%'};
});

$scope.random();

$scope.randomStacked = function() { $scope.stacked = [];

var types = ['success', 'info', 'warning', 'danger']; for (var i = 0, n = Math.floor((Math.random() * 4) + 1); i < n; i++) { var index = Math.floor((Math.random() * 4));

$scope.stacked.push({ value: Math.floor((Math.random() * 30) + 1),

type: types[index] }); } }; $scope.randomStacked(); };

var app = angular.module('progressApp',['nprogress']); var MainCtrl = function($scope,ngProgress){ }

A: I use this round progress ba directive, works pretty well:
http://www.youtube.com/watch?v=w2qrYL0Le24
https://github.com/angular-directives/angular-round-progress-directive
If you need a rectangular one give me a buzz I, have a custom directive implemented.
If you need two decimal numbers you only have to adjust the font size.
Test with two decimals:

Code to change (configuring ang:roundprogress directive)
data-round-progress-label-font="80pt Arial"

Whole markup
<div ang:round:progress data-round-progress-model="roundProgressData"
                        data-round-progress-width="500"
                        data-round-progress-height="500"
                        data-round-progress-outer-circle-width="40"
                        data-round-progress-inner-circle-width="10"
                        data-round-progress-outer-circle-radius="200"
                        data-round-progress-inner-circle-radius="140"
                        data-round-progress-label-font="80pt Arial"
                        data-round-progress-outer-circle-background-color="#505769"
                        data-round-progress-outer-circle-foreground-color="#12eeb9"
                        data-round-progress-inner-circle-color="#505769"
                        data-round-progress-label-color="#fff"></div>


text:
Q: What's the best way of implementing a finite state machine in C++ I've seen a number of different approaches to implementing a FSM.
Switch-case
Function pointer tables
object oriented programming
My question is what are the main factors I should be aware of when choosing one implementation over the other. In my case I only have 4 states with at most 2 transitions at each state. My main goal is for the implementation to be easily readable for someone else to modify.
Thanks

A: Please take a look at method-based FSA implementation
// abstract FSA
template<class C, typename T>
struct fsa {
    struct state_t {
        typedef state_t (C::*type)(T);
        inline state_t(type f) : state(f) {}
        type state;
    };

    fsa(state_t init) : state(init) {}

    inline bool next(T val) {
        state = (static_cast<C*>(this)->*state.state)(val);
        return state.state != nullptr;
    }
private:
    state_t state;
};

//concrete FSA implementation
struct myfsa : fsa<myfsa,char> {
    inline myfsa() : fsa<myfsa, char>(&myfsa::start) {}
    state_t start(char) {
        std::cout << "start" << std::endl;
        return &myfsa::state1;
    }
    state_t state1(char) {
        std::cout << "state1" << std::endl;
        return &myfsa::state2;
    }
    state_t state2(char) {
        std::cout << "state2" << std::endl;
        return nullptr;
    }
    char get() { return ' '; /*TODO*/ }
    void run() {
        while(next(get()));
    }
};


text:
Q: Generic argument method ? super Why can NOT be added a new Object into a List if with this type is supposed to be able to add any supertype of Apple?
import java.util.List;
import java.util.ArrayList;
class Apple{}
public class Macintosh extends Apple {
    public static void main(String[] munch){
        List<Apple> a = new ArrayList<Apple>();
        basket(a);
    }
    static void basket(List<? super Apple> list){ list.add(new Object());}
}

If we change argument to List list, of course it works :s

class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
public class Mixer<A extends Animal>{
    public <C extends Cat> Mixer<? super Dog> useMe(A a, C c){
        return new Mixer<Animal>();
    }
}

Why can we use Mixer in return time if the compiler in the case before didn't know about the Class of the object, now is because of is a class ?¿?

A: You are trying to add to a List of Apples something that is not an Apple (Object is not a sublcass of Apple). Hence, the compilation error.

A: You cannot add anything other than Apple and its subtypes to a List<? super Apple>, because the ? means 'some type' not 'any type'.  It is a list of instances of some type that is either Apple or a supertype of Apple, and there is no way of knowing which exact type the ? means.
I'd suggest avoiding these constraints if you can, they don't help very often and they can easily lead to confusion.

A: As noted by others, wildcard types are existentially quantified types, not universally quantified. This means that, when using a variable of a type with wildcards, you can assign any matching type you wish when you are writing to it, but you cannot assume any particular type when you read from the variable. When writing, you control the choice, but when reading, others choose it for you.
More Detailes

*

*You have full control when writing. The return value of a method is written to inside its body, in a return statement. Its parameters are written to where you invoke the method. You can happily assign a particular type to a wildcard return statement or pass a particular type to a wildcard method parameter.

*The choice is forced upon you when reading. The return value of a method is read where you invoke the method. Its parameters are read inside its body, where you define the method. You face difficulties inside basket() when you try to use the passed list.

If we change argument to List list, of course it works :s

That's a totally different story. List is a raw type. As you discovered yourself, you can do unsafe things, like adding an Orange or any other Object to a List<Apple> if you use raw types. Java supports raw types mostly for historical reasons like backward compatibility. They are unsound by design. If you use raw types in this fashion you are likely to get a ClassCastExceptions later:
    List<Apple> a = new ArrayList<Apple>();
    basket(a);
    for (Apple apple : a) {     // Is not assignable to Apple, throws ClassCastException
        System.out.println(apple);
    }


text:
Q: Getting JQuery UI's datepicker widget as a EmberJS Mixin to work In this JsFiddle : http://jsfiddle.net/maxl/mCXND/
(copied and modified from http://jsfiddle.net/ud3323/XMgwV/)
I try to create an Ember DatePicker based on JQuery's.
The first problem I run into is this line :
var ui = jQuery.ui[this.get('uiType')](options, this.get('element'));

jQuery.ui[this.get('uiType')] doesn't return a function, so I suppose that the solution
that I started with works for some jQueryUI widgets, but not all.
I would like a solution that will work for all JQuery-UI widgets,
and in particular JQueryUI's Datepicker.
Thanks

A: If you look at the jqueryui code, you see that some of them are invoked as a function, others not. You can solve it using this:
var ui;
if (typeof jQuery.ui[this.get('uiType')] === 'function') {
   ui = jQuery.ui[this.get('uiType')](options, this.get('element'));
} else {
   ui = this.$()[this.get('uiType')](options);
}

working example: http://jsfiddle.net/PzsrT/7/

A: One more thing about jQuery UI's datepicker widget as a EmberJS Mixin.
If you want to supply a callback function to handle the beforeShowDay event, you will raise this error:
Uncaught TypeError: Cannot read property '0' of undefined

even if your callback function (in your ember view) return an array, like it's specified in the jqueryui doc
  beforeShowDay: function(date){
    some code...
    return [true, ''];
  };

This happens because nothing is returned after the callback.call in the _gatherEvents function
  _gatherEvents: function(options) {
    var uiEvents = this.get('uiEvents') || [], self = this;

    uiEvents.forEach(function(event) {
      var callback = self[event];

      if (callback) {
        // You can register a handler for a jQuery UI event by passing
        // it in along with the creation options. Update the options hash
        // to include any event callbacks.
        options[event] = function(event, ui) { callback.call(self, event, ui); };
      }
    });
  }

I fix this by adding a return statement before the callback.call.
_gatherEvents: function(options) {
    var uiEvents = this.get('uiEvents') || [], self = this;

    uiEvents.forEach(function(event) {
      var callback = self[event];

      if (callback) {
        // You can register a handler for a jQuery UI event by passing
        // it in along with the creation options. Update the options hash
        // to include any event callbacks.
        options[event] = function(event, ui) { return callback.call(self, event, ui); };
      }
    });
  }

working example http://jsfiddle.net/thibault/qf3Yu/


text:
Q: Passing session to another sub-domain In C# how can I pass a Session from one sub domain to another sub domain?
For instance I am using IIS localhost and I tried to send value from
http:\\localhost\site1 to http:\\localhost\site2
using the below way
In site1

Session["test"] = "My value";

In site2

Response.Write(Convert.ToString(Session["test"]));

The above method worked fine to pass values from one page to another but I need values to be passed from one sub domain to another sub domain i.e. one IIS web application to another IIS web application.

A: You can't do that with the default session state providers.  You will have to roll your own using the provider model (SessionStateStoreProvider) see: here
You could also NOT use the provider model and do something like this
EDIT
HACK: I guess you can do that. here

A: I'm doing something similar by exchanging the session ID (and the associated settings) through a common database.
I.e.

*

*site 1 writes its session ID to a database table, together with all required associated settings like test in your above example.

*site 1 calls an URL on site 2, passing the session ID of site 1 as a query string parameter.

*site 2 picks up the session ID that is passed as the query string parameter.

*site 2 uses the passed session ID as a lookup key in the database table to fetch the value of test ("My value" in your example)

To enhance security, I also write a timestamp to the table and let site 2 only read those rows where the session ID and the timestamp (with some tolerance) matches. In addition, site 2 deletes the record after reading it.
Of course this is not straight forward and possibly not 100% of what you want to achieve, it may be some idea to build upon, though.

A: A session is specific to the application.  Can you post from site1 to site2 (via JQuery for example).  The post will allow you to send data (hidden).  Then assign the querystring in your post to a new session variable on site2.


text:
Q: How to extract entire packet from skb including ethernet header, ip, and tcp plus pay load in poll method of device driver in r8169 driver from realtek it does
    rx_buf = page_address(tp->Rx_databuff[entry]);
    dma_sync_single_for_cpu(d, addr, pkt_size, DMA_FROM_DEVICE);
    prefetch(rx_buf);
    skb_copy_to_linear_data(skb, rx_buf, pkt_size);<----//Do I get packet at this????
    skb->tail += pkt_size;
    skb->len = pkt_size;
    dma_sync_single_for_device(d, addr, pkt_size, DMA_FROM_DEVICE);
    //csum...
    skb->protocol = eth_type_trans(skb, dev);
    napi_gro_receive(&tp->napi, skb);

this is inside rtl_rx function called from poll of driver. I like to know in above code how can I extract the entire packet from skb at which line afterwards.
I assume at this line
             skb_copy_to_linear_data(skb, rx_buf, pkt_size);

I should have a packet, but like to know the correct way I can create a kmalloc obect like
         void   *packet=   kmalloc(....sizeof(struct ethhdr)+sizeof(struct iphdr)+sizeof(tcphdr))

and read ethernet ip and tcp headers from void *packet
How to achieve it
Or should I simple do skb_netword_header, skb_tcp_header, etc... to extract the headers and payload from skb after it get populated in above lines,
or can I simply cast as
              rx_buf = page_address(tp->Rx_databuff[entry]);
              struct ether_header ethhdr_of_packet=(struct eher_header *) rx_buf;

Should it work?

A: The highlighted line (the one with skb_copy_to_linear_data()) indeed copies entire packet data from the buffer in the driver-internal Rx ring (rx_buf) to the data buffer of the skb.
static inline void skb_copy_to_linear_data(struct sk_buff *skb,
                       const void *from,
                       const unsigned int len)
{
    memcpy(skb->data, from, len);
}

Casting the rx_buf pointer to Ethernet header should be OK, too. However, the purpose of accessing the packet header like this is rather vague in the question of yours. Are you trying to just print ("dump") the packet or do you intend to copy the packet data to a completely different buffer to be consumed elsewhere?


text:
Q: Why is my for loop skipping certain values in my python index generator? I am writing a python search engine that reads a list of jokes, tokenizes the words, creates an index (key:words,values:document ids of the document(s) the word appears in, and then searches the index. The tokenization and search methods work fine, but my indexing method is giving me issues and I can't figure out why.
Code
def create_index(tokens):
    lst = -1
    duplicates =[]
    index = {}
    docnum = len(tokens)
    for list in tokens:
        lst += 1
        xst = -1
        for x in list:
            xst += 1
            element = tokens[lst][xst]
            value = ""
            elin = 0
            if element not in duplicates:
                for r in range(docnum):
                    if element in tokens[r]:
                        if elin > 0:
                            value += " "
                        value += "%d" % r
                        elin += 1

                        print(tokens[r])
                        print(r)
                if len(value) > 1:
                    index[element] = value.split()
                    duplicates += element
                else:
                    index[element] = value
                    duplicates += element
    return index

the print statements are there just so I could see where the problem lies, and indeed I saw that certain r values in the for loop are being skipped entirely. I'm pretty sure I'm not modifying what I'm iterating over, which I believe is what usually causes for loops to skip.
Input (tokens)
[['What', 'did', 'the', 'little', 'boy', 'tell', 'the', 'game', 'warden', 'His', 'dad', 'was', 'in', 'the', 'kitchen', 'poaching', 'eggs'], ['What', 'do', 'you', 'call', 'a', 'chicken', 'crossing', 'the', 'road', 'Poultry', 'in', 'motion'], ['What', 'do', 'you', 'call', 'it', 'when', 'a', 'cat', 'sues', 'another', 'cat', 'A', 'Clawsuit'], ['What', 'does', 'an', 'envelope', 'say', 'when', 'you', 'lick', 'it', 'Nothing', 'It', 'just', 'shuts', 'up'], ['How', 'can', 'you', 'tell', 'the', 'ocean', 'is', 'friendly', 'It', 'waves'], ['What', 's', 'black', 'white', 'green', 'and', 'bumpy', 'A', 'pickle', 'wearing', 'a', 'tuxedo'], ['When', 'was', 'meat', 'so', 'high', 'When', 'the', 'cow', 'jumped', 'over', 'the', 'moon'], ['What', 'happened', 'to', 'the', 'wind', 'It', 'blew', 'away'], ['What', 'starts', 'with', 'T', 'is', 'full', 'of', 'T', 'and', 'ends', 'with', 'T', 'A', 'teapot'], ['What', 'is', 'a', 'hermit', 'A', 'girl', 's', 'baseball', 'glove'], ['What', 'does', 'a', 'television', 'have', 'in', 'common', 'with', 'a', 'rabbit', 'His', 'ears'], ['What', 'did', 'the', 'crop', 'say', 'to', 'the', 'farmer', 'Why', 'are', 'you', 'always', 'picking', 'on', 'me'], ['What', 'did', 'the', 'guy', 'say', 'when', 'he', 'walked', 'into', 'the', 'bar', 'Ouch'], ['How', 'is', 'a', 'locksmith', 'like', 'a', 'typewritter', 'They', 'both', 'have', 'a', 'lot', 'of', 'keys'], ['What', 'has', 'four', 'legs', 'and', 'goes', 'booo', 'A', 'cow', 'with', 'a', 'cold'], ['What', 'is', 'a', 'caterpillar', 'afraid', 'of', 'A', 'dogerpillar'], ['Who', 'has', 'the', 'strongest', 'underwear', 'Arnold', 'Shortsineger'], ['Why', 'did', 'the', 'elephant', 'decide', 'not', 'to', 'move', 'Because', 'he', 'couldn', 't', 'lift', 'his', 'trunk'], ['Which', 'are', 'the', 'stronger', 'days', 'of', 'the', 'week', 'Saturday', 'and', 'Sunday', 'The', 'rest', 'are', 'weekdays'], ['Which', 'runs', 'faster', 'hot', 'or', 'cold', 'Hot', 'Everyone', 'can', 'catch', 'a', 'cold'], ['Why', 'did', 'the', 'strawberry', 'cross', 'the', 'road', 'Because', 'his', 'mother', 'was', 'in', 'a', 'jam'], ['How', 'do', 'you', 'keep', 'a', 'lion', 'from', 'charging', 'Take', 'away', 'its', 'credit', 'cards'], ['What', 'do', 'you', 'call', 'a', 'cow', 'with', 'a', 'twitch', 'Beef', 'jerky'], ['What', 'is', 'the', 'best', 'way', 'to', 'keep', 'water', 'from', 'running', 'Don', 't', 'pay', 'the', 'water', 'bill'], ['Where', 'do', 'cows', 'go', 'to', 'have', 'fun', 'The', 'moovies'], ['What', 'time', 'was', 'is', 'when', 'the', 'elephant', 'sat', 'on', 'a', 'chair', 'Time', 'to', 'get', 'a', 'new', 'chair'], ['What', 'did', 'the', 'flower', 'say', 'to', 'the', 'bike', 'Petal'], ['Why', 'do', 'we', 'not', 'tell', 'secrets', 'in', 'a', 'corn', 'patch', 'Too', 'many', 'ears'], ['What', 's', 'yellow', 'and', 'writes', 'A', 'ball', 'point', 'banana'], ['Did', 'people', 'laugh', 'when', 'the', 'lady', 'fell', 'on', 'the', 'ice', 'No', 'but', 'the', 'ice', 'cracked', 'up'], ['What', 'word', 'is', 'always', 'spelled', 'incorrectly', 'Incorrectly'], ['What', 'should', 'you', 'do', 'if', 'your', 'dog', 'is', 'missing', 'Check', 'the', 'Lost', 'and', 'Hound'], ['What', 'have', 'you', 'seen', 'that', 'you', 'will', 'never', 'see', 'again', 'Yesterday'], ['Why', 'did', 'the', 'turkey', 'cross', 'the', 'road', 'To', 'get', 'to', 'the', 'chicken'], ['Why', 'was', 'Cinderella', 'Late', 'for', 'the', 'ball', 'She', 'forgot', 'to', 'swing', 'the', 'bat'], ['How', 'can', 'you', 'tell', 'there', 's', 'a', 'hippo', 'in', 'your', 'oven', 'The', 'oven', 'door', 'won', 't', 'close'], ['What', 'do', 'you', 'get', 'when', 'you', 'cross', 'a', 'shark', 'and', 'Flipper', 'A', 'fat', 'shark'], ['What', 'did', 'the', 'lamp', 'say', 'to', 'the', 'other', 'lamp', 'You', 'turn', 'me', 'on'], ['What', 'did', 'the', 'sidewalk', 'do', 'when', 'he', 'heard', 'a', 'funny', 'joke', 'He', 'cracked', 'up'], ['Why', 'did', 'the', 'chicken', 'cross', 'the', 'road', 'He', 'wanted', 'to', 'prove', 'to', 'the', 'armadillo', 'that', 'it', 'could', 'be', 'done'], ['Why', 'did', 'the', 'dalmation', 'need', 'glasses', 'He', 'was', 'seeing', 'spots'], ['What', 'did', 'the', 'book', 'say', 'to', 'the', 'page', 'Don', 't', 'turn', 'away', 'from', 'me'], ['What', 'do', 'you', 'call', 'a', 'pig', 'in', 'a', 'butcher', 'shop', 'A', 'pork', 'chop'], ['In', 'France', 'what', 'do', 'frogs', 'eat', 'French', 'Flies'], ['What', 'is', 'yellow', 'and', 'wears', 'a', 'mask', 'The', 'Lone', 'Lemon'], ['What', 'do', 'astronauts', 'eat', 'for', 'dinner', 'Launch', 'meat'], ['Why', 'is', 'the', 'little', 'duck', 'always', 'so', 'sad', 'Because', 'he', 'always', 'sees', 'a', 'bill', 'in', 'front', 'of', 'his', 'face'], ['What', 'did', 'they', 'digital', 'clock', 'say', 'to', 'its', 'mom', 'Look', 'mom', 'no', 'hands'], ['What', 'is', 'the', 'best', 'way', 'to', 'raise', 'a', 'child', 'In', 'an', 'elevator'], ['What', 'is', 'always', 'behind', 'the', 'time', 'The', 'back', 'of', 'the', 'clock'], ['What', 's', 'green', 'and', 'sings', 'Elvis', 'Parsley'], ['What', 'has', '10', 'letters', 'and', 'starts', 'with', 'gas', 'An', 'automobile'], ['Why', 'did', 'they', 'bury', 'the', 'battery', 'Because', 'it', 'was', 'dead'], ['Why', 'did', 'the', 'chicken', 'go', 'to', 'the', 'library', 'To', 'check', 'out', 'a', 'bawk', 'bawk', 'bawkbawk'], ['If', 'a', 'woodchuck', 'had', 'a', 'name', 'what', 'would', 'it', 'be', 'Chuck', 'Wood'], ['How', 'do', 'you', 'catch', 'a', 'squirrel', 'Climb', 'a', 'tree', 'and', 'act', 'like', 'a', 'nut'], ['What', 'did', 'one', 'penny', 'say', 'to', 'the', 'other', 'Let', 's', 'get', 'together', 'and', 'make', 'some', 'sense'], ['Why', 'don', 't', 'lobsters', 'share', 'Because', 'they', 'are', 'shellfish'], ['Why', 'does', 'the', 'man', 'wish', 'he', 'could', 'be', 'a', 'guitar', 'player', 'in', 'a', 'room', 'full', 'of', 'beautiful', 'girls', 'Because', 'if', 'he', 'was', 'a', 'guitar', 'player', 'he', 'would', 'have', 'his', 'pick'], ['What', 'is', 'a', 'cat', 's', 'favorite', 'color', 'Purrple'], ['Why', 'did', 'the', 'ghost', 'float', 'across', 'the', 'road', 'Because', 'he', 'couldn', 't', 'walk'], ['What', 'kind', 'of', 'star', 'could', 'hurt', 'you', 'A', 'shooting', 'star']]

Output (shortened)
['What', 'did', 'the', 'little', 'boy', 'tell', 'the', 'game', 'warden', 'His', 'dad', 'was', 'in', 'the', 'kitchen', 'poaching', 'eggs']
0
['What', 'do', 'you', 'call', 'a', 'chicken', 'crossing', 'the', 'road', 'Poultry', 'in', 'motion']
1
['What', 'do', 'you', 'call', 'it', 'when', 'a', 'cat', 'sues', 'another', 'cat', 'A', 'Clawsuit']
2
['What', 'does', 'an', 'envelope', 'say', 'when', 'you', 'lick', 'it', 'Nothing', 'It', 'just', 'shuts', 'up']
3
['What', 's', 'black', 'white', 'green', 'and', 'bumpy', 'A', 'pickle', 'wearing', 'a', 'tuxedo']
5
['What', 'happened', 'to', 'the', 'wind', 'It', 'blew', 'away']
7
['What', 'starts', 'with', 'T', 'is', 'full', 'of', 'T', 'and', 'ends', 'with', 'T', 'A', 'teapot']
8
['What', 'is', 'a', 'hermit', 'A', 'girl', 's', 'baseball', 'glove']
9
['What', 'does', 'a', 'television', 'have', 'in', 'common', 'with', 'a', 'rabbit', 'His', 'ears']
10
['What', 'did', 'the', 'crop', 'say', 'to', 'the', 'farmer', 'Why', 'are', 'you', 'always', 'picking', 'on', 'me']
11
['What', 'did', 'the', 'guy', 'say', 'when', 'he', 'walked', 'into', 'the', 'bar', 'Ouch']
12
['What', 'has', 'four', 'legs', 'and', 'goes', 'booo', 'A', 'cow', 'with', 'a', 'cold']
14
['What', 'is', 'a', 'caterpillar', 'afraid', 'of', 'A', 'dogerpillar']
15
['What', 'do', 'you', 'call', 'a', 'cow', 'with', 'a', 'twitch', 'Beef', 'jerky']
22
['What', 'is', 'the', 'best', 'way', 'to', 'keep', 'water', 'from', 'running', 'Don', 't', 'pay', 'the', 'water', 'bill']
23
['What', 'time', 'was', 'is', 'when', 'the', 'elephant', 'sat', 'on', 'a', 'chair', 'Time', 'to', 'get', 'a', 'new', 'chair']
25
['What', 'did', 'the', 'flower', 'say', 'to', 'the', 'bike', 'Petal']
26
['What', 's', 'yellow', 'and', 'writes', 'A', 'ball', 'point', 'banana']
28
['What', 'word', 'is', 'always', 'spelled', 'incorrectly', 'Incorrectly']
30

With the input being a list of lists, the idea is to search through and put every unique word in as a key, with values being the documents it appears in. However the index produced
Index
{'walked': ['12'], 'across': ['60'], 'incorrectly': ['30'], 'Nothing': '3', 'keys': ['13'], 'frogs': ['43'], 'meat': ['6', '45'], 'be': ['39', '54', '58'], 'mother': ['20'], 'Petal': ['26'], 'typewritter': ['13'], 'see': ['32'], 'keep': ['21', '23'], 'jam': ['20'], 'black': '5', 'lick': '3', 'girls': ['58'], 'sues': '2', 'sidewalk': ['38'], 'book': ['41'], 'strongest': ['16'], 'shop': ['42'], 'favorite': ['59'], 'A': ['2', '5', '8', '9', '14', '15', '28', '36', '42', '61'], 'seen': ['32'], 'Did': ['29'], 'glove': '9', 'hands': ['47'], 'room': ['58'], 'patch': ['27'], 'T': '8', 'legs': ['14'], 'hippo': ['35'], 'his': ['17', '20', '46', '58'], 'cows': ['24'], 'new': ['25'], 'cards': ['21'], 'you': ['1', '2', '3', '4', '11', '21', '22', '31', '32', '35', '36', '42', '55', '61'], 'Look': ['47'], 'tree': ['55'], 'tell': ['0', '4', '27', '35'], 'missing': ['31'], 'front': ['46'], 'lion': ['21'], 'automobile': ['51'], 'eggs': '0', 'spots': ['40'], 'water': ['23'], 'full': ['8', '58'], 'moon': '6', 'need': ['40'], 'When': '6', 'moovies': ['24'], 'rest': ['18'], 'cat': ['2', '59'], 'boy': '0', 'fell': ['29'], 'hermit': '9', 'dogerpillar': ['15'], 'sings': ['50'], 'couldn': ['17', '60'], 'dad': '0', 'clock': ['47', '49'], 'turkey': ['33'], 'sat': ['25'], 'He': ['38', '39', '40'], 'bike': ['26'], 'seeing': ['40'], 'elevator': ['48'], 'Parsley': ['50'], 'secrets': ['27'], 'They': ['13'], 'flower': ['26'], 'both': ['13'], 'close': ['35'], 'bill': ['23', '46'], 'crossing': '1', 'glasses': ['40'], 'bawkbawk': ['53'], 'many': ['27'], 'penny': ['56'], 'guy': ['12'], 'chop': ['42'], 'had': ['54'], 'oven': ['35'], 'are': ['11', '18', '57'], 'jerky': ['22'], 'some': ['56'], 'Launch': ['45'], 'Ouch': ['12'], 'An': ['51'], 'Where': ['24'], 'caterpillar': ['15'], 'faster': ['19'], 'do': ['1', '2', '21', '22', '24', '27', '31', '36', '38', '42', '43', '45', '55'], 'lamp': ['37'], 'white': '5', 'Hot': ['19'], 'friendly': '4', 'pick': ['58'], 'me': ['11', '37', '41'], 'high': '6', 'always': ['11', '30', '46', '49'], 'crop': ['11'], 'face': ['46'], 'In': ['43', '48'], 'sad': ['46'], 'spelled': ['30'], 'poaching': '0', 'color': ['59'], 'twitch': ['22'], 'To': ['33', '53'], 'door': ['35'], 'Lemon': ['44'], 'jumped': '6', 'lobsters': ['57'], 'raise': ['48'], 'armadillo': ['39'], 'locksmith': ['13'], 'bawk': ['53'], 'It': ['3', '4', '7'], 'astronauts': ['45'], 'Flies': ['43'], 'Too': ['27'], 'digital': ['47'], 'Because': ['17', '20', '46', '52', '57', '58', '60'], 'joke': ['38'], 'ocean': '4', 'make': ['56'], 'hurt': ['61'], 'go': ['24', '53'], 'four': ['14'], 'with': ['8', '10', '14', '22', '51'], 'You': ['37'], 'laugh': ['29'], 'Don': ['23', '41'], 'Hound': ['31'], 'tuxedo': '5', 'farmer': ['11'], 'yellow': ['28', '44'], 'that': ['32', '39'], 'Wood': ['54'], 'if': ['31', '58'], 'eat': ['43', '45'], 'star': ['61'], 'happened': '7', 'catch': ['19', '55'], 'again': ['32'], 'check': ['53'], 'trunk': ['17'], 'together': ['56'], 'what': ['43', '54'], 'ice': ['29'], 'cross': ['20', '33', '36', '39'], 'banana': ['28'], 'mask': ['44'], 'Time': ['25'], 'Incorrectly': ['30'], 'underwear': ['16'], 'goes': ['14'], 'Cinderella': ['34'], 'they': ['47', '52', '57'], 'does': ['3', '10', '58'], 'child': ['48'], 'is': ['4', '8', '9', '13', '15', '23', '25', '30', '31', '44', '46', '48', '49', '59'], 'lady': ['29'], 'game': '0', 'the': ['0', '1', '4', '6', '7', '11', '12', '16', '17', '18', '20', '23', '25', '26', '29', '31', '33', '34', '37', '38', '39', '40', '41', '46', '48', '49', '52', '53', '56', '58', '60'], 'chicken': ['1', '33', '39', '53'], 'float': ['60'], 'His': ['0', '10'], 'mom': ['47'], '10': ['51'], 'people': ['29'], 'elephant': ['17', '25'], 'one': ['56'], 'will': ['32'], 'wish': ['58'], 'television': ['10'], 'can': ['4', '19', '35'], 'ends': '8', 'duck': ['46'], 'fat': ['36'], 'chair': ['25'], 'Clawsuit': '2', 'kind': ['61'], 'common': ['10'], 'its': ['21', '47'], 'wind': '7', 'shooting': ['61'], 'best': ['23', '48'], 'time': ['25', '49'], 'Poultry': '1', 'no': ['47'], 'not': ['17', '27'], 'picking': ['11'], 'won': ['35'], 'sees': ['46'], 'on': ['11', '25', '29', '37'], 'funny': ['38'], 'pig': ['42'], 'of': ['8', '13', '15', '18', '46', '49', '58', '61'], 'behind': ['49'], 'an': ['3', '48'], 'little': ['0', '46'], 'word': ['30'], 'point': ['28'], 'get': ['25', '33', '36', '56'], 'don': ['57'], 'could': ['39', '58', '61'], 'in': ['0', '1', '10', '20', '27', '35', '42', '46', '58'], 'away': ['7', '21', '41'], 'Everyone': ['19'], 'Let': ['56'], 'swing': ['34'], 'it': ['2', '3', '39', '52', '54'], 'Late': ['34'], 'way': ['23', '48'], 'rabbit': ['10'], 'to': ['7', '11', '17', '23', '24', '25', '26', '33', '34', '37', '39', '41', '47', '48', '53', '56'], 'have': ['10', '13', '24', '32', '58'], 'just': '3', 'heard': ['38'], 'over': '6', 'shark': ['36'], 'so': ['6', '46'], 'teapot': '8', 'strawberry': ['20'], 'from': ['21', '23', '41'], 'call': ['1', '2', '22', '42'], 'Lone': ['44'], 'weekdays': ['18'], 'ghost': ['60'], 'bumpy': '5', 'or': ['19'], 'girl': '9', 'Chuck': ['54'], 'guitar': ['58'], 'we': ['27'], 'Why': ['11', '17', '20', '27', '33', '34', '39', '40', '46', '52', '53', '57', '58', '60'], 'bat': ['34'], 'there': ['35'], 'The': ['18', '24', '35', '44', '49'], 'your': ['31', '35'], 'would': ['54', '58'], 'act': ['55'], 'writes': ['28'], 'No': ['29'], 'pickle': '5', 'beautiful': ['58'], 'running': ['23'], 'corn': ['27'], 'week': ['18'], 'wears': ['44'], 'French': ['43'], 'walk': ['60'], 'name': ['54'], 'sense': ['56'], 'never': ['32'], 'Take': ['21'], 'out': ['53'], 'woodchuck': ['54'], 'pay': ['23'], 'shellfish': ['57'], 'cold': ['14', '19'], 'letters': ['51'], 'butcher': ['42'], 'another': '2', 'runs': ['19'], 'ball': ['28', '34'], 'Sunday': ['18'], 'up': ['3', '29', '38'], 'like': ['13', '55'], 'page': ['41'], 'man': ['58'], 'If': ['54'], 'Which': ['18', '19'], 'nut': ['55'], 'share': ['57'], 'say': ['3', '11', '12', '26', '37', '41', '47', '56'], 'How': ['4', '13', '21', '35', '55'], 'Beef': ['22'], 'wanted': ['39'], 'dalmation': ['40'], 'baseball': '9', 'dinner': ['45'], 'ears': ['10', '27'], 'What': ['0', '1', '2', '3', '5', '7', '8', '9', '10', '11', '12', '14', '15', '22', '23', '25', '26', '28', '30', '31', '32', '36', '37', '38', '41', '42', '44', '45', '47', '48', '49', '50', '51', '56', '59', '61'], 'has': ['14', '16', '51'], 'prove': ['39'], 'Lost': ['31'], 'road': ['1', '20', '33', '39', '60'], 'green': ['5', '50'], 'wearing': '5', 'fun': ['24'], 'move': ['17'], 'cracked': ['29', '38'], 'shuts': '3', 'was': ['0', '6', '20', '25', '34', '40', '52', '58'], 'blew': '7', 'stronger': ['18'], 'Climb': ['55'], 'motion': '1', 'decide': ['17'], 'kitchen': '0', 'turn': ['37', '41'], 'cow': ['6', '14', '22'], 'he': ['12', '17', '38', '46', '58', '60'], 'days': ['18'], 'Yesterday': ['32'], 'envelope': '3', 'Arnold': ['16'], 'hot': ['19'], 'waves': '4', 'She': ['34'], 'bury': ['52'], 'pork': ['42'], 'afraid': ['15'], 'when': ['2', '3', '12', '25', '29', '36', '38'], 'other': ['37', '56'], 'warden': '0', 'did': ['0', '11', '12', '17', '20', '26', '33', '37', '38', '39', '40', '41', '47', '52', '53', '56', '60'], 'Purrple': ['59'], 'forgot': ['34'], 'Check': ['31'], 'charging': ['21'], 'and': ['5', '8', '14', '18', '28', '31', '36', '44', '50', '51', '55', '56'], 'player': ['58'], 'gas': ['51'], 'for': ['34', '45'], 'dog': ['31'], 'Flipper': ['36'], 'Elvis': ['50'], 'library': ['53'], 'credit': ['21'], 'Shortsineger': ['16'], 'but': ['29'], 'battery': ['52'], 'lot': ['13'], 'lift': ['17'], 'booo': ['14'], 'Who': ['16'], 'Saturday': ['18'], 'back': ['49'], 'should': ['31'], 'starts': ['8', '51'], 'done': ['39'], 'France': ['43'], 'squirrel': ['55'], 'into': ['12'], 'dead': ['52'], 'bar': ['12']}

is incorrect because my for loop is skipping steps. Is it possible that the amount of looping being done is messing with the loop? After adding the two print statements for debugging the output was 11373 lines long. If so, can anyone recommend a better alternative? Apologies if I'm missing an obvious answer.

A: I'm not sure I understand you correctly, but:
from collections import defaultdict

def create_index(tokens):
    index = defaultdict(list)

    for docid, ls in enumerate(tokens):
        for word in set(ls):
            index[word].append(docid)
    return index

That makes index a dictionary from words to lists of document ids:
>>> tokens = ["this is a test".split(), "that is another test".split()]
>>> create_index(tokens)
defaultdict(<class 'list'>, {'test': [0, 1], 'is': [0, 1], 'this': [0], 'that': [1], 'a': [0], 'another': [1]})


text:
Q: Expectation Value of Unitary Time Evolution Operator in Quantum Mechanics Does the expression $\langle \Psi_i|U(t)|\Psi_i\rangle$ have a specific meaning, where $U(T)$ is the unitary time evolution operator of $\Psi$, and $\Psi_i$ is the initial state of $\Psi$?
If so, could you please explain that meaning and also please provide any clear references to this that I could read?

A: To talk about $\langle \psi_i \vert U(t) \vert \psi_i \rangle$ as the "expectation value of the time evolution operator" is probably the least insightful way to talk about this quantity. Since $U(t) = \exp(-\mathrm{i}Ht)$ for time-independent Hamiltonians, if you want to look at expectation values, you could as well look at that of $H$ directly. Note that, in particular, the time evolution operator is not self-adjoint, since $U(t)^\dagger = U(-t)\neq U(t)$, so it is not an observable, and speaking of its "expectation value" is physically meaningless.
The physical meaning is clearer when you realize that $\lvert \langle \psi_i \vert U(t)\vert \psi_i\rangle\rvert^2$ is the probability (assuming the states are normalized) to find a system  that was at time $t_0 = 0$ in the state $\lvert \psi_i \angle$ again in the same state after the time $t$ has passed, hence $\langle \psi_i \vert U(t) \vert \psi_i \rangle$ is the "transition amplitude for a state into itself". This is probably most interesting when the $\lvert \psi_i\rangle$ are eigenstates of an operator that is being measured.


text:
Q: Unable to click the submenu in selenium webdriver Mouse hover menu's does not work. Please see further details below:-

*

*When I click start --> I get the submenus.

*When I click customer submenu--> element not clickable
a. I should be able to go to "Search for Customers" or "Create Top level Customer"

Start

Customers

Search for Customers

Create Top level Customer

A: Use Actions utility to first mouse hover on Start and then click on the desired sub menu. Sample code should look like below:
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;

//create Actions object
Actions builder = new Actions(driver);
IWebElement menuHoverLink = driver.FindElement(By.XPath("//a[text()='Start']"));
builder.MoveToElement(menuHoverLink);

IWebElement subLink = driver.FindElement(By.LinkText("Customers"));
builder.MoveToElement(subLink);
builder.Click();
builder.Build().Perform();

Lemme know if this helps!

A: We can use the keys to move over and click, instead of trying with the mouse coordinates this is with the keyboard.
Please try this
Mousehover:
String hover=Keys.chord(Keys.DOWN);
driver.findElement(By.linkText("the text which has to be clicked")).sendKeys(hover);

Click:
String clickdown=Keys.chord(Keys.ENTER);
driver.findElement(By.linkText("sub menu which has to be clicked")).sendKeys(clickdown);


text:
Q: What are the 'levels' of matches in Triple Town? I'm playing Triple Town on Android, and have never managed to match 3 on a mansion as yet.  So I was wondering how many levels I'm missing.  ;)
What I've seen:
Rock starter:

*

*Small rock (unmatched diamond)

*Large rock

*Treasure chest

Bear starter:

*

*Bear

*Gravestone

*Chapel

*Cathedral

*Treasure chest

Grass starter:

*

*Grass

*Bush

*Tree

*Barn

*House

*Mansion

Does the grass series eventually hit treasure chest as well?  Or are there extra levels I haven't managed to achieve so far?

A: You can always see what the next level of an item is by holding your finger above it (on the iOS version), you'll see it above the play field in the form of item+item+item=match.
Three mansions turn into a castle, three castles turn into sky castles. You can see two Sky Castles in this screen shot on the fourth row:

After you have four sky castles (exception from the previous "triple" pattern) it makes a bigger one, a floating Triple Castle, and that is the final level.


text:
Q: Pyinstaller doesnt create running exe for Kivy app I wrote a programm (with kivy) to help with some logical functions and wanted to build an exe using pyinstaller. The Code runs fine while using .py files. The Problems I encounter are Modules that aren't loaded:
[CRITICAL] [Camera      ] Unable to find any valuable Camera provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
    picamera - ModuleNotFoundError: No module named 'picamera'
      File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\__init__.py", line 62, in core_select_lib
        fromlist=[modulename], level=0)
      File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\camera\camera_picamera.py", line 18, in <module>
        from picamera import PiCamera

    gi - ModuleNotFoundError: No module named 'gi'
      File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\__init__.py", line 62, in core_select_lib
        fromlist=[modulename], level=0)
      File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\camera\camera_gi.py", line 10, in <module>
        from gi.repository import Gst

    opencv - ModuleNotFoundError: No module named 'cv2'
      File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\__init__.py", line 62, in core_select_lib
        fromlist=[modulename], level=0)
      File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\camera\camera_opencv.py", line 48, in <module>
        import cv2
[CRITICAL] [Spelling    ] Unable to find any valuable Spelling provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
enchant - ModuleNotFoundError: No module named 'enchant'
  File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\__init__.py", line 62, in core_select_lib
    fromlist=[modulename], level=0)
  File "c:\users\aayhan\appdata\local\programs\python\python37\lib\site-packages\kivy\core\spelling\spelling_enchant.py", line 12, in <module>
    import enchant

below is the spec file I used, where I used the fix suggesetet from Python to Exe
# -*- mode: python ; coding: utf-8 -*-
from kivy_deps import sdl2, glew

block_cipher = None

a = Analysis(['C:\\Users\\Aayhan\\Desktop\\LogicFunc\\Development\\Logic_Function_UIS.py', 'C:\\Users\\Aayhan\\Desktop\\LogicFunc\\Development\\Generate_Output.py', 'C:\\Users\\Aayhan\\Desktop\\LogicFunc\\Development\\Lambda_Function.py', 'C:\\Users\\Aayhan\\Desktop\\LogicFunc\\Development\\Generate_Output.py'],
             pathex=[],
             binaries=[],
             datas=[('C:\\Users\\Aayhan\\Desktop\\LogicFunc\\Development\\UIS.kv', '.')],
             hiddenimports=[],
             hookspath=[],
             hooksconfig={},
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='KorrekturTool',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True,
          disable_windowed_traceback=False,
          target_arch=None,
          codesign_identity=None,
          entitlements_file=None)

coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
               strip=False,
               upx=True,
               upx_exclude=[],
               name='KorrekturTool')

My Programm gets an Input which is converted into a lambda Function and then used to generate some information about the function.
Does anyone know how to get this modules/only the modules I need?


text:
Q: How to print double without trailing zeros and without scientific format As far as I can gather the output format can either be in fixed, scientific or default mode.
I don't want scientific mode, so that is out.
When using fixed mode (std::fixed) std::cout.precision(15) will leave trailing zeros.
When using default mode (std::defaultfloat) std::cout.precision(15) doesn't affect anything - e.g. after 6 decimal places it still switches to scientific format.
Basically, I would like
std::cout << 0.1 << std::endl;
std::cout << 0.0000001 << std::endl;

to print
0.1
0.0000001


text:
Q: How Reset vector of CPU is fixed As everyone knows, CPU starts execution from reset vector address. But How that address is fixed for any CPU. How CPU comes to know that fetch instruction from reset vector address.
where will be the reset vector address will be stored?

A: It is fixed in the same way that all the other functions like add number A to number B are fixed, it is a collection of transistors that make up gates that provide functions.
In the same way there are a collection of transistors and circuits that make up the program counter and they will be set up such that when a reset signal is received then the default value is set to the reset vector value.
You could think of it as a collection of gates connected on the side of the program counter that has only one input which is the reset signal. When that signal is received then the processor is stopped and those gates are triggered. They will push the various bits within the program counter register up and down to match the reset vector.
In that way, the reset vector is a fundamental feature of the way the circuit inside the processor is constructed.