text:
Q: Modify Graph Orientation in Excel VBA I am trying to create a bar graph but have it horizontally oriented. So far I can only make it vertical with the following code. I have been digging
around and man sources only show the vertical orientation. Is there a
way to
    Sub test_tic_count_graph()

    Dim chtTicCount As chart
    Dim ticCountGraph As Worksheet

    Set ticCountGraph = ActiveWorkbook.Sheets("ticCountGraph")
    Set chtTicCount = ticCountGraph.Shapes.AddChart(xlColumnClustered).chart

    With chtTicCount

                    .SetSourceData Source:=ticCountGraph.Range("A1:B9")

                    ''Activating the xlValue so we can refer to x-y values.
                    .HasAxis(xlValue, xlPrimary) = True
                    .HasAxis(xlValue, xlSecondary) = True

                    .Legend.Font.Size = 10
                    '' Sets legend position 100 points from top.
                    .Legend.Top = 100

                    ''Label the X - axis. Note it's xlCategory.
                    With .Axes(xlValue, xlPrimary)
                        .HasTitle = True
                        .AxisTitle.Text = "DEVICE"
                        .AxisTitle.Font.Size = 10

                        '' Modify tickmark labels font size.
                        .TickLabels.Font.Size = 10

                    End With

                    '' Label the Y - axis. Note it's xlValue.
                    With .Axes(xlCategory, xlPrimary)
                        .HasTitle = True
                        ''.AxisTitle.Text = "CPU %"
                        .AxisTitle.Font.Size = 10
                        .TickLabels.Font.Size = 10
                        ''.MaximumScale = 1

                    End With

            End With

    End Sub

A: xlColumnClustered is the ChartType property value for vertical bars. You probably want xlBarClustered for horizontal bars.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if y-axis begins at zero I want to determine if a plot generated by ggplot begins at zero.
I am generating a couple hundred reports that each have thirty or more charts in them. I am content with ggplot's defaults for when a plot starts at zero and when it doesn't, but I want to add a caption that draws the reader's attention to this fact.
Something like:
labs(caption = ifelse(XXXXX, "Note: y-axis does not begin at zero", ""))

But I have no clue what my test should be.

A: Try this:
library(ggplot2)

g <- ggplot(data.frame(x=1:10, y=0:9), aes(x=x,y=y)) + geom_point()
yrange <- ggplot_build(g)$layout$panel_params[[1]]$y.range
if(yrange[1] <= 0) g <- g + labs(caption = "Note: y-axis does not begin at zero")
plot(g)


text:
Q: Spring Security 3.2 XML configuration I know that this problem here very popular. But anyone didn't help me.
The problem is that I can't configure my spring-security.xml config file. I'm also have 404 error on / page.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-context.xml
            /WEB-INF/spring-data.xml
            /WEB-INF/spring-security.xml
            /WEB-INF/mvc-dispatcher-servlet.xml
        </param-value>
    </context-param>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- utf8 Encoder -->
    <filter>
        <filter-name>charsetFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>charsetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                                 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                                 http://www.springframework.org/schema/security
                                 http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/*" access="permitAll" />
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
        <form-login login-page="/" default-target-url="/home" authentication-failure-url="/?error=true"/>
        <logout logout-success-url="/" />
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService" />
    </authentication-manager>

</beans:beans>

Please, help me with my problem. Thanks!
===UPDATE===
mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="
              http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
              http://www.springframework.org/schema/mvc
              http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <annotation-driven />

    <resources mapping="/res/**" location="file:/home/piotr/Work/apache-tomcat-7.0.42/work-dir/res/" />

    <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/pages/"/>
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <beans:property name="maxUploadSize" value="1000000000"/>
    </beans:bean>

    <beans:bean id="fileUploadService" class="com.petrez.service.FileUploadServiceImpl">
        <beans:property name="savePath" value="/home/piotr/Work/apache-tomcat-7.0.42/work-dir" />
    </beans:bean>
</beans:beans>

spring-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <annotation-config />

    <component-scan base-package="com.petrez" />

</beans:beans>

spring-data.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
              http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
              http://www.springframework.org/schema/tx
              http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/Library" />
        <property name="username" value="root" />
        <property name="password" value="G190419g" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="packagesToScan" value="com.petrez" />
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="show_sql">false</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.petrez.model.User</value>
                <value>com.petrez.model.Role</value>
                <value>com.petrez.model.Book</value>
                <value>com.petrez.model.BookGenre</value>
            </list>
        </property>
    </bean>

    <bean id="userDetailsService" class="com.petrez.service.CustomUserDetailsService" />

    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
</beans>

A: @Petr, I know that this thread is a long back one, but my guess that you might have missed any of the following spring libraries,

*

*spring-security-core

*spring-security-web

*spring-security-context

From Spring Security docs at https://docs.spring.io/spring-security/site/docs/3.0.x/reference/ns-config.html, I found the following quote

To start using the security namespace in your application context, you first need to make sure that the spring-security-config.jar is on your classpath. Then all you need to do is add the schema declaration to your application context file:


text:
Q: How am I supposed to render timezone-aware model field with local time setting in django Let's say I had the following code
# settings.py in a proper location
...
TIME_ZONE = 'Asia/Seoul'
USE_TZ = True

# models.py in a proper location
class Post(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    def created_formatted(self):
        return self.created.strftime("%Y/%m/%d %H:%M")

Then, I rendered the following django template to html
before formatting: {{ a_post.created }}  # localtime
after formatting: {{ a_post.created_formatted }}  # not localtime

I expected both {{ a_post.created }} and {{ a_post.created_formatted }} have the same timezone, but they don't. I tried to find out how {{ a_post.created }} is rendered to localtime but I'm not sure which part of the django code is the right place to look for yet. (It will be really helpful if you let me know the right part of the django source code to look for). I want to apply the same idea to my created_formatted after I find how the rendering of datetime works in django template.
p.s. I know how to convert timezone-aware datetime to local time in Python. but do how I really have to do this manually for every method that I have? Any advice would be helpful!

A: From the docs
{% load tz %}

{% localtime on %}
    {{ value }}
{% endlocaltime %}

{% localtime off %}
   {{ value }}
{% endlocaltime %}

If you need a specific timezone
{% load tz %}

{% timezone "Europe/Paris" %}
    Paris time: {{ value }}
{% endtimezone %}

{% timezone None %}
    Server time: {{ value }}
{% endtimezone %}

Docs for localtime,
Docs for timezone


text:
Q: Generating rows of a rule 30 cellular automaton Rule 30 is a one dimensional cellular automaton where only the cells in the previous generation are considered by the current generation. There are two states that a cell can be in: 1 or 0. The rules for creating the next generation are represented in the row below, and depend on the cell immediately above the current cell, as well as it's immediate neighbours.
The cellular automaton is applied by the following rule (using bitwise operators):
left_cell ^ (central_cell | right_cell)

This rule forms the table below:

Now I tried to implement these rules into Python, using numpy. I defined an initial state that accepts width as a parameter and produces an initial row of zeros with 1 in the middle.
def initial_state(width):
    initial = np.zeros((1, width), dtype=int)
    if width % 2 == 0:
        initial = np.insert(initial, int(width / 2), values=0, axis=1)
        initial[0, int(width / 2)] = 1
        return initial
    else:
        initial[0, int(width / 2)] = 1
        return initial

The function below just produces the second generation given an initial row. How do I create a for loop that keeps producing new generations until the first element of the last bottom row becomes 1?
def rule30(array):
    row1 = np.pad(array,[(0,0), (1,1)], mode='constant')
    next_row = array.copy()
    for x in range(1, array.shape[0]+1):
        for y in range(1, array.shape[1]+1):
            if row1[x-1][y-1] == 1 ^ (row1[x-1][y] == 1 or row1[x-1][y+1] == 1):
                next_row[x - 1, y - 1] = 1
            else:
                next_row[x - 1, y - 1] = 0
        return np.concatenate((array, next_row))

For example, if the input is
A = [0, 0, 0, 1, 0, 0, 0]

The output should be
>>> print(rule30(A))
[[0, 0, 0, 1, 0, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 1, 1, 0, 0, 1, 0],
 [1, 1, 0, 1, 1, 1, 1]]

A: Here is the code based on string representations and lookup. It does use some of the ideas from the comments above. Besides I added padding for handling edge cells - the conditions were unclear about that. Also note that your proposed patterns table is not symmetric. Compare new states for '110' and '011'.
def rule30(a):
    patterns = {'111': '0', '110': '0', '101': '0', '100': '1',
                '011': '1', '010': '1', '001': '1', '000': '0', }
    a = '0' + a + '0'  # padding
    return ''.join([patterns[a[i:i+3]] for i in range(len(a)-2)])

a = '0001000'
result = [list(map (int, a))]

while a[0] != '1':
    a = rule30(a)
    result.append (list(map (int, a)))
print (result)  # list of lists
print (np.array(result))  # np.array

list of lists:
[[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [1, 1, 0, 1, 1, 1, 1]]

np.array:
array([[0, 0, 0, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 1, 1, 0, 0, 1, 0],
       [1, 1, 0, 1, 1, 1, 1]])

A: Method 1 - Numpy
You could achieve this using the following slight modification to your current code - alter the return value of rule30 to return np.array(next_row). Then you can use the following function:
def apply_rule(n):
    rv = initial_state(n)
    while rv[-1][0] == 0:
        rv = np.append(rv, rule30(rv[-1].reshape(1,-1)), axis=0)
    return rv

Usage:
>>> apply_rule(7)
array([[0, 0, 0, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 1, 1, 0, 0, 1, 0],
       [1, 1, 0, 1, 1, 1, 1]])

Or plotted:
>>> plt.imshow(apply_rule(7), cmap='hot')

Method 2 - Lists
Alternatively, you could use the following solution without using numpy, which uses a few functions to apply the Rule 30 logic across each triple in each padded list, until the stop-condition is met.
Code:
def rule(t):
    return t[0] ^ (t[1] or t[2])

def initial_state(width):
    initial = [0]*width
    if width%2:
        initial[width // 2] = 1
    else:
        initial.insert(width//2, 1)
    return initial

def get_triples(l):
    return zip(l,l[1:],l[2:])

def rule30(l):
    return [rule(t) for t in get_triples([0] + l + [0])]

def apply_rule(width):
    rv = [initial_state(width)]
    while not rv[-1][0]:
        rv.append(rule30(rv[-1]))
    return rv

Usage:
>>> apply_rule(7)
[[0, 0, 0, 1, 0, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 1, 1, 1, 0, 1, 0],
 [1, 1, 1, 0, 0, 1, 1]]
>>> [''.join(str(y) for y in x) for x in apply_rule(7)]
['0001000',
 '0011100',
 '0111010',
 '1110011']

Matplotlib visualisation (using either method):
import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
plt.imshow(apply_rule(250), cmap='hot')


text:
Q: VBA WebScraping Script Returns Subscript OutOf Range Problem:
I've been trying to scrape data from a WebSite, but it's always giving me an error Subscript OutOf Range. I don't know why. I use the exact same code for another website and it works perfectly fine.
Yes, I've changed the divs from the new website I want to scrape from.
Code:
Option Explicit
Public Sub Loiça()
    Dim data As Object, i As Long, html As HTMLDocument, r As Long, c As Long, item As Object, div As Object
    Set html = New HTMLDocument                  '<== VBE > Tools > References > Microsoft HTML Object Library

    Const START_URL As String = "https://mediamarkt.pt/pages/search-results-page?q=maquina+roupa&page=1"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", START_URL, False
        .setRequestHeader "User-Agent", "Mozilla/5.0"
        .send
        html.body.innerHTML = .responseText
        Dim numPages As Long, numResults As Long, arr() As String
        arr = Split(html.querySelector(".snize-search-results-header").innerText, Chr$(32))
        numResults = arr(UBound(arr))
        numPages = 1

        For i = 1 To numPages
             If i > 1 Then
                .Open "GET", Replace$("https://mediamarkt.pt/pages/search-results-page?q=maquina+roupa&page=1", "page=1", "page=" & i), False
                .setRequestHeader "User-Agent", "Mozilla/5.0"
                .send
                 html.body.innerHTML = .responseText
            End If
            Set data = html.getElementsByClassName("snize-four-columns")
            For Each item In data
                r = r + 1: c = 1
                For Each div In item.getElementsByTagName("div")
                    With ThisWorkbook.Worksheets("Loiça")
                        .Cells(r, c) = div.innerText
                    End With
                    c = c + 1
                Next
            Next
        Next
    End With
    '----------------------------------------------------------------------------------------------------------------------------------------------------------------------'
End Sub

A: This
html.querySelector(".snize-search-results-header").innerText

is returning an empty string, therefore when you do split you end up with a -1 in your arr.
It may be that this value requires javascript to run on page. Inspect the returned html. I think no value is returned for that. Use a method like selenium or IE which allows js to run on the page and update content with the value
In this case you also need the lbound so you could use a function that returns the value which uses IE
numPages  =  GetNumberOfPages

Public Function GetNumberOfPages() As Long
    Dim IE As New InternetExplorer
    With IE
        .Visible = False
        .Navigate2 "https://mediamarkt.pt/pages/search-results-page?q=maquina+roupa&page=1"

        While .Busy Or .readyState < 4: DoEvents: Wend

        Dim numPages As Long, numResults As Long, arr() As String
        arr = Split(.document.querySelector(".snize-search-results-header").innerText, Chr$(32))
        numResults = arr(LBound(arr))
        GetNumberOfPages =  numResults
        .Quit
    End With
End Function

For the next page you are looking at a different class name (I think)
Set data = html.getElementsByClassName("snize-product")

Inspect the html to verify.


text:
Q: How to integrate AWS Lex chatbot in Xamarin application? I have basic understanding of .net and chatbot.
I wanted to integrate Amazon lex in xamarin(ios, android)app. There seems to be no example or sample. I have created chatbot from AWS platform intent and slots.
Also I wanted to use database to get query return. Any sample to integrate AWS Lex with Xamarin app would be helpful.

A: As I understand from your question, you already have some implementation of chatbot made with AWS services, but you are having issue on integrating it to your xamarin application to be able to use it in IOS and Android devices.
For that purpose, there is AWS Mobile SDK which happens to support also xamarin.
From their link:
https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/Welcome.html
I also did not find a Lex tutorial directly, but a very promising quote:

Supported AWS services currently include, but are not limited to [narrow list of services]

was on the same page. I looked around, found this text:

The AWS Mobile SDK for .NET and Xamarin also allows you to use most of the AWS services supported by the AWS SDK for .NET. The AWS services specific to mobile development are explained in this developer guide. For more information about the AWS SDK for .NET, see [a link]

clicked the link and ended here:
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/Index.html
and under link AmazonLex -> AmazonLexClient there was something, you probably wanted to see:

Version Information
  .NET Standard:
  Supported in: 1.3
  .NET Framework:
  Supported in: 4.5, 4.0, 3.5
  Portable Class Library:
  Supported in: Windows Store Apps
  Supported in: Windows Phone 8.1
  Supported in: Xamarin Android
  Supported in: Xamarin iOS (Unified)
  Supported in: Xamarin.Forms

Those 3 last let me understand that whenever you setup Mobile SDK, you get access to AWS services in Xamarin, also Lex.
Steps to install on
https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/setup.html
mainly contain steps on how to create xamarin app and get AWS account, most important is to install the AWS Mobile SDK for .NET and Xamarin and configure it. More detailed steps are under that link.
After that the process is to follow the instructions on:
https://aws.amazon.com/getting-started/projects/bots-just-got-better-net-toolkit-lex-lambda-cognito/module-one/
like pointed in comments. I suppose once you have access to any service via Mobile SDK, the wire up of Lex may go in similar steps and no special just xamarin tutorial is not needed anymore.

A: It seems you are looking for both architecture and sample code for implementing AWS Lex bot with .NET backend that can be integrated with iOS/Android Frontend.
You have multiple choices here to do it

*

*Build both chat user interfaces in iOS and Android and integrate them AWS iOS & Android SDKs to utilize the AWS LEX bot.

*Just implement a bot user interface in iOS and Android app and integrate it with a .NET backend that can utilize AWS .NET SDK to integrate with your LEX bot.
I would recommend the second approach as it will save you writing the LEX integration code twice both in Android and in iOS. In the second appraoch you will be able to write a single integration for AWS LEX in .NET and that can give a unified experience across the mobile devices(iOS/Android)
Now for the .NET based backend integration with AWS LEX bot.
If you are an experienced .NET developer and you know how will you host your code then only thing that you need is the .NET API reference for AWS LEX, which can be found here
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Lex/TLexClient.html
But if you are not sure how to write this integration code and also not sure how the deployment will look like then you can follow the below tutorial
Bots Just Got Better with .NET and the AWS Toolkit for Visual Studio
Also, find here the architecture form the above tutorial

A: there is no direct solution like Amazon Lex is supported by React-native. i confirmed with xamarin team as well as AWS service one of the member. direct integration not possible.


text:
Q: Read contents of tar file without unzipping to disk I have been able to loop through the files in a tar file, but I am stuck on how to read the contents of those files as string. I would like to know how to print the contents of the files as a string?
This is my code below
package main

import (
    "archive/tar"
    "fmt"
    "io"
    "log"
    "os"
    "bytes"
    "compress/gzip"
)

func main() {
    file, err := os.Open("testtar.tar.gz")

    archive, err := gzip.NewReader(file)

    if err != nil {
        fmt.Println("There is a problem with os.Open")
    }
    tr := tar.NewReader(archive)

    for {
        hdr, err := tr.Next()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("Contents of %s:\n", hdr.Name)
    }
}

A: Just use the tar.Reader as an io.Reader for each file you want to read.
tr := tar.NewReader(r)

// get the next file entry
h, _ := tr.Next()

If you need the whole file as a string:
// read the complete content of the file h.Name into the bs []byte
bs, _ := ioutil.ReadAll(tr)

// convert the []byte to a string
s := string(bs)

If you need to read line by line, then this would be better:
// create a Scanner for reading line by line
s := bufio.NewScanner(tr)

// line reading loop
for s.Scan() {

  // read the current last read line of text
  l := s.Text()

  // ...and do something with l

}

// you should check for error at this point
if s.Err() != nil {
  // handle it
}

A: Sometimes I have seen people use tar.gz as a makeshift database, so I found it
useful to read the archive into a fstest.MapFS:
package main

import (
   "archive/tar"
   "compress/gzip"
   "io"
   "os"
   "testing/fstest"
)

func tarGzMemory(source string) (fstest.MapFS, error) {
   file, err := os.Open(source)
   if err != nil { return nil, err }
   defer file.Close()
   gzRead, err := gzip.NewReader(file)
   if err != nil { return nil, err }
   tarRead := tar.NewReader(gzRead)
   files := make(fstest.MapFS)
   for {
      cur, err := tarRead.Next()
      if err == io.EOF { break } else if err != nil { return nil, err }
      if cur.Typeflag != tar.TypeReg { continue }
      data, err := io.ReadAll(tarRead)
      if err != nil { return nil, err }
      files[cur.Name] = &fstest.MapFile{Data: data}
   }
   return files, nil
}

Example:
package main

func main() {
   m, e := tarGzMemory("mingw64.db.tar.gz")
   if e != nil {
      panic(e)
   }
   data := m["mingw-w64-x86_64-gcc-10.2.0-10/desc"].Data
   print(string(data))
}

https://golang.org/pkg/testing/fstest

A: With some help from the official site this is what I had intended previously. Special focus should be turned to the bottom where the conversion from bytes to string is made.
package main

import (
    "archive/tar"
    "fmt"
    "io"
    "log"
    "os"
    "bytes"
    "compress/gzip"
)

func main() {

    file, err := os.Open("testtar.tar.gz")

    archive, err := gzip.NewReader(file)

    if err != nil {
        fmt.Println("There is a problem with os.Open")
    }
    tr := tar.NewReader(archive)

    for {
        hdr, err := tr.Next()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("Contents of %s:\n", hdr.Name)

        //Using a bytes buffer is an important part to print the values as a string

        bud := new(bytes.Buffer)
        bud.ReadFrom(tr)
        s := bud.String()
        fmt.Println(s)
        fmt.Println()
    }

}


text:
Q: Python error No such file or directory I get the following error: No such file or directory but I'm unsure why. I know it looks easy to explain but I'm unsure what directory its referring to here
env = os.environ.copy()
env['MY_LIB_PATH'] = '/Users/user/Documents/workspace/projecttest/lib'
subprocess.call(["test_program",image_url],env=env)

Error:
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    model = get_model(image.get_image_content())
  File "/Users/user/Documents/workspace/projecttest/utilities.py", line 51, in get)model
    env=env
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

A: To make sure that a program is found, you need to append to the PATH environment variable.
env = os.environ.copy()
env['PATH'] += os.pathsep + '/Users/user/Documents/workspace/projecttest/lib'
subprocess.call(["test_program", image_url], env=env)

Or you can call it explicitly;
cmd = '/Users/user/Documents/workspace/projecttest/lib/test_program'
subprocess.call([cmd, image_url])

Additionally, your test_program must be executable.
Note that subprocess.call can only execute programs. If you want to use a function from a dynamic link library, you'll have to use ctypes.

A: You cannot set a random environment variable and expect python to magically read it. Either you:

*

*Insert the path in PATH.

*Use your random environment variable to construct the path, e.g.:
subprocess.call([os.path.join(os.environ["MY_LIB_PATH"],
                              "test_program"),
                img_url])


text:
Q: parsing a xhr.responseText response I am trying to get the xhr.responseText response after consuming a web service, when I executed this code:
if (xhr.readyState === 4)
{
       alert("result "+xhr.responseText);
}

I get this response:
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://www.webserviceX.NET/">0.4498</double>

I would like to get the 0.4498 value!
thank you in advance!

A: You should use responseXML to parse XML:
var xmlDoc = xhr.responseXML;
var d = xmlDoc.getElementsByTagName("double")[0].childNodes[0].nodeValue;

or can use regexp also:
/>([\d.]+)</.exec(xhr.responseText)[1]


text:
Q: Can't I use Polymer.js via CDN in rails app? I want to add frameworks like AngularJS, Bootstrap and polymer JS into my rails app. Problem with the gems is they are unstable with new versions and they even stop developing gems(which leads to failing of one gem which depends on another)
So I just want to add those frameworks directly into the application root html file via CDN(offered by the vendor). Is that a good practice? Will it cause any future problems in production environment?

A: Yes, if you are using reliable CDN's (and those offered my vendors can be treat as one) it may even bring you some improvements in the production enviromnent, e.g.:

*

*those assets will be often already cached on your user's machines

*it circumvents browsers limit the number of concurrent connections from the same domain (as your app)

On the flip side, on your dev enviromnent you'll have to wait a liiitle bit more for the website to load those assets comparing it to loading them from localhost ;)

A: if you dont use CDN,you have much control over the assets ,as they might change/update or sometimes the url can be down :( in worst case scenario..so i suggest using local assets if there is large dependency and for small dependency ...you may use cdn. :)
use this to set up polymer js onlocal.


text:
Q: Sorting multiple columns from a CSV file in Python I am a secondary school teacher attempting to find an appropriate way to teach KS4 pupils techniques that will allow them to write data to a CSV file and then read that same data from a file and display it back in Python in an organised structure.
Pupils and I have a clear understanding of how to write the data to the file however in terms of getting the data from the file into Python and then sorting it is becoming rather tricky and complex to explain.
I've created a program that allows the user to input their name followed by 3 separate numbers all of which get written to the CSV file in the format shown below...
James , 3 , 7 , 4
David , 5 , 5 , 9
Steven , 8 , 3 , 9

These results are saved in a file "7G1.csv"
So far I have a functioning program that sorts alphabetically, highest to lowest and by average highest to lowest. I have been able to establish through research and piecing together techniques from numerous sources the following program but can anybody suggest an easier more efficient approach that could be understood by 16 year olds.
import csv

G1 = open('7G1.csv')
csv_G1 = csv.reader(G1)
list7G1 = []
for column in csv_G1:
    column[1] = int(column[1])
    column[2] = int(column[2])
    column[3] = int(column[3])
    minimum = min(column[1:4])
    column.append(minimum)
    maximum = max(column[1:4])
    column.append(maximum)
    average = round(sum(column[1:4])/3)
    column.append(average)
    list7G1.append(column[0:7])

group_menu = 0
while group_menu != 4:
    group_menu = int(input("Which group / class do you want to look at?\n1.7G1?\n2.7G2?\n3.7G3?\n4.Quit? "))
    if group_menu == 1:
        print ("You have chosen to focus on group 7G1.")
        menu = int(input("\nDo you want to...\n1.Sort Alphabetically?\n2.Sort Highest to Lowest?\n3.Sort Average Highest to Lowest?\n4.Exit Group? "))
        while menu != 4:
            if menu == 1:
                print("You have chosen to Sort Alphabetically...")
                namesList = [[x[0], x[5]] for x in list7G1]
                print("\nSorted Alphabetically with Highest Scores \n")
                for names in sorted(namesList):
                    print (names)
            elif menu == 2:
                print("You have chosen to Sort Highest to Lowest...")
                highestScore = [[x[5], x[0]] for x in list7G1]
                print("\nScores Highest to Lowest \n")
                for hightolow in sorted(highestScore, reverse = True):
                    print (hightolow)
            elif menu == 3:
                print("You have chosen to Sort Average Highest to Lowest")
                averageScore = [[x[6], x[0]] for x in list7G1]
                print("\nAverage Scores \n")
                for average in sorted(averageScore, reverse = True):
                    print(average)
            elif menu == 4:
                print("You have chosen to exit this group")
            else:
                print("This is not a valid option")
            menu = int(input("\nDo you want to...\n1.Sort Alphabetically?\n2.Sort Highest to Lowest?\n3.Sort Average Highest to Lowest?\n4.Exit Group? "))

Any suggestions on how to simplify this program would be hugely appreciated.


text:
Q: How to 'git cat-file' using exclusively Python? I am trying to read out commit hashes, alongside their parent hashes, in order to build a commit graph from the .git/ directory. Currently, I have something like:
import zlib
import os

...

    for current, subs, files in os.walk('.'):
        for filename in files:

            # in format ##/#{38}

            path = os.path.join(current, filename)[2:]

            # 'info/' and 'pack/' exist
            # don't worry about packed files
            # assume empty (excluding . and ..)

            with open(path, 'rb') as file:

                # returns bytes object
                # assuming UTF-8 encoding (default) vs. legacy
                # https://git-scm.com/docs/git-commit#_discussion
                # .decode() also defaults to utf-8

                print(zlib.decompress(file.read()).decode())

However, I am noticing that this is not what I want. The above code is meant to eventually go through all of .git/objects/ and parse into a list the commits and their parents to help me build the commit graph. As of right now, it seems like the zlib decompression is not producing output the way I like. I have read the relevant sections in Pro Git, specifically: http://git-scm.com/book/en/v2/Git-Internals-Git-Objects , which had instructions for Ruby. How can I accomplish this in Python?

A: The linked documentation seems pretty clear.

Git first constructs a header which starts by identifying the type of object — in this case, a blob. To that first part of the header, Git adds a space followed by the size in bytes of the content, and adding a final null byte:

Ruby is very similar to Python, so when the documentation shows:
>> content = "what is up, doc?"
=> "what is up, doc?"
>> header = "blob #{content.bytesize}\0"
=> "blob 16\u0000"
>> store = header + content
=> "blob 16\u0000what is up, doc?"

The Python code is almost identical:
>>> content = "what is up, doc?"
>>> header = f"blob {len(content)}\0"
>>> blob = header + content
>>> blob
'blob 16\x00what is up, doc?'

As both the prose and the code are showing us, when you read data from an object file you need to split it into a header and content. Something like:
with open(path, 'rb') as fd:
    data = zlib.decompress(fd.read())
    header, content = data.split(b'\0', 1)
    if header.startswith(b'commit'):
      print('found a commit in', path)


text:
Q: How can I access to the Android camera directly from Salesforce 1 I want to open the camera in an Android device from Saleforce1. I've seen many blogs that say that it is possible in android but always the screenshots are with an IOS device.
Salesforce1 can open the camera when you want to post a picture in chatter like this:

The take picture open the camera directly.
Now in my visualforce page I have a Button to open the camera with this code
<input id="picture_info" type="file" accept="image/*;capture=camera" capture="camera" onchange="" />

But when I click on it, I need to select an Image from my gallery:

I would like to open with a button the camera directly as the Salesforce1 "Take picture" button. Is something that I can do? it is possible?
I'm using a Google Nexus 5 device with Android 5.1, also I tested it with Android 4.4.4 KitKat.

A: Ok Guys, I just saw that now with the last version of Salesforce1 v 10.0, and Android 6.0 the option to use the camera is available. I tried this in the same project without any code change.

A: You can use this link it will help you a lot but it is working only for Nexus5 and IPhone6 read this article if need some help
Link : http://www.jitendrazaa.com/blog/salesforce/access-camera-and-audio-recorder-of-mobile-device-in-visualforce-and-upload-as-chatter-file/


text:
Q: Target screen readers and avoid duplicating content I have heard of @media speech, aural, screen but when I try to play with them in order to have NVDA read a piece of HTML the way I want it to, it doesn't work.
Practical example: in a list of extensions, I want the screen reader to utter "o g g" when reading "ogg", (because otherwise it sounds like "ag"), but I don't want visual users to read a long list of acronyms in capital letters (which is what sounds best) because it is harder to read.
The markup which achieves the expected result is the following.

    oga
    OGA

You can tell I have duplicated the content and there is a lot of boilerplate.
Instead, I would have liked to do the following
oga

@media speech {
  abbr {
     text-transform: uppercase;
  }
}

or
abbr {
  text-transform: uppercase;
}

@media screen{
  abbr {
     text-transform: lowercase;
  }
}

(by the way, I'm not sure if @media screen is a condition which validates if the device has a screen or if it allows a set of instructions to be targetted at the rendering engine)
I have also tried the following, which is less verbose
oga

oga

But none of these work.

A: You don't need to do anything.
Screen reader users will read an extension a letter at a time with their screen reader if it is a list of abbreviations and they can't understand what is being said.
For example in NVDA they would press NVDA + . to read the next letter one at a time.
There are hundreds of hacks you could use (wrap each letter in a
 tag and make it display inline) but they all end up in a mess of completely useless HTML that is semantically incorrect.
If you absolutely MUST control the speech.
In your example the best way to achieve this is to duplicate your list with one for screen readers and one for visual presentation.
I would 'recommend' (I don't recommend it at all, but it is the best option if you really really must) this approach because:-

*

*Much easier to maintain.

*Same amount of nodes (well + 1 for the additional
)  e.g.
, , ,  VS
,  times two.

*Easier to render for the browser (if this was 10,000 items you would notice a difference).

*Less page weight - saves around 40 bytes per item.

*Clean HTML without hundreds of aria attributes.

*Other solutions such as relying on CSS media queries etc. may not work with older screen readers (this solution is robust).

Example

.visually-hidden {
    position: absolute !important;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
    white-space: nowrap; /* added line */
}

         oga

         abc

         OGA

         ABC

Edit
In my comment I realised another option could be to have a toggle button at the start of the list 'capitalise extensions'.
You could then use JavaScript to capitalise the letters (replace the HTML, CSS capitalisation is not robust for screen readers as some ignore it) if someone preferred that, although this is just an idea to leave the markup clean. You would have to test this.

A: You can use the zero-width space char :  to separate each char, without making any visual difference

Use the "ogg" extension

*

*The aria-label won't work for text elements.

*speech and aural media type have no support

*There's no guarantee that uppercase word will be read differently than lowercase. This depends on the synthesiser


text:
Q: Split string elements based on multiple words delimiters in Python Given a text list as follows:
text = ["Nanjing Office and Retail Market Overview 2019 Second Quarter",
"Xi'an Office and Retail Market Overview 2020 Q1",
"Suzhou office and retail overview 2019 fourth quarter DTZ Research",
"marketbeat Shanghai office Second quarter of 2020 Future New Grade A office supply in non-core business districts One-year trend Although the epidemic in Shanghai has been controlled in a timely and effective manner, the negative impact of the epidemic on Shanghai's commercial real estate The impact continues.",
"Shanghai office September 2019 marketbeats 302.7 -0.4% 12.9% rent rent growth vacancy"]

I would like to use multiple words (Market, quarter, marketbeats) to split each string element, then get the first part including the delimiter words:
for string in text:
    # string = string.lower()
    split_str = re.split(r"[Market|quarter|marketbeats]", string)
    print(split_str)

Out:
['n', 'njing offic', ' ', 'nd ', '', '', '', 'il ', '', '', '', '', '', ' ov', '', 'vi', 'w 2019 ', '', 'cond ', '', '', '', '', '', '', '']
["xi'", 'n offic', ' ', 'nd ', '', '', '', 'il ', '', '', '', '', '', ' ov', '', 'vi', 'w 2020 ', '1'],
...

But the expected result will be like this:
"Nanjing Office and Retail Market",
"Xi'an Office and Retail Market",
"Suzhou office and retail overview 2019 fourth quarter",
"marketbeat Shanghai office Second quarter",
"Shanghai office September 2019 marketbeats"

How could I get the correct result in Python? Thanks.

A: You could use an re.findall approach here:
text = ["Nanjing Office and Retail Market Overview 2019 Second Quarter", "Xi'an Office and Retail Market Overview 2020 Q1", "Suzhou office and retail overview 2019 fourth quarter DTZ Research", "marketbeat Shanghai office Second quarter of 2020 Future New Grade A office supply in non-core business districts One-year trend Although the epidemic in Shanghai has been controlled in a timely and effective manner, the negative impact of the epidemic on Shanghai's commercial real estate The impact continues.", "Shanghai office September 2019 marketbeats 302.7 -0.4% 12.9% rent rent growth vacancy"]
output = [re.findall(r'^.*?\b(?:Market|quarter|marketbeats|$)\b', x)[0] for x in text]
print(output)

This prints:
['Nanjing Office and Retail Market',
 "Xi'an Office and Retail Market",
 'Suzhou office and retail overview 2019 fourth quarter',
 'marketbeat Shanghai office Second quarter',
 'Shanghai office September 2019 marketbeats']


text:
Q: How to add test parameters to PHP code I am looking to set test parameters into my variables that I have written, however they recieve their data through the POST method, what's the best way to test my code by presetting the variables myself, e.g. thisRate->$fromCurr = 'GBP' rather than always testing through the browser...
Thanks

A: $_POST['myVar'] = "test";

Is this what you mean?

A: If you don't want to work through post while testing, you could just set another variable and use that until you know it works. Instead of using $_POST['myvar'] you could use $myvar.


text:
Q: Ubuntu installation and updates This is my firs OS change. Can I Install Ubuntu on a completely Formatted Hard drive? And do I need to install additional drivers from Microsoft or is every thing I need is on the Ubuntu DVD I have just downloaded? Also like Microsoft, does Ubuntu have automatic updates?

A: 1) you can install Ubuntu on a formatted hard drive
2) you don't have to use Microsoft drivers, just some new graphic cards may need a driver which are supported by Nvidia and ATI
3) yes, and absolutely yes,Ubuntu updates are available and automatic :)


text:
Q: String literal in Webpack dynamic import I'm using dynamic imports to create chunks of all locales in a project. The chunks are created, but the client reports this error at runtime:
Uncaught (in promise) ReferenceError: locale is not defined
  at _callee$ (main.js?f161:72)
  at tryCatch (runtime.js?98b8:62)
  at Generator.invoke [as _invoke] (runtime.js?98b8:288)
  at Generator.prototype.(:8082/d2/v2/search/anonymous function) [as next] (webpack-internal:///./node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:114:21)
  at asyncGeneratorStep (asyncToGenerator.js?c973:3)
  at _next (asyncToGenerator.js?c973:25)

The code in question:
// main.js
import { locale } from './config';

(async () => {
  const formatter = new Formatter({ locale });
  const i18n = new VueI18n({
    locale,
    formatter,
  });

  // Prints "en-GB", for example, so it's *not* undefined
  console.log(locale);

  const messages = await import(
    /* webpackChunkName: "[request]" */
    `./locales/${locale}/translations.js`, // <= Error
  );
  i18n.setLocaleMessage(locale, messages);

  new Vue({
    el: '#app',
    router,
    i18n,
    render: h => h(App),
  });
})();

Babel configuration:
"babel": {
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    [
      "@babel/plugin-proposal-object-rest-spread",
      {
        "useBuiltIns": true
      }
    ],
    "@babel/plugin-transform-runtime",
    "@babel/plugin-transform-async-to-generator",
    "@babel/plugin-syntax-dynamic-import"
  ]
},

Locale is exported like so:
// config.js
export const locale = process.env.LOCALE; // e.g. "en-GB"

Changing the import path to something static, like ./locales/en-GB/translations.js, works.
Edit
This started working when I reassigned locale to an intermediate variable, like below:
(async () => {
  // ...

  const tempLocale = locale;

  // Passing `locale` here won't work, but `tempLocale` does...
  const messages = await import(
    /* webpackChunkName: "[request]" */
    `./locales/${tempLocale}/translations.js`,
  );

  // `locale` is accepted just fine here, for some reason
  i18n.setLocaleMessage(locale, messages);

  // ...
})();

I also noticed that when inspecting the locale variable in the debugger that outside of the IIFE it resolves to the actual string ("en-GB"), but inside it resolves to the module in which the locale variable is contained. Very confusing, and this solution feels too hacky to be acceptable.


text:
Q: Go << and >> operators Could someone please explain to me the usage of << and >> in Go? I guess it is similar to some other languages.

A: << is left shift.  >> is sign-extending right shift when the left operand is a signed integer, and is zero-extending right shift when the left operand is an unsigned integer.
To better understand >> think of
var u uint32 = 0x80000000;
var i int32 = -2;

u >> 1;  // Is 0x40000000 similar to >>> in Java
i >> 1;  // Is -1 similar to >> in Java

So when applied to an unsigned integer, the bits at the left are filled with zero, whereas when applied to a signed integer, the bits at the left are filled with the leftmost bit (which is 1 when the signed integer is negative as per 2's complement).

A: Go's << and >> are similar to shifts (that is: division or multiplication by a power of 2) in other languages, but because Go is a safer language than C/C++ it does some extra work when the shift count is a number.
Shift instructions in x86 CPUs consider only 5 bits (6 bits on 64-bit x86 CPUs) of the shift count. In languages like C/C++, the shift operator translates into a single CPU instruction.
The following Go code
x := 10
y := uint(1025)  // A big shift count
println(x >> y)
println(x << y)

prints
0
0

while a C/C++ program would print
5
20

A: In decimal math, when we multiply or divide by 10, we effect the zeros on the end of the number.
In binary, 2 has the same effect. So we are adding a zero to the end, or removing the last digit

A: The << and >> operators are Go Arithmetic Operators.
<<   left shift             integer << unsigned integer
>>   right shift            integer >> unsigned integer

The shift operators shift the left
  operand by the shift count specified
  by the right operand. They implement
  arithmetic shifts if the left operand
  is a signed integer and logical shifts
  if it is an unsigned integer. The
  shift count must be an unsigned
  integer. There is no upper limit on
  the shift count. Shifts behave as if
  the left operand is shifted n times by
  1 for a shift count of n. As a result,
  x << 1 is the same as x*2 and x >> 1
  is the same as x/2 but truncated
  towards negative infinity.

A: The super (possibly over) simplified definition is just that << is used for "times 2" and >> is for "divided by 2" - and the number after it is how many times.
So n << x is "n times 2, x times". And y >> z is "y divided by 2, z times".
For example, 1 << 5 is "1 times 2, 5 times" or 32. And 32 >> 5 is "32 divided by 2, 5 times" or 1.

A: They are basically Arithmetic operators and its the same in other languages here is a basic PHP , C , Go Example
GO
package main

import (
    "fmt"
)

func main() {
    var t , i uint
    t , i = 1 , 1

    for i = 1 ; i < 10 ; i++ {
        fmt.Printf("%d << %d = %d \n", t , i , t<<i)
    }

    fmt.Println()

    t = 512
    for i = 1 ; i < 10 ; i++ {
        fmt.Printf("%d >> %d = %d \n", t , i , t>>i)
    }

}

GO Demo
C
#include <stdio.h>
int main()
{

    int t = 1 ;
    int i = 1 ;

    for(i = 1; i < 10; i++) {
        printf("%d << %d = %d \n", t, i, t << i);
    }

        printf("\n");

    t = 512;

    for(i = 1; i < 10; i++) {
        printf("%d >> %d = %d \n", t, i, t >> i);
    }

  return 0;
}

C Demo
PHP
$t = $i = 1;

for($i = 1; $i < 10; $i++) {
    printf("%d << %d = %d \n", $t, $i, $t << $i);
}

print PHP_EOL;

$t = 512;

for($i = 1; $i < 10; $i++) {
    printf("%d >> %d = %d \n", $t, $i, $t >> $i);
}

PHP Demo
They would all output
1 << 1 = 2
1 << 2 = 4
1 << 3 = 8
1 << 4 = 16
1 << 5 = 32
1 << 6 = 64
1 << 7 = 128
1 << 8 = 256
1 << 9 = 512

512 >> 1 = 256
512 >> 2 = 128
512 >> 3 = 64
512 >> 4 = 32
512 >> 5 = 16
512 >> 6 = 8
512 >> 7 = 4
512 >> 8 = 2
512 >> 9 = 1

A: From the spec at http://golang.org/doc/go_spec.html, it seems that at least with integers, it's a binary shift. for example, binary 0b00001000 >> 1 would be 0b00000100, and 0b00001000 << 1 would be 0b00010000.

Go apparently doesn't accept the 0b notation for binary integers. I was just using it for the example. In decimal, 8 >> 1 is 4, and 8 << 1 is 16. Shifting left by one is the same as multiplication by 2, and shifting right by one is the same as dividing by two, discarding any remainder.

A: n << x = n * 2^x   Example: 3 << 5 = 3 * 2^5 = 96
y >> z = y / 2^z   Example: 512 >> 4 = 512 / 2^4 = 32

A: << is the bitwise left shift operator ,which shifts the bits of corresponding integer to the left….the rightmost bit being '0' after the shift .
For example:
In gcc we have 4 bytes integer which means 32 bits .
like binary representation of 3 is
00000000 00000000 00000000 00000011
3<<1 would give
00000000 00000000 00000000 00000110 which is 6.
In general 1<<x would give you 2^x
In gcc
1<<20 would give 2^20 that is 1048576
but in tcc it would give you 0 as result because integer is of 2 bytes in tcc.
in simple terms we can take it like this in golang
So
n << x is "n times 2, x times". And y >> z is "y divided by 2, z times".
n << x = n * 2^x   Example:  3<< 5 = 3 * 2^5 = 96
y >> z = y / 2^z   Example: 512 >> 4 = 512 / 2^4 = 32

A: These are Right bitwise and left bitwise operators


text:
Q: SQL Server python Machine Learning cannot access filesystem SQL Server 2017 using sp_execute_external_script (SQL Server Machine Learning) to run a python script in the context of the database. python script needs to load a file from filesystem. Everything (the database and the filesystem) is local on my PC. Error trace:
Msg 39004, Niveau 16, État 20, Ligne 1
Une erreur de script « Python » s'est produite lors de l'exécution de « sp_execute_external_script » avec HRESULT 0x80004004.
Msg 39019, Niveau 16, État 2, Ligne 1
Une erreur de script externe s'est produite :
Error in execution.  Check the output for more information.
Traceback (most recent call last):
File "", line 5, in
File "C:\PROGRA~1\MICROS~3\MSSQL1~2.MSS\MSSQL\EXTENS~1\MSSQLSERVER201701\B2E71FC7-8E08-4D86-8B82-38AD564DBC9D\sqlindb.py", line 43, in transform
im = Image.open(adresse_image)

File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER2017\PYTHON_SERVICES\lib\site-packages\PIL\Image.py", line 2410, in open
fp = builtins.open(filename, "rb")

PermissionError: [Errno 13] Permission denied: 'C:\Users\aubertl\Downloads\plage_corse_2.jpg'
SqlSatelliteCall error: Error in execution.  Check the output for more information.
Message(s) STDOUT provenant du script externe :
Express Edition will continue to be enforced.
SqlSatelliteCall function failed. Please see the console output for more information.
Traceback (most recent call last):
File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER2017\PYTHON_SERVICES\lib\site-packages\revoscalepy\computecontext\RxInSqlServer.py", line 406, in rx_sql_satellite_call
rx_native_call("SqlSatelliteCall", params)

File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER2017\PYTHON_SERVICES\lib\site-packages\revoscalepy\RxSerializable.py", line 291, in rx_native_call
ret = px_call(functionname, params)

RuntimeError: revoscalepy function failed.

A: From Grant all application packages permissions on file folder:
Option 1: Interactive

*

*Launch Windows Explorer and right click on the target file folder.

*From context menu, select Properties.

*Switch to Security tab.

*Click Edit button.

*Click Add... to add ALL APPLICATION PACKAGES privileges.

*Tick Modify and/or Full Control to allow Read/Write to this directory.

Can also add Everyone to prevent any further issues.
Option 2: Command line
Adapted from StackOverflow answer, run this in an Administator command prompt:
icacls "X:\DataDir" /grant "ALL APPLICATION PACKAGES:(OI)(CI)F" /T

A: By default python services run under "NT Service\MSSQLLaunchpad". File is located in the "C:\Users\aubertl" folder, which is by default not accessible by MSSQLLaunchpad.
I would advice to create another directory, like C:\PytrhonScripts" and grant read access to this folder to MSSQLLaunchpad.

A: right click on directory -> grant access to -> Add "everyone". And then the script runs and produces the desired output. The user the service runs with (NT Service\MSSQLLaunchpad) cannot be added apparently, so this is a workaround.


text:
Q: Binding to event property 'onlyCurrentMonth' is disallowed for security reasons After enable enableIvy:true In my project I have used Angular-7 after enable ivy in tsconfig.json showing error

My tsconfig.json file:
{
     "compileOnSave": false,
     "compilerOptions": {
          "baseUrl": "./",
          "outDir": "./dist/out-tsc",
          "sourceMap": true,
          "declaration": false,
          "moduleResolution": "node",
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true,
          "target": "es5",
          "typeRoots": [
               "node_modules/@types"
          ],
          "lib": [
               "es2017",
               "dom"
          ]
     },
     "angularCompilerOptions": {
          "enableIvy": true
     }
}

In my project i have used BsDatepickerModule Module.
How to solve this issue ?

A: Remove the prefix "on" in "onlyCurrentMonth" and it will work.


text:
Q: Div innerHTML rewrite failure So I've been glad for the help I've gotten with this table thing from my previous questions; but I have ran into another problem. The way that the word generator works for the tool is that it generates a random number from 1-9 using math.random then rounds it with math.floor. Then, with that, the function changeRandom() aspect of that code grabs that number and changes the number to a random word based on that number, so that if the random number generated is 3, it will turn into Word 3. Now, I tried to do the same thing for the answers, but it seems to not change. Only thing that the debugging console gives me as an error is that gen_nums isn't defined for the getRandomAnswer(), yet when I remove it, it takes longer to process + there's an error about max file space or something. I need to have something similar done with the word selector functions to apply with the 9 boxes. Here's the code.
NOTE: The notes/comments in the codes can be ignored, as they are for reference for when I present this.
HTML

        <button id="myBtn">Randomize!</button>

Click this button to generate a random word!

JavaScript
/*function playSound()  {

}
*/
/* This section is for the first tool; the Randomizer.*/
/* This is the new function for getting a random number; also used in the getRandomAnswer() function. To select different numbers, adjust the range. */
function getRandom() {
  var nums = [1,2,3,4,5,6,7,8,9];
  var gen_nums = [];

  function in_array(array, el) {
    for(var i = 0 ; i < array.length; i++)
      if(array[i] == el) return true;
    return false;
  }

  function get_rand(array) {
    var rand = array[Math.floor(Math.random()*array.length)];
    if(!in_array(gen_nums, rand)) {
      gen_nums.push(rand);
      return rand;
    }
    return get_rand(array);
  }

  for(var i = 0; i < 9; i++) {
    return (get_rand(nums));
  }
}
function timeOut(){
  /* This can be ignored, as it was a testing function for creating, making, and fixing the randomizer tool, but may change based on creating new tools that need to be troubleshooted. */
  setTimeout (changeRandom, 1);
}
/* This is the function that grabs the innerHTML (what the box says) of the #output1 and changes that number to the word specified. [In example, if the number [randomly] generated was 5, then this function detects that the number was 5 and changes it to Word 5.]  */
function changeRandom()  {
  /* Using the "var x" command, this tells the function that whenever there's an x in the code, it will read it as "document.getElementById('output1').innerHTML", and will grab whatever is inside that #output1 element. */
  var x = document.getElementById('outputNumber').innerHTML
  /* Here's the tutorial for modifying this tool for the possible answers. This tool [by default] has it set to  */
  if(x == 1)  {
    document.getElementById("outputNumber").innerHTML = "Word 1";
  } else if(x == 2)  {
    document.getElementById("outputNumber").innerHTML = "Word 2";
  } else if(x == 3)  {
    document.getElementById("outputNumber").innerHTML = "Word 3";
  } else if(x == 4)  {
    document.getElementById("outputNumber").innerHTML = "Word 4"
  } else if(x == 5) {
    document.getElementById("outputNumber").innerHTML = "Word 5"
  }
  else if(x == 6) {
    document.getElementById("outputNumber").innerHTML = "Word 6"
  }
  else if(x == 7) {
    document.getElementById("outputNumber").innerHTML = "Word 7"
  }
  else if(x == 8) {
    document.getElementById("outputNumber").innerHTML = "Word 8"
  }
  else if(x == 9) {
    document.getElementById("outputNumber").innerHTML = "Word 9"
  }
  else if(x == 10) {
    document.getElementById("outputNumber").innerHTML = "Word 10"
  }
  /* If the function is broken [by user modifications], it will output "Error :c", which means the user should check their modifications. */
  else  {
    document.getElementById("output1").innerHTML = "Error :c"
  }
}
document.getElementById("myBtn").addEventListener("click", function(){document.getElementById("outputNumber").innerHTML = getRandom(); changeRandom();})
function testFunction()  {
  if(document.getElementById("output1").innerHTML == 3)  {
    document.getElementById("output1").innerHTML = "Three";
  }
  else  {
    document.getElementById("output1").innerHTML = "N3"
  }
}
function getRandomAnswer() {
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var copy = nums.slice();

  for (var i = 0, len = nums.length; i < len; i++) {
    var j = Math.floor(Math.random() * copy.length);
    var rand = copy[ j ];

    // remove from array
    copy.splice(j, 1);

    // add to output
    document.getElementById('output' + (i + 1)).innerHTML = rand;
  }
  return gen_nums;
  document.getElementById('output' + (i + 1)).innerHTML = getRandomAnswer();
}
function changeRandomAnswer()  {
  /* Using the "var x" command, this tells the function that whenever there's an x in the code, it will read it as "document.getElementById('output1').innerHTML", and will grab whatever is inside that #output1 element. */
  /* Here's the tutorial for modifying this tool for the possible answers. This tool [by default] has it set to  */
  if(document.getElementById("output1").innerHTML = "1")  {
    document.getElementById("output1").innerHTML = "Answer 1";
  }
  else if(document.getElementById("output1").innerHTML = "2")  {
    document.getElementById("output2").innerHTML = "Answer 2";
  }
  else if(document.getElementById("output1").innerHTML = "3")  {
    document.getElementById("output3").innerHTML = "Answer 3";
  }
  else if(document.getElementById("output1").innerHTML = "4")  {
    document.getElementById("output4").innerHTML = "Answer 4"
  }
  else if(document.getElementById("output1").innerHTML = "5") {
    document.getElementById("output5").innerHTML = "Answer 5"
  }
  else if(document.getElementById("output1").innerHTML = "6") {
    document.getElementById("output6").innerHTML = "Answer 6"
  }
  else if(document.getElementById("output1").innerHTML = "7") {
    document.getElementById("output7").innerHTML = "Answer 7"
  }
  else if(document.getElementById("output1").innerHTML = "8") {
    document.getElementById("output8").innerHTML = "Answer 8"
  }
  else if(document.getElementById("output1").innerHTML = "9") {
    document.getElementById("output9").innerHTML = "Answer 9"
  }
  /* If the function is broken [by user modifications], it will output "Error :c", which means the user should check their modifications. */
  else  {
    document.getElementById("output1").innerHTML = "Error :c"
  }
}
document.getElementById("myBtn").addEventListener("click", function(){document.getElementById("answers").innerHTML = getRandomAnswer(); changeRandomAnswer();})

Here's a workable codepen to work with.

A: You having some scoping issue and a recursion issue. To simplify:
function foo() {
  var gen_nums = [];

  for ( var i=0; i<10; i++ ) {
    gen_nums.push(i)
  }

  return gen_nums;
}

function bar() {
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var copy = nums.slice();

  return gen_nums;
  bar()
}

console.log(foo()) // [0, ..., 9]
console.log(bar()) // error - gen_nums is not defined

The reason why removing it from getRandomAnswer() makes things take longer, is because when it is there, the function stops at that line, and not reaching the next line, which is
document.getElementById('output' + (i + 1)).innerHTML = getRandomAnswer();
which makes the function recursive.

A: Your getRandomAnswer Function is
function getRandomAnswer() {
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var copy = nums.slice();

  for (var i = 0, len = nums.length; i < len; i++) {
    var j = Math.floor(Math.random() * copy.length);
    var rand = copy[ j ];

    // remove from array
    copy.splice(j, 1);

    // add to output
    document.getElementById('output' + (i + 1)).innerHTML = rand;
  }
  return gen_nums;
  document.getElementById('output' + (i + 1)).innerHTML = getRandomAnswer();
}

In this you are returning gen_nums before some code execution. So write it like,
function getRandomAnswer() {
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var copy = nums.slice();

  for (var i = 0, len = nums.length; i < len; i++) {
    var j = Math.floor(Math.random() * copy.length);
    var rand = copy[ j ];

    // remove from array
    copy.splice(j, 1);

    // add to output
    document.getElementById('output' + (i + 1)).innerHTML = rand;
  }
    document.getElementById('output' + (i + 1)).innerHTML = getRandomAnswer();
  return gen_nums;

}

here is your working code in jsfiddle.

A: There are a few things the code you provided is doing that are unnecessary.

*

*On the last line, you dont need to assign an output from getRandomAnswer() to the innerHTML of "answers". The function itself is already performing the operation to assign the random numbers to each output. You can simply just call the function:
document.getElementById("myBtn").addEventListener("click", function(){ getRandomAnswer(); changeRandomAnswer();})

*Within the function of getRandomAnswer(), you can remove return gen_numbers; and you can remove the line:
document.getElementById('output' + (i + 1)).innerHTML = getRandomAnswer();
This is causing the recursion and is completely not necessary since the numbers are getting applied in the for loop just before.

The function changeRandomAnswer() has some issues that need to be addressed:

*

*First off you are defining instead of comparing the contents of innerHTML within each if condition by using one equal sign(=) instead of two(==).

*The way you have the logic set up, it will only apply to the first box it matches and skip the rest. You are also only ever checking for the innerHTML value of "output1".

One solution is to loop through each element and run the same conditional check on each element:
function changeRandomAnswer()  {

  var answers = document.getElementById("answers");

  for(var i = 0, len = answers.children.length; i < len; i++) {
    var output = answers.children[i];
    var answer = output.innerHTML;

    if(answer == "1")  {
      output.innerHTML = "Answer 1";
    }
    else if(answer == "2")  {
      output.innerHTML = "Answer 2";
    }
    else if(answer == "3")  {
      output.innerHTML = "Answer 3";
    }
    else if(answer == "4")  {
      output.innerHTML = "Answer 4"
    }
    else if(answer == "5") {
      output.innerHTML = "Answer 5"
    }
    else if(answer == "6") {
      output.innerHTML = "Answer 6"
    }
    else if(answer == "7") {
      output.innerHTML = "Answer 7"
    }
    else if(answer == "8") {
      output.innerHTML = "Answer 8"
    }
    else if(answer == "9") {
      output.innerHTML = "Answer 9"
    }
    else  {
      output.innerHTML = "Error :c"
    }
  }
}

Here is the full javascript with all edits mentioned (Also I forked a working version on codepen here):
/*function playSound()  {

}
*/
/* This section is for the first tool; the Randomizer.*/
/* This is the new function for getting a random number; also used in the getRandomAnswer() function. To select different numbers, adjust the range. */
function getRandom() {
  var nums = [1,2,3,4,5,6,7,8,9];
  var gen_nums = [];

  function in_array(array, el) {
    for(var i = 0 ; i < array.length; i++)
      if(array[i] == el) return true;
    return false;
  }

  function get_rand(array) {
    var rand = array[Math.floor(Math.random()*array.length)];
    if(!in_array(gen_nums, rand)) {
      gen_nums.push(rand);
      return rand;
    }
    return get_rand(array);
  }

  for(var i = 0; i < 9; i++) {
    return (get_rand(nums));
  }
}
function timeOut(){
  /* This can be ignored, as it was a testing function for creating, making, and fixing the randomizer tool, but may change based on creating new tools that need to be troubleshooted. */
  setTimeout (changeRandom, 1);
}
/* This is the function that grabs the innerHTML (what the box says) of the #output1 and changes that number to the word specified. [In example, if the number [randomly] generated was 5, then this function detects that the number was 5 and changes it to Word 5.]  */
function changeRandom()  {
  /* Using the "var x" command, this tells the function that whenever there's an x in the code, it will read it as "document.getElementById('output1').innerHTML", and will grab whatever is inside that #output1 element. */
  var x = document.getElementById('outputNumber').innerHTML
  /* Here's the tutorial for modifying this tool for the possible answers. This tool [by default] has it set to  */
  if(x == 1)  {
    document.getElementById("outputNumber").innerHTML = "Word 1";
  } else if(x == 2)  {
    document.getElementById("outputNumber").innerHTML = "Word 2";
  } else if(x == 3)  {
    document.getElementById("outputNumber").innerHTML = "Word 3";
  } else if(x == 4)  {
    document.getElementById("outputNumber").innerHTML = "Word 4"
  } else if(x == 5) {
    document.getElementById("outputNumber").innerHTML = "Word 5"
  }
  else if(x == 6) {
    document.getElementById("outputNumber").innerHTML = "Word 6"
  }
  else if(x == 7) {
    document.getElementById("outputNumber").innerHTML = "Word 7"
  }
  else if(x == 8) {
    document.getElementById("outputNumber").innerHTML = "Word 8"
  }
  else if(x == 9) {
    document.getElementById("outputNumber").innerHTML = "Word 9"
  }
  else if(x == 10) {
    document.getElementById("outputNumber").innerHTML = "Word 10"
  }
  /* If the function is broken [by user modifications], it will output "Error :c", which means the user should check their modifications. */
  else  {
    document.getElementById("output1").innerHTML = "Error :c"
  }
}
document.getElementById("myBtn").addEventListener("click", function(){document.getElementById("outputNumber").innerHTML = getRandom(); changeRandom();})
function testFunction()  {
  if(document.getElementById("output1").innerHTML == 3)  {
    document.getElementById("output1").innerHTML = "Three";
  }
  else  {
    document.getElementById("output1").innerHTML = "N3"
  }
}
function getRandomAnswer() {
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var copy = nums.slice();

  for (var i = 0, len = nums.length; i < len; i++) {
    var j = Math.floor(Math.random() * copy.length);
    var rand = copy[ j ];

    // remove from array
    copy.splice(j, 1);

    // add to output
    document.getElementById('output' + (i + 1)).innerHTML = rand;
  }
  //return gen_nums;
  //document.getElementById('output' + (i + 1)).innerHTML = getRandomAnswer();
}
function changeRandomAnswer()  {

  var answers = document.getElementById("answers");

  for(var i = 0, len = answers.children.length; i < len; i++) {
    var output = answers.children[i];
    var answer = output.innerHTML;

    if(answer == "1")  {
      output.innerHTML = "Answer 1";
    }
    else if(answer == "2")  {
      output.innerHTML = "Answer 2";
    }
    else if(answer == "3")  {
      output.innerHTML = "Answer 3";
    }
    else if(answer == "4")  {
      output.innerHTML = "Answer 4"
    }
    else if(answer == "5") {
      output.innerHTML = "Answer 5"
    }
    else if(answer == "6") {
      output.innerHTML = "Answer 6"
    }
    else if(answer == "7") {
      output.innerHTML = "Answer 7"
    }
    else if(answer == "8") {
      output.innerHTML = "Answer 8"
    }
    else if(answer == "9") {
      output.innerHTML = "Answer 9"
    }
    else  {
      output.innerHTML = "Error :c"
    }
  }

}
document.getElementById("myBtn").addEventListener("click", function(){ getRandomAnswer(); changeRandomAnswer();})


text:
Q: What is this type of data with CENG prefix related to GEOLOCATION of a M2M SIM CARD? I'm troubleshooting an old proprietary software, and in the GEOLOCATION tab - which reports machines we have around the world - I found this piece of data for each machine:

So basically, for each machine I want to check, I get a data similar to this one above. I do not have the knowledge to interpret what is means.
Geolocation data is sent through a M2M SIM CARD installed in each machine.
I was expecting a COORDINATES info with a DATE/TIME attached to it. But this CENG information doesn't ring a bell for me.
What could it possibly mean? How should I interpret it?
Thank you!

A: What could it possibly mean? How should I interpret it?

The AT+CENG command is used to turn on the engineering (engg) mode to
get detailed network information.
The following info is available:

*

*Frequency channel number,

*Receive level,

*Receive quality,

*Mobile country code,

*Mobile network code,

*Base station identify code,

*Cell id,

*Location area code,

*Receive level access minimum,

*Transmit power maximum,

*Timing advance.

Source: AT+CENG – Switch on or off engineering mode | M2MSupport.net
Further Reading: Tutorial for SIMCOM M2M Modules | M2MSupport.net


text:
Q: Select multiple dates in Android DatePickerDialog I've got a requirement to select multiple dates from Android DatePickerDialog. Below is my snippet. With this, I'm able to select only one date. I've seen other libraries like https://github.com/square/android-times-square. But, I'm more interested in native Android code.
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val currentDate = Calendar.getInstance()
        val year = currentDate.get(Calendar.YEAR)
        val month = currentDate.get(Calendar.MONTH)
        val day = currentDate.get(Calendar.DAY_OF_MONTH)

        val maxDate = Calendar.getInstance()
        maxDate.add(Calendar.MONTH, 3)

        val datePickerDialog = DatePickerDialog(activity, onDateSet, year, month, day)
        datePickerDialog.datePicker.minDate = currentDate.timeInMillis
        datePickerDialog.datePicker.maxDate = maxDate.timeInMillis

        return datePickerDialog
}

A: Android doesn't support this feature by till date. You can however create you own calendar. I have the same requirement and have done this. Please note that I have not allowed user to select any date. But users can select custom dates. I have created a Fragment which only changes months, and so it changes the adapter as when month is changed.
public class CalendarFragment extends DialogFragment {

private final String TAG = CalendarFragment.class.getSimpleName();

private static CalendarFragment instance;
private View view;
private ImageView ivDecrementMonth, ivIncrementMonth;
private TextView btnOk, btnCancel;
public TextView tvMonthYear;
private int counter = 0;
private int year = 2017;
private static CalendarActivity INSTANCE;

private Calendar calendarMinimumDate, calendarMaximumDate;

private GridView gridCalendarView;
private ArrayList<EventDateSelectionBean> listEventDates;
private String from;

public static final String KEY_EVENT_DATES = "key event dates";
public static final String KEY_FROM = "key from";

public static final String FROM_ANNOUNCEMENT_ACTIVITY = "from announcement activity";
public static final String FROM_BOOKING_DIALOG = "from booking dialog";
private List<String> listMonths;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    WindowManager.LayoutParams wlmp = dialog.getWindow().getAttributes();
    wlmp.gravity = Gravity.CENTER | Gravity.FILL_HORIZONTAL;
    wlmp.dimAmount = 0.0F;
    dialog.getWindow().setAttributes(wlmp);
    dialog.getWindow().setWindowAnimations(R.style.DialogTheme);
    dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    return dialog;
}
//End of onCreateDialog()

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (view == null) {
        instance = this;
        view = inflater.inflate(R.layout.activity_calendar, container);
        findViewsId();
        setData();
        setClickListeners();
    }

    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();

    return view;
}
//End of onCreateView()

private void findViewsId() {

    ivDecrementMonth = (ImageView) view.findViewById(R.id.ivDecrementMonth);
    ivIncrementMonth = (ImageView) view.findViewById(R.id.ivIncrementMonth);
    gridCalendarView = (GridView) view.findViewById(R.id.calendar);
    tvMonthYear = (TextView) view.findViewById(R.id.tvMonthYear);
    btnOk = (TextView) view.findViewById(R.id.btnOk);
    btnCancel = (TextView) view.findViewById(R.id.btnCancel);

}
//End of findViewsId()

private void setData() {
    listMonths = Arrays.asList(getResources().getStringArray(R.array.months));

    Bundle bundle = getArguments();

    calendarMinimumDate = Calendar.getInstance();
    calendarMinimumDate.setTimeInMillis(System.currentTimeMillis());
    calendarMaximumDate = Calendar.getInstance();
    calendarMaximumDate.setTimeInMillis(System.currentTimeMillis());

    btnOk.setText(getString(R.string.ok));
    btnCancel.setText(getString(R.string.cancel));

    listEventDates = bundle.getParcelableArrayList(KEY_EVENT_DATES);
    from = bundle.getString(KEY_FROM);

    //setMinMaxDateCalendar();

    counter = calendarMinimumDate.get(Calendar.MONTH);
    year = calendarMinimumDate.get(Calendar.YEAR);
    tvMonthYear.setText(listMonths.get(counter) + " " + year);

    MyCalendarAdapter adapter = new MyCalendarAdapter(GoToTourActivity.getInstance(),
            listEventDates, counter, year);
    gridCalendarView.setAdapter(adapter);
}
//End of setData()

private void setClickListeners() {
    btnOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (from.equals(FROM_ANNOUNCEMENT_ACTIVITY)) {
                GoToTourActivity.getInstance().setDate(listEventDates);
            } else if (from.equals(FROM_BOOKING_DIALOG)) {
                BookDialogs.getInstance().setDate(listEventDates);
            }
            dismiss();
        }
    });

    btnCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
        }
    });

    ivDecrementMonth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (counter == 0) {
                counter = listMonths.size() - 1;
                year = year - 1;
            } else {
                counter--;
            }
            tvMonthYear.setText(listMonths.get(counter) + " " + year);
            updateCalendar();
        }
    });

    ivIncrementMonth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (counter == (listMonths.size() - 1)) {
                counter = 0;
                year = year + 1;
            } else {
                counter++;
            }
            tvMonthYear.setText(listMonths.get(counter) + " " + year);
            updateCalendar();
        }
    });
}
//End of setClickListeners()

private void updateCalendar() {
    MyCalendarAdapter adapter = new MyCalendarAdapter(GoToTourActivity.getInstance(),
            listEventDates, counter, year);
    gridCalendarView.setAdapter(adapter);
}
//End of updateCalendar()

}
//Here is the layout of Fragment Calendar
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.1"
    android:background="#FFF"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="1">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2"
        android:background="#FFF"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/llPrev"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/margin">

            <ImageButton
                android:id="@+id/back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:padding="1dp"
                android:src="@drawable/slide_right" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.6"
        android:gravity="center">

        <TextView
            android:id="@+id/tvMonthYear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="DECEMBER 2017"
            android:textAllCaps="false"
            android:textColor="#000"
            android:textSize="22dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2"
        android:background="#FFF"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/llNext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/margin">

            <ImageButton
                android:id="@+id/forw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:padding="1dp"
                android:rotation="180"
                android:src="@drawable/slide_right" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:id="@+id/llcalender"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.9"
    android:background="#FFF">

    <GridView
        android:id="@+id/calgrid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="7">

    </GridView>
</LinearLayout>

And the most important part is the Gridview Adapter. Go through the code and try to understand, there is not anything that would trouble you. However if you have any problem. Please comment.
public MyCalendarAdapter(Context context, ArrayList<EventDateSelectionBean> listEvents, int month, int year) {
    super();
    this._context = context;
    dateDefaultTextColor = context.getResources().getColor(R.color.calendar_date_default_text_color);
    dateInEventTextColor = context.getResources().getColor(R.color.calendar_date_in_event_text_color);
    dateInEventSelectedTextColor = context.getResources().getColor(R.color.calendar_date_in_event_selected_text_color);

    this.list = new ArrayList<>();
    Calendar calendar = Calendar.getInstance();
    setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
    setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
    this.listEvents = listEvents;

    currentMonth = month;
    currentYear = year;

    // Print Month
    printMonth(month, year);

    eventCalendar = Calendar.getInstance();
    eventCalendar.setTimeInMillis(System.currentTimeMillis());
    currentDayCalendar = Calendar.getInstance();
    currentDayCalendar.setTimeInMillis(System.currentTimeMillis());

    currentDayCalendar.set(Calendar.MONTH, currentMonth);
    currentDayCalendar.set(Calendar.YEAR, currentYear);
}

private String getMonthAsString(int i) {
    return months[i];
}

private int getNumberOfDaysOfMonth(int i) {
    if (currentYear % 4 == 0 && i == 1) {
        return daysOfMonth[i] + 1;
    } else {
        return daysOfMonth[i];
    }
}

public String getItem(int position) {
    return list.get(position);
}

@Override
public int getCount() {
    return list.size();
}

private void printMonth(int mm, int yyyy) {
    int trailingSpaces = 0;
    int daysInPrevMonth = 0;
    int prevMonth = 0;
    int prevYear = 0;
    int nextMonth = 0;
    int nextYear = 0;

    int currentMonth = mm/* - 1*/;
    daysInMonth = getNumberOfDaysOfMonth(currentMonth);

    // Gregorian Calendar : MINUS 1, set to FIRST OF MONTH
    GregorianCalendar cal = new GregorianCalendar(yyyy, currentMonth, 1);

    if (currentMonth == 11) {
        prevMonth = currentMonth - 1;
        daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
        nextMonth = 0;
        prevYear = yyyy;
        nextYear = yyyy + 1;
    } else if (currentMonth == 0) {
        prevMonth = 11;
        prevYear = yyyy - 1;
        nextYear = yyyy;
        daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
        nextMonth = 1;
    } else {
        prevMonth = currentMonth - 1;
        nextMonth = currentMonth + 1;
        nextYear = yyyy;
        prevYear = yyyy;
        daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
    }

    int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
    trailingSpaces = currentWeekDay;

    // Trailing Month days
    for (int i = 0; i < trailingSpaces; i++) {
        list.add(String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i) + "-GREY" + "-" + getMonthAsString(prevMonth) + "-" + prevYear);
    }

    // Current Month Days
    for (int i = 1; i <= daysInMonth; i++) {
        if (i == getCurrentDayOfMonth())
            list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthAsString(currentMonth) + "-" + yyyy);
        else
            list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(currentMonth) + "-" + yyyy);
    }

    // Leading Month days
    for (int i = 0; i < list.size() % 7; i++) {
        list.add(String.valueOf(i + 1) + "-GREY" + "-" + getMonthAsString(nextMonth) + "-" + nextYear);
    }
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //Blue - Current Day
    //White - Current Month
    //Grey - Next Month
    final ViewHolder holder;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    // ACCOUNT FOR SPACING
    String[] day_color = list.get(position).split("-");
    String theday = day_color[0];

    // Set the Day GridCell
    holder.btnDate.setText(theday);

    if (day_color[1].equals("WHITE") || day_color[1].equals("BLUE")) {      //For Current Month
        holder.btnDate.setTextColor(dateDefaultTextColor);
        holder.btnDate.setBackgroundResource(R.drawable.date_default_bg);

        currentDayCalendar.set(Calendar.DAY_OF_MONTH, Integer.valueOf(theday));

        for (int i = 0; i < listEvents.size(); i++) {

            EventDateSelectionBean eventDate = listEvents.get(i);
            setDataInEventCalendar(eventDate.getDate());

            if(Commons.checkDateEquality(currentDayCalendar, eventCalendar)) {

                final EventDateSelectionBean finalEventDate = eventDate;
                if(finalEventDate.isSelected()) {
                    holder.btnDate.setBackgroundResource(R.drawable.date_selected_bg);
                    holder.btnDate.setTextColor(dateInEventSelectedTextColor);

                } else {
                    holder.btnDate.setBackgroundResource(R.drawable.date_unselected);
                    holder.btnDate.setTextColor(dateInEventTextColor);
                }

                holder.btnDate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(finalEventDate.isSelected()) {
                            finalEventDate.setSelected(false);
                            holder.btnDate.setBackgroundResource(R.drawable.date_unselected);
                            holder.btnDate.setTextColor(dateInEventTextColor);

                        } else {
                            finalEventDate.setSelected(true);
                            holder.btnDate.setBackgroundResource(R.drawable.date_selected_bg);
                            holder.btnDate.setTextColor(dateInEventSelectedTextColor);
                        }
                    }
                });
                break;
            }
        }
    } else {       //For Previous and next month dates
        holder.btnDate.setAlpha(0.4f);
        holder.btnDate.setBackgroundResource(R.drawable.date_default_bg);
        //holder.btnDate.setVisibility(View.INVISIBLE);
        holder.llBtnParent.setVisibility(View.INVISIBLE);
    }

    if (position == list.size() - 1) {
        //Set Default data
    }
    return convertView;
}
//End of getView()

public class ViewHolder {
    Button btnDate;
    LinearLayout llBtnParent;

    public ViewHolder(View view) {
        btnDate = (Button) view.findViewById(R.id.calendar_day_gridcell);
        llBtnParent = (LinearLayout) view.findViewById(R.id.llBtnParent);
    }
}

public int getCurrentDayOfMonth() {
    return currentDayOfMonth;
}

private void setCurrentDayOfMonth(int currentDayOfMonth) {
    this.currentDayOfMonth = currentDayOfMonth;
}

public void setCurrentWeekDay(int currentWeekDay) {
    this.currentWeekDay = currentWeekDay;
}

private void setDataInEventCalendar(String date) {
    String splittedDate[] = date.split("-");
    eventCalendar.set(Calendar.YEAR, Integer.valueOf(splittedDate[0]));
    eventCalendar.set(Calendar.MONTH, (Integer.valueOf(splittedDate[1]) - 1));
    eventCalendar.set(Calendar.DAY_OF_MONTH, Integer.valueOf(splittedDate[2]));

}
//End of setDataInEventCalendar()

}
Adapter layout is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_margin="1dp"
android:background="@android:color/transparent"
android:id="@+id/llBtnParent">

<LinearLayout
    android:layout_width="44dp"
    android:layout_height="44dp"
    android:layout_margin="1dp"
    android:background="@drawable/day_calendar"
    android:padding="1dp"
    android:gravity="center">

    <com.yaashvi.placeandpeople.customviews.AttendanceButton
        android:id="@+id/calendar_day_gridcell"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:text="1"
        android:gravity="left"
        android:paddingLeft="2dp"
        android:textSize="12sp"/>
</LinearLayout>

The Output will be like that.

A: Also, you can try this repository which i have done so far in my own project
https://github.com/Diwakarsingh9/MultiDatePickerCalendar


text:
Q: How to create an Angularjs controller within a meteor app? I'm working in a meteor app project and I would like to integrate angularjs, I'm using urigo:ngmeteor to avoid conflict between these two frameworks, this is my code so far
//[root]/app.html

Product Name: [[store.name]]

Product Price: $[[store.price]]

Product Description: [[store.description]]

//[root]/client/js/app/js
   (function(){
       var app = angular.module('store', [], function(){ });
       var gem = {
           name: 'Dodecahendro',
           price: 2.95,
           description: '...'
       };
       console.log($("#mybody").length);
       app.controller('StoreController', function($scope){
           $scope.product = gem;
       });
    })();

but when I run it, I got this error message:

Error: [ng:areq] Argument 'StoreController' is not a function, got
  undefined

and for the console.log() output I got 0
so, the question is, what am I missing?
thanks!


text:
Q: Youtube video downloader for iPhone I need to create a downloaded application for iPhone. Many of application is already in itune with same purpose. When any video play in UIWebView player, then i have to show option for downloading video. For downloading video i need URL which is playing in Player.
What i tried yet
i have found nothing, i got Notification which tell me that player is in full screen or not (UIMoviePlayerControllerDidEnterFullscreenNotification).  I have tried with web view delegate methods for URL but it is not giving me any video URL. it print on console "setting movie path:"  but it is not giving full path for downlaod


text:
Q: Can't send a variable to javascript from java I'm fetching a url and trying to send it's text content to a javascript function inside a webview.
I do this from the java code:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://volteck.net");
// Get the response
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response_str = client.execute(request, responseHandler);

response_str = response_str.replaceAll("\n", "\\");
// this is because js don't support multi-line strings

myWebView.loadUrl("javascript:myfunction('" + response_str + "')");
System.out.println("javascript:myfunction('" + response_str + "')");

This is code that is inside the webview:
function myfunction(val){
    document.body.innerHTML = val.length;
    }

So far I'm only trying to get the text length. But when I use the url of previous code, nothing happens. and I get this from the log:
08-19 23:55:03.141: I/dalvikvm-heap(1846): Grow heap (frag case) to 3.551MB for 262160-byte allocation
08-19 23:55:03.351: D/dalvikvm(1846): GC_FOR_MALLOC freed 0 objects / 0 bytes in 209ms
But the weird thing is that if I attempt to fetch volteck.net/ip, that only contains an IP number, it works just fine!
Thanks a lot from a Java newbie.

A: Try this:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String script = "function myfunction(val){
document.body.innerHTML = val.length;
}";
engine.eval(script);
Invocable inv = (Invocable) engine;
inv.invokeFunction("myfunction", response_str );


text:
Q: Group in Python Pandas based on a date filter I have the following dataframe.
I need to group by ID adding the PROFIT column based on the last 30 and 60 days.
import pandas as pd
df = pd.DataFrame({"ID":[1,1,1,1,2,2,2,2],"DATE":['2019-04-03','2019-03-03','2019-03-01','2019-02-03','2019-02-01','2019-01-01','2019-01-06','2019-04-03'],"PROFIT":[10,20,30,60,90,100,20,10]})

    ID  DATE    PROFIT
0   1   2019-04-03  10
1   1   2019-03-03  20
2   1   2019-03-01  30
3   1   2019-02-03  60
4   2   2019-02-01  90
5   2   2019-01-01  100
6   2   2019-01-06  20
7   2   2019-04-03  10

Final Result:
df_end = pd.DataFrame({"ID":[1,1,2,2],"TIME":[30,60,30,60],"SUM_PROFIT":[10,60,10,90]})

    ID  TIME    SUM_PROFIT
0   1   30      10
1   1   60      60
2   2   30      10
3   2   60      90

A: IIUC, then you can try something like this:
timespan = [30, 60]
pd.concat([df.sort_values('DATE', ascending=False)
             .groupby(['ID'])
             .apply(lambda x: x.loc[x['DATE'].head(1).values[0]-x['DATE']<=pd.Timedelta(days=t),'PROFIT'].sum())
             .rename('SUM_PROFIT').reset_index().assign(TIME = t) for t in timespan],
          ignore_index=True)

Output:
   ID  SUM_PROFIT  TIME
0   1          10    30
1   2          10    30
2   1         120    60
3   2          10    60


text:
Q: How to get a column name based on function Suppose I have a dataset:
A B C Final
1 2 3 C
4 5 6 C

I want final to return the column name of the max value. In the example above, 3 and 6 are the highest values, so columns C will be returned in the 'Final' column.Is there an efficient way/formula you can use to get the column names without using VBA? the real dataset containts 60 columns.

A: I would try something like this to get the column letter.
=SUBSTITUTE(ADDRESS(1,MATCH(MAX(A3:C3),A3:C3,0),4),1,"")

If you want the header, I think there's an easier way, but the extension from this would be
=INDIRECT(SUBSTITUTE(ADDRESS(1,MATCH(MAX(A3:C3),A3:C3,0),4),1,"")&1)

For the header, the better way
=INDEX(A1:C1,1,MATCH(MAX(A3:C3),A3:C3,0))

A: HLOOKUP is a way without VBA, but sadly HLOOKUP does only search in the first row of the array, so you should add the "title column" at the bottom
A B C Final
1 2 3 <formula1>
4 5 6 <formula2>
A B C

If the dataset starts at first corner, Formula1 would be :
=HLOOKUP(MAX(A2:C2);A2:C4;2;FALSE)

Formula2 will be
=HLOOKUP(MAX(A3:C3);A3:C4;1;FALSE)

etc...
=HLOOKUP(MAX($A3:$C3);$A3:$C$4;<manual change here backward>;FALSE)

A: You can use the vector form of the LOOKUP function.
If your first row, with A B C, are the labels, then:
=LOOKUP(2, 1/(MAX(A2:C2)=A2:C2),$A$1:$C$1)