text:
Q: Trouble accessing python dictionary elements I have the following dict:
b = {None: u'{"TimeStamp":"2017-01-30T13:50:22.3854765+00:00","RealEstate":          {"Id":"fa9ba4d0-3e69-46f0-9460-05d6b2ff1211","Name":"Building 1","Room":"Room     1","Device":{"Id":"fa9ba4d0-3e69-46f0-9460-08d6b2ff6408","Payload":{"Temperature":{"Unit":"C","Value":32.3},"Humidity":{"Unit":"%","Value":12},"Light":{"Unit":"lux","Value":154},"Motion":{"Unit":"Number of motion","Value":0},"Co2":null}}},"Message":null}'}

And cant access any elements. Tried both b['None'], b['u'] and b['TimeStamp'] which all generates:
ERROR: ..../sparkstream.py", line 24, in test
    c = b['u']

KeyError: 'u'
Any tips!?

A: What you have a a dictionary with one key, which you can access the value via b[None]. This value in turn, is a string, not a dictionary. In order to get the dictionary, you will have to use JSON to decode it:
import json

b = {None: u'{"TimeStamp":"2017-01-30T13:50:22.3854765+00:00","RealEstate":          {"Id":"fa9ba4d0-3e69-46f0-9460-05d6b2ff1211","Name":"Building 1","Room":"Room     1","Device":{"Id":"fa9ba4d0-3e69-46f0-9460-08d6b2ff6408","Payload":{"Temperature":{"Unit":"C","Value":32.3},"Humidity":{"Unit":"%","Value":12},"Light":{"Unit":"lux","Value":154},"Motion":{"Unit":"Number of motion","Value":0},"Co2":null}}},"Message":null}'}
dict_object = json.loads(b[None])
print json.dumps(dict_object, indent=2)  # Show the decoded result

# Accessing some keys
print '---'
print 'Time stamp:', dict_object['TimeStamp']
print 'Real Estate ID:', dict_object['RealEstate']['Id']
print 'Device ID:', dict_object['RealEstate']['Device']['Id']

Output:
{
  "TimeStamp": "2017-01-30T13:50:22.3854765+00:00",
  "Message": null,
  "RealEstate": {
    "Device": {
      "Id": "fa9ba4d0-3e69-46f0-9460-08d6b2ff6408",
      "Payload": {
        "Motion": {
          "Value": 0,
          "Unit": "Number of motion"
        },
        "Light": {
          "Value": 154,
          "Unit": "lux"
        },
        "Co2": null,
        "Temperature": {
          "Value": 32.3,
          "Unit": "C"
        },
        "Humidity": {
          "Value": 12,
          "Unit": "%"
        }
      }
    },
    "Room": "Room     1",
    "Id": "fa9ba4d0-3e69-46f0-9460-05d6b2ff1211",
    "Name": "Building 1"
  }
}
---
Time stamp: 2017-01-30T13:50:22.3854765+00:00
Real Estate ID: fa9ba4d0-3e69-46f0-9460-05d6b2ff1211
Device ID: fa9ba4d0-3e69-46f0-9460-08d6b2ff6408

A: The Dictionary which you shared has only one key, an object of type None. To access it you simply type: b[None] the value returned from that call will be the whole string prefixed with u'...'.
You can't access the elements in it because this is just a Unicode string, not a python dictionary. You need to convert this JSON string to a dictionary and you can find instructions here:
https://pythonspot.com/json-encoding-and-decoding-with-python/
Hope this helps


text:
Q: Confusion with void* type memory allocation? I am pretty inexperienced in C++ programming and now I'm trying to make a small program using dctmk to modify the pixel data of the dicom image. In doing so while reading documentation I found a c++ method about which I'm not quite clear. In the documention for the class DicomImage I found the following method:
int DicomImage::getOutputData   (   void *      buffer,
        const unsigned long     size,
        const int   bits = 0,
        const unsigned long     frame = 0,
        const int   planar = 0
    )

My confusion is about buffer. It's quoted in the link as

buffer :    pointer to memory buffer (must already be allocated)

Here my confusion is how do a I allocate? I'm not sure how I could allocate a memory that's a pointer of void type. Could you please explain. Thank you.

A: You can do it in the following way (for example):
void * mem = malloc(1024); // 1 kb

image.GetOutputData(mem, 1024);

// Don't forget to free(mem);

Another way:
char * mem = new char[1024];

image.GetOutputData((void *)mem, 1024);

// Don't forget to delete[] mem;

Another way:
char mem[1024];

image.GetOutputData((void *)&mem, 1024);

A: A pointer to void can point to anything, it's a generic nondescript anonymous pointer to some memory. This means that you can pass any kind of pointer as the first argument of the function, as all pointers can implicitly be converted to void*.

A: You can allocate any type of buffer. It will be converted using void*. However you will need to pass proper size of element. You will need to refer to documentation of api for size of each buffer element. In the example below it is 1 byte. And total buffer size is 10.
int size_of_buffer = 10;
unsigned char *buffer = malloc(sizeof(unsigned char)*size_of_buffer);

A: It looks like DicomImage::getOutputData does not care how you allocated your bytes.  Simply take take the pointer to some blob of your choice (object, struct, array, whatever) and cast it to void*.    You can get the memory with new, malloc or it can be a local variable.
Thing to be sure of:

*

*Make sure you allocate enough space.

*Make sure you accurately send the size parameter.

*Make sure that you understand what format of data DicomImage::getOutputData works with.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to format any random dictionary according to this specified json format. The dictionary is generating dynamically This is my dictionary:
my_dict = {"0": "age", "1": "Medu", "2": "Fedu", "3": "traveltime"}

I want dictionary in this json format:
var json = {
  columns: [{
      "0": "age"
    },
    {
      "1": "Medu"
    },
    {
      "2": "Fedu"
    },
    {
      "3": "traveltime"
    }
  ]
};

Also, I need it dynamic as the dictionary is also dynamic ...

A: Use the dict() constructor with a list comprehension:
>>> {"columns": [dict([item]) for item in my_dict.items()]}

or
>>> {"columns": [{k: v} for k, v in my_dict.items()]}

both will return
{'columns': [{'0': 'age'}, {'1': 'Medu'}, {'2': 'Fedu'}, {'3': 'traveltime'}]}


text:
Q: For a Generic outerclass, why do i need to declare the nested class static? I am trying to write the Data Structure for a Hash Table using Chaining. When i remove the keyword "static" from the nested class, i get the error that "Cannot create a generic array of SeparateChaining.Node"? on the line where i allocate memory to hmap using new.
With the static keyword it works fine.Can anybody please point out the significance of the keyword static here and the difference it makes? I am creating an array of object, then how come it shows generic array in the error (Eclipse)?
public class SeparateChaining<Key,Value> {

    private int m;

    private Node[] hmap;

    private int n;

    public SeparateChaining()
    {
        m=5;
        n=0;

        //error here on removal of static keyword from the node  class declaration
                hmap=new Node[m];

    }

    private ____ class Node //works fine with static. Otherwise shows error
    {
        private Object key;
        private Object value;
        private Node next;

        public Node(Object k, Object v)
        {

            key=k;
            value=v;
        }

    }

Thanks

A: If you declare the inner Node class as static, then the class is associated with the outer class SeparateChaining. Node is then in fact SeparateChaining.Node.
Without the static, it will be associated with an instance of SeparateChaining, which will need a couple type parameters, thus the inner Node class will also need those type parameters. Node is then in fact SeparateChaining<Key, Value>.Node; and in Java, creating an array of generics is not legal.

A: Well, it is generic. If the inner class is not static then the type is SeparateChaining<Key,Value>.Node. When you add static then it's treated like a regular class

A: Keyowrd static in the declaration of the nested class means "I don't want to have a reference to an object of the outer class, thank you very much". If you don't put static, then any object of the inner class has a reference to some object of the outer class.
And thus an object of inner, non-static class can be created only inside a non-static method of an object of the outer class.


text:
Q: how to validate ilog variables individually? I am going to validate multiple objects but individually (one at a time) using ilog jrules.
My current thought is wrap all items needs to be validated in a input param called "itemToValidate" as follows
<xs:element name="itemToValidate">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="employer" type="tns:employer" minOccurs="0" />
            <xs:element name="department" type="tns:department" minOccurs="0" />
        </xs:sequence>
    </xs:complexType>
</xs:element>

then in a rule called "init" in package called "init" get each item and set to a variable  for example "the employer"
then for each item (element) in "itemToValidate" would have a package such as "employer" for all rules related to "the employer"
issue i am facing with this is I need to check the null ness for all rules before the actual validation.
is there a way to avoid that? or is there any wrong with my implementation?
Thanks

A: I am not sure to understand your issue. "Check the null ness for all rules before the actual validation".
Why are you not setting the objects in the working memory and let JRules deal with the memory and use local rule variable rather than global variables?
Set "my employer" to an Employer
if the name of "my employer" is bobthen print "hello"
I would create a function that pushes the "ItemsToValidate" in the working memory first and then write rules as I did.
By doing this, if there is no Employer to validate then rules never fire because there is no item of type Employer in the memory.

A: The Tester section of the BOM-to-XOM mapping of the class you are interested in can be implemented to check for the existence of the fields you care about.
For example, the tester can be written as :

return this.employer != null

This would mean that the itemToValidate where the employer is null would not be evaluated in the rules you write. This would eliminate the null check (for the employer).
Check the knowledge center under the "class mapping tester using IRL" topic

A: Simply in our project we did a single verbalization for this approach, using:
the value {VALUE} is defined (return a boolean)
Hope this helps.


text:
Q: `call is closed` when calling onNext() in gRPC We have a server-side stream structure, the thing is the server side is a multi-thread environment where the streamObserver will be passed between methods and even threads, I have put the code where the .onNext() is called in a synchronized block but still it does not do the work.
When in unit tests, it passes the test only half of the time and when the test fails sometimes I got call is closed error, sometimes I got Stream is already completed, no further calls are allowed. My understanding is that those errors indicate the client side has closed the connection when the server is still trying to send response but I'm just confused when and how did the client closed the connection?
server-side code:
synchronized (responseObserver) {
    try {
        responseObserver.onNext(response);
    } catch (Exception e) {
        System.out.println("=== exception: ");
        e.printStackTrace();
    }
    eventsAsync.addAll(currentEvents);
}

exception:
java.lang.IllegalStateException: call is closed
    at com.google.common.base.Preconditions.checkState(Preconditions.java:508)
    at io.grpc.internal.ServerCallImpl.sendMessageInternal(Unknown Source)
    at io.grpc.internal.ServerCallImpl.sendMessage(Unknown Source)
    at io.grpc.stub.ServerCalls$ServerCallStreamObserverImpl.onNext(Unknown Source)


text:
Q: Include an icon for a Prism module I want my Prism shell to display an image and label for each module that it discovers. How might I go about including an image from a module assembly and accessing it in the shell?
I've already tried creating an interface for providing an icon (as an ImageSource) and a string label, but I am having trouble creating the ImageSource from the image in the module's assembly. (The URI used in the constructor for a BitmapImage always wants to find content in the shell's assembly rather than the module's assembly.)
I was thinking that I could add an image as a resource and just use that, but it is represented in code as a System.Drawing.Bitmap and I couldn't find an obvious way to convert that to a type usable in the WPF shell. (I did see some code for converting from a Bitmap, but that feels like the wrong approach. Might have to settle with that, though.) [Edit: That approach does actually work, but I still think it smells.]

A: Pat, your problem is most likely because you do not use the correct path to the image. You are trying to load that image in the view constructor or something then it does not find the import fails.
You wanna double check whether your image is compiled as Resource.
Use this (assuming your image is called Icon.png and is locatd in the root of your module project)
public BitmapImage Icon
{
    get
    {
        var assembly = Assembly.GetCallingAssembly();

        Uri uri = new Uri("/" + GetType().Assembly.ToString().Split(',')[0] + ";component/Icon.png", UriKind.Relative);

        if (_icon == null)
            _icon = new BitmapImage(uri);

        return _icon;
    }
}

A: When you return the BitmapSource from the module, make sure to use a Pack Uri.  If you are trying to load an image from an assembly ModuleFoo.dll, you would do something like so:
public ImageSource ModuleImage
{
    get
    {
        return BitmapFrame.Create(new Uri("pack://application:,,,/ModuleFoo;component/ModuleIcon.png", UriKind.Absolute);
    }
}

Remember that for WPF resources, the images must be compiled as a "Resource", and not "Embedded Resource" that WinForms requires.


text:
Q: metabuilder checked listbox selected index changed not working on server am using meta builder checked listbox and their selected index changed working fine in local.but not working on server side. please help me to fix this error. My partial code is here..
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{

    try
    {
        if (ListBox1.Items.Count > 0)
        {
            for (int i = 0; i <= ListBox1.Items.Count; i++)
            {
                if (ListBox1.Items[i].Selected == true)
                {
                    lblempid.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(0, 8));
                    lblempname.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(9));
                    DataSet5TableAdapters.sp_GetallpayperiodTableAdapter TA = new DataSet5TableAdapters.sp_GetallpayperiodTableAdapter();
                    DataSet5.sp_GetallpayperiodDataTable DS = TA.GetData();
                    if (DS.Rows.Count > 0)
                    {
                        fromdate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstartdate"]);
                        todate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldtodate"]);
                        status = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstatus"]);
                        if (status == "OPEN")
                        {
                            lblfromdate.Text = Convert.ToString(Convert.ToDateTime(fromdate).ToShortDateString());
                            lbltodate.Text = Convert.ToString(Convert.ToDateTime(todate).ToShortDateString());
                        }
                    }

                }
            }
        }

    }
    catch (Exception e1)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "onload", "<script language='javascript'>alert('" + e1.Message + "');</script>", false);
    }

Design code:
       <%@ Register Assembly="MetaBuilders.WebControls" Namespace="MetaBuilders.WebControls"
TagPrefix="mb" %>

        <mb:CheckedListBox ID="ListBox1" runat="server" CssClass="textbox" Width="250px"
                                                                            Height="515px" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
                                                                        </mb:CheckedListBox>

A: please check if the auto post back is true in your aspx code:
Example:
<asp:DropDownList ID="ddlForecastOption" runat="server"
      onselectedindexchanged="ddlForecastOption_SelectedIndexChanged"
      AutoPostBack="true">


text:
Q: System commands vs Perl subroutines I have the following snippet of code that I run as part of several jobs everyday:
  system("cp $keyFile  $destinationFile");
  system("chown $userID $destinationFile");
  system("chmod 400 $destinationFile");

The problem with the above code is that sometimes, very rarely, at least one of the above operations do not complete successfully and my job fails. While it is alright for the job to fail if one of the above operations fail I still want to avoid the failing one of the simple system commands.
So I have the following options:

*

*Use Perl subroutines File::Copy::copy, chmod, chown instead of the system commands.

*Check the return values of the system() commands. This I have done but does not explain why it might fail.

Is is better/safer to use Perl subroutines instead of system commands. My jobs will always run on an RHEL5 machine [never Windows].
Is there anything else that I can do here. How can I collect more information on what went wrong?
Update: File names or file paths will never contain spaces or weird characters. They will be from the set [a-zA-Z].

A: Yes, it's always better to use Perl native versions (File::Copy and chmod()).
Among many reasons:

*

*Performance. Calling system() forks off between 1 and 2 new processes (one for command and likely another one for shell) which is a heavy operation

*Error checking. IO related system calls in Perl set a "$!" error text variable when errors happen:
File::Copy::copy($source, $destination)
    || die "Failed to copy from $source to $destination. Error: $!\n";


text:
Q: RcppArmadillo pass user-defined function Consider the following R code,
## ----------- R version -----------

caller <- function(x=1:3, fun = "identity", ...){

  ## do some other stuff
  ## ...
  ## then call the function
  eval(call(fun, x))

}

fun1 <- function(x, ...){
  x + x
}

fun2 <- function(x, a = 10) a * x

caller(fun = "fun1")
caller(fun = "fun2")

The user can pass a function name "fun", that is used by caller. I wish to perform the same task with RcppArmadillo objects (as part of a more complex task, obviously). The function would be defined in C++, and the user selects it at the R level by referring to its name:
caller_cpp(1:3, "fun1_cpp")

or
caller_cpp(1:3, "fun2_cpp")

etc.
Here's my naive attempt for the caller function, that even fails to compile:
## ----------- C++ version -----------

library(Rcpp)
require( RcppArmadillo )

sourceCpp( code = '

       // [[Rcpp::depends("RcppArmadillo")]]

       #include <RcppArmadillo.h>

       using namespace arma ;
       using namespace Rcpp ;

       colvec fun1_cpp(const colvec x)
      {
       colvec y ;
       y = x + x;
       return (y);
      }

       colvec fun2_cpp(const colvec x)
      {
       colvec y ;
       y = 10*x;
       return (y);
      }

     // mysterious pointer business in an attempt
     // to select a compiled function by its name

      typedef double (*funcPtr)(SEXP);
      SEXP putFunPtrInXPtr(SEXP funname) {
            std::string fstr = Rcpp::as<std::string>(funname);
            if (fstr == "fun1")
                return(Rcpp::XPtr<funcPtr>(new funcPtr(&fun1_cpp)));
            else if (fstr == "fun2")
            return(Rcpp::XPtr<funcPtr>(new funcPtr(&fun2_cpp)));

       }

       // [[Rcpp::export]]
       colvec caller_cpp(const colvec x, character funname)
      {
       Rcpp::XPtr fun = putFunPtrInXPtr(funname);
       colvec y ;
       y = fun(x);
       return (y);
      }

   ')

Edit: adapted the example after following Dirk's suggestion to look at RcppDE.

A: (Sometime you need to use svn log ... on files to see how dated they are...)
I think a better use case is in my "port" of the C-based DEoptim to Rcpp / RcppArmadillo: RcppDE.  In it, I allow the optimization routine to use either an R function (as DEoptim does) or a user-supplied compiled function -- which is what you want here as I understand it.
There is a tiny bit of C++ scaffolding, but you should have no problem following that.
Edit on 2013-01-21 Below is a complete solution which I have also justed posted as this new post at the Rcpp Gallery -- including some comments and sample usage.
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>

using namespace arma;
using namespace Rcpp;

vec fun1_cpp(const vec& x) {    // a first function
    vec y = x + x;
    return (y);
}

vec fun2_cpp(const vec& x) {    // and a second function
    vec y = 10*x;
    return (y);
}

typedef vec (*funcPtr)(const vec& x);

// [[Rcpp::export]]
XPtr<funcPtr> putFunPtrInXPtr(std::string fstr) {
    if (fstr == "fun1")
        return(XPtr<funcPtr>(new funcPtr(&fun1_cpp)));
    else if (fstr == "fun2")
        return(XPtr<funcPtr>(new funcPtr(&fun2_cpp)));
    else
        return XPtr<funcPtr>(R_NilValue); // runtime error as NULL no XPtr
}

// [[Rcpp::export]]
vec callViaString(const vec x, std::string funname) {
    XPtr<funcPtr> xpfun = putFunPtrInXPtr(funname);
    funcPtr fun = *xpfun;
    vec y = fun(x);
    return (y);
}

// [[Rcpp::export]]
vec callViaXPtr(const vec x, SEXP xpsexp) {
    XPtr<funcPtr> xpfun(xpsexp);
    funcPtr fun = *xpfun;
    vec y = fun(x);
    return (y);
}


text:
Q: unsafe use of relative rpath libboost.dylib when making boost.python helloword demo? Recently, I am learning boost C++ library. I want to use python to call exist C++ project. I have install boost under OSX 10.11 using brew install boost. My python version 2.7.
I make a hello.c:
char const* greet()
{
    return "hello, world";
}

#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello)
{
    using namespace boost::python;
    def("greet", greet);
}

and Makefile:
PYTHON_VERSION = 2.7
PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)

# location of the Boost Python include files and library
#
BOOST_INC = /usr/local/include
BOOST_LIB = /usr/local/lib
#
# compile mesh classes
TARGET = hello

$(TARGET).so: $(TARGET).o
    g++ -shared -Wl $(TARGET).o -L$(BOOST_LIB) -lboost_python -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so

$(TARGET).o: $(TARGET).c
    g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).c

However, after I run make and got hello.so. I met following error when I run python code:
import hello
print hello.greet()

error:
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    import hello
ImportError: dlopen(/Users/einverne/boost_test/hello.so, 2): Library not loaded: libboost_python.dylib
  Referenced from: /Users/einverne/boost_test/hello.so
  Reason: unsafe use of relative rpath libboost_python.dylib in /Users/einverne/boost_test/hello.so with restricted binary

A: It is advisable to change the Boost dynamic libraries themselves on MacOS instead of changing the executables or other dynamic libraries linked against them. Run the bash script given below in the directory that contains your libboost_XXX.dylib libraries:
#!/bin/bash

# Modify the absolute dylib paths baked into the libraries
for i in *.dylib
do
    FULLPATH=`pwd`/$i
    install_name_tool -id $FULLPATH $i
    echo -change $i $FULLPATH
    done > changes
for i in *.dylib
do
    install_name_tool `cat changes` $i
done
rm changes

You will need to do this only once after you built the Boost libraries. No mucking around with the executables linking against them is needed.

A: Take this link as a reference.
To my problem, use otool -L hello.so:
hello.so:
    hello.so (compatibility version 0.0.0, current version 0.0.0)
    libboost_python.dylib (compatibility version 0.0.0, current version 0.0.0)
    /System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.10)
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.1.1)

you can see that libboost_python.dylib is not point to the really exist path.
so use this command:
install_name_tool -change libboost_python.dylib /usr/local/lib/libboost_python.dylib hello.so

and run otool -L hello.so again:
hello.so:
    hello.so (compatibility version 0.0.0, current version 0.0.0)
    /usr/local/lib/libboost_python.dylib (compatibility version 0.0.0, current version 0.0.0)
    /System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.10)
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.1.1)

and finally run python test.py, I get the result.


text:
Q: Start a login_activity if the user has not logged in I set a check method that opens login_activity if the user has not logged in - isLogged. App gets stuck on MessageRow activity even if user has not logged in.
//launcher activity

class MessageRow : AppCompatActivity(){

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(R.layout.message_row)
        supportActionBar?.title = "messages"
        supportActionBar?.setLogo(R.drawable.logo)

        isLogged()

    }

     private fun isLogged(){
     val uid = FirebaseAuth.getInstance().uid
     Log.e("tag","$uid")
     if(uid == null){
         val intent = Intent(this,Login::class.java)
         intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
         startActivity(intent)
        }
    }
}

Logcat error
E/MultiWindowProxy: getServiceInstance failed!

A: Change this:
val uid = FirebaseAuth.getInstance().uid

into this:
val user = FirebaseAuth.getInstance().currentUser
val uid  = user.uid


text:
Q: Can I use leaflet to access a WMS service published as an OpenLayers javascript API? I would like to add this layer to a site I'm working on that uses leaflet:
http://116.240.195.134/vicmapapi/UserGuide.jsp

The API itself is a javascript file based on OpenLayers: http://api.maps.vic.gov.au/vicmapapi/js/vicmapapi.js (I don't know OpenLayers at all, so I'm not really sure what I'm looking at).
Am I able to access the tiles using leaflet? This didn't work:
var map = L.map('map').setView([-37.3, 145.3], 5);
        var wms = L.tileLayer.wms("http://api.maps.vic.gov.au/vicmapapi/map/wms", {
        LAYERS: 'CARTOGRAPHICAL',
        FORMAT: 'image/png',
        FIRSTTITLE: false,
        transparent: true,
        WIDTH:512,
        HEIGHT:512,
        EXCEPTIONS:"application/vnd.ogc.se_inimage",
        SRS:"EPSG:3111"
        });
        wms.addTo(map);

In particular, it didn't work because the tiles it tried to fetch had URLs like this:
http://api.maps.vic.gov.au/vicmapapi/map/wms?service=WMS&request=GetMap&version=1.1.1&layers=&styles=&format=image/jpeg&transparent=true&height=256&width=256&LAYERS=CARTOGRAPHICAL&FORMAT=image/png&FIRSTTITLE=false&WIDTH=512&HEIGHT=512&EXCEPTIONS=application/vnd.ogc.se_inimage&SRS=EPSG:3111&srs=EPSG:3857&bbox=18785164.071364917,-3757032.814272983,20037508.342789244,-2504688.542848655

instead of:
http://api.maps.vic.gov.au/vicmapapi/map/wms?LAYERS=CARTOGRAPHICAL&FORMAT=image%2Fpng&FIRSTTILE=false&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A3111&BBOX=2327867.7504022,2539132.2495979,2869735.5008043,3081000&WIDTH=512&HEIGHT=512&cache_bbox=2296369.732799%2C2279293.001349%2C2931371.002802%2C2702627.181351

The server then returns error messages like "400: (x + width) is outside of Raster". If I increase WIDTH to 10000, then Apache returns 500 Internal Server error with a complaint about Java heap space. Oops.
So - am I barking up the wrong tree here, or is there a way to do this?

A: I am using the same API, just use their Web mercator version. I am making the request as such:
var wms = L.tileLayer.wms("http://api.maps.vic.gov.au/geowebcacheWM/service/wms?VERSION=1.1.1&TILED=true", {
    layers: [layer],
    format: 'image/'+ imgType,
    transparent: choice,
});

This map is then in 3857, which is the same as Google. Any data then that is in EPSG 4326 can be reprojected on the fly and does not need reprojection, such as GeoJSON.  GeoJson by default uses 4326 so using 3111 is inconvenient.
Additional notes:
Note, they may have since changed the web mercator URL, I will update when I have the final one. Also, if you are using their satellite imagery, add the following:
    height:'512',
    width:'512'
Furthermore, if you are calling the Hybrid or Cartograhic layers you should set the transparent to true because it is a png. The satellite imagery is in JPEG format and thus can be set to false.

A: user1147183 put me on the right track, but I wanted to give a more complete answer.
So, first, yes, Leaflet can access a WMS service, using the TileLayer.WMS subclass.
If the tiles are not available in ESPG 3857 (Web Mercator) then you can either switch your whole leaflet interface to use whatever the WMS service is using (http://blog.kartena.se/local-projections-in-a-world-of-spherical-mercator/), or give up.
In this instance, after I posted the original question, VicMap began providing a separate WMS service in Web Mercator. They don't seem to have documented it anywhere, so thanks user1147183 for providing the URL: /geowebcacheWM/service/wms.
Calling the WMS function getCapabilities (http://api.maps.vic.gov.au/geowebcacheWM/service/wms?request=getcapabilities) shows that there is a layer called WEB_MERCATOR. (Strangely, the layer names bear no relation to those in the EPSG:3111 service, such as CARTOGRAPHICAL).
So, finally you can make this call in leaflet:
var wms = L.tileLayer.wms("http://api.maps.vic.gov.au/geowebcacheWM/service/wms?VERSION=1.1.1&TILED=true", {
                layers: ['WEB_MERCATOR'],
                format: 'image/png',
                transparent: false,
                continuousWorld: true,
            });

            wms.addTo(map);

The rendering is a little funny, but it's usable.


text:
Q: How to change specific classname in react after click

checkCard(cardName, index) {
        const item = {
            name: cardName,
            indexNumber: index
        };

        // check the part where you should look at
        const newFlipStatus = this.state.flipped[index];

        this.setState({
            tempArray: [...this.state.tempArray, item],
            flipped: !newFlipStatus
        }, () => {
            this.cardCounter(this.state.tempArray)
        });
    }

render() {
        return (

                <button onClick={() => this.shuffleCard()}>Click</button>
                {this.state.cardArray.map((items, index) => (

 this.checkCard(items, index)}>{items}

                ))}

        )
    }

When the user clicks on a specific card in this case a specific element, but the problem I have now is that it is looping through all the element and change them all.
https://codeshare.io/5O0M7j

A: this.state = {
        memoryCards: ['mario', 'luigi', 'browser', 'peach', 'wario', 'toad', 'yoshi', 'bowser-junior', 'waluigi', 'diddy-kong-jr' ],
        cardArray: [],
        newArray: [],
        tempArray: [],
        arrayHere: [],
        count: 0,
        score: 0,
        flipped: false
    }

You only have a single flipped property which is representing the whole deck of cards. This is the same property you are checking in:
<li className={this.state.flipped ? 'card' : 'card true'}

So when you click on it, you update the state, but this state property is used on all the cards, so all the li elements will get the card classname.
Your check:
const newFlipStatus = this.state.flipped[index];

Will also return false, as you defined flipped as a boolean at the start. Then you assign it, which will be true.
flipped: !newFlipStatus

If you update your flipped state to an Object:
this.state = {
  flipped: {}
  ...
}

You can update your Render function to check the property, on the Flipped Object, which related to the Index of the card:

 ({
  tempArray: [...state.tempArray, item],
  flipped: {
    ...state.flipped,
    [index]: !state.flipped[index]
  }
}), () => {
  this.cardCounter(this.state.tempArray)
});


text:
Q: How can I turn Google fonts into a png or gif? I've been using a Google font as my web app's logo. But it seems that it doesn't render as great as I expected. But I still love the font face I've been using. So I want to just turn that into a png or gif and use the image as the logo.
What is the easiest way to do something like this?

A: While Aatch is right about the idea of Web fonts is not having to create images, you can always download the font to your computer and create the logo in Photoshop.

A: I found this fantastic site to help you convert the Google Fonts Text into an Image. The site is Picas. Picas is Open Source. You can find out the Source Code in their repo.
See https://picas.vercel.app/.
See Source Code https://github.com/djyde/Picas.
Preview:

A: Take a screenshot of the text rendered in the browser that renders it best. Ctrl-PrintSrc in KDE and Windows.

A: take a screenshot
on Mac: CMD+Shift+4
on Windows: open the print screen program
on Linux: PrintSrc

A: Take a screenshot, crop it in Photoshop.

A: I ran into the same need to have static images of google fonts.
It was a huge timesink so I ended up automating it with puppeteer/lambda. I have up to date renders of every google font available for download @ gfontpng.com


text:
Q: Python assert -- Best way to report non-existing files in a list with one line Background
I use assert statement to check if certain files in a list exist in my computer, then I would like to do further work if these files are all there.
I've referenced to this thread, so I do something like this:
from pathlib import Path

# The list containing several filepaths
files = ['folder/file1', 'folder/file2', 'folder/file3']

# check if all of these files are exist
assert all(Path(n).exists() for n in files)

# Do something else ...
# ...

This piece of code is runnable. If one file does not exist, the program will raise AssertionError.
Question
Now I would like to all the file(s) that not exist, instead of a simple AssertionError.
Is there any one-liner solution for this?
What I have tried
I've tried the following:
assert all(Path(n).exists() for n in files), f"file {n} not exist!"

Runing this code will report NameError: name 'n' is not defined.

A: You'll need to use a loop:
for file in files:
    assert Path(file).exists(), f"{file} does not exist!"

In Python 3.8+, you can do it in one line by using the walrus operator:
assert not (missing_files := [n for n in files if not Path(n).exists()]), f"files missing: {missing_files}"

A: n from comprehension isn't in scope where you do f'{n}'
You can show all not exists files
not_exists = [f for f in files if not Path(f).exists()]
assert not not_exists, f'Files {not_exists} not exist'

Or, only the first one
for f in files:
  assert Path(f).exists(), f'{f} not exists'

A: As already pointed out in comments, assert is strictly a development tool. You should use an exception which cannot be turned off for any proper run-time checks; maybe create your own exception for this. (Assertions will be turned off in production code under some circumstances.)
Secondly, the requirement to do this in a single line of code is dubious. Code legibility should trump the number of lines everywhere, except possibly in time-critical code, where execution time trumps both.
class MissingFilesException(Exception):
   pass

missing = {x for x in files if not Path(x).exists()}
if missing:
    raise MissingFilesException(
        'Missing files: {}'.format(", ".join(missing))


text:
Q: Why do I get a negative value for this integral? I am trying to compute the integral: $$\int_{4}^{5} \frac{dx}{\sqrt{x^{2}-16}}$$
The question is related to hyperbolic functions, so I let $x = 4\cosh(u)$ therefore the integral becomes: $$-\int_{0}^{\ln(2)}\frac{4\sinh(u)}{\sqrt{16-16\cosh^{2}(u)}}du = -\int_{0}^{\ln(2)}1du = -\ln(2)$$
The answer is $\ln(2)$ so if someone could point out where I went wrong that would be great, thanks

A: Setting $x = 4 \cosh(u)$, gives us $dx = 4 \sinh(u)du$. Hence the integral becomes
$$\int_0^{\ln(2)} \dfrac{4 \sinh(u) du}{\sqrt{16\cosh^2(u) - 16}} = \int_0^{\ln(2)} \dfrac{4 \sinh(u) du}{4 \sinh(u)} = \ln(2)$$

A: use this formula
$$\int \frac{dx}{\sqrt{x^{2}-a^2}}=\log|x+\sqrt{x^2-a^2}|+c$$
$$\int_{4}^{5} \frac{dx}{\sqrt{x^{2}-16}}$$
$$\int_{4}^{5} \frac{dx}{\sqrt{x^{2}-4^2}}$$
$$(\log|x+\sqrt{x^2-16}|)_4 ^5$$
$$\log|8|-\log|4|$$
$$\log2$$


text:
Q: PHP Condicionales ternarios Me preguntaba si existía alguna forma de realizar un codicional ternario que solo evalue una condición verdadera y no una falsa.
Por ejemplo, el condicional ternario en php sería:
$n = (2) ? true : false;

Mi idea sería realizar un condicional ternario tal que:
$n = (2) ? true;

he probado de diferentes maneras pero todas me dan error, así que supongo que no existe manera, pero por si acaso lo pregunto por aquí.
Gracias! :)
Os pongo el código entero sin el ejemplo anterior:
function encrypt($chr) {

  if($chr === 'Ñ') { return 0; }

  $abc = array(    'A' => 2,    'B' => 22,
                   'C' => 222,  'D' => 3,
                   'E' => 33,   'F' => 333,
                   'G' => 4,    'H' => 44,
                   'I' => 444,  'J' => 5,
                   'K' => 55,   'L' => 555,
                   'M' => 6,    'N' => 66,
                   'O' => 666,  'P' => 7,
                   'Q' => 77,   'R' => 777,
                   'S' => 7777, 'T' => 8,
                   'U' => 88,   'V' => 888,
                   'W' => 9,    'X' => 99,
                   'Y' => 999,  'Z' => 9999 );

      return $abc[$chr];
}

Mi idea simplemente era usar un ternario en lugar de un if, (por estética) sé que es una tonteria. De ahí que me preguntase si se pudiese hacer algo como:
return $chr == 'Ñ' ? true : false;

La cosa es que solo quiero retornar el true, no el false, si es false mi idea es que siga con el código.

A: Por la propia naturaleza de del operador ternario no puedes hacer un operador ternario que solo devuelva true en caso de que la expresión a evaluar sea verdadera y nada en caso de que sea falsa.

A partir de PHP 5.3, es posible dejar de lado la parte media del
  operador ternario. La expresión expr1 ?: expr3 retorna expr1 si expr1
  se evalúa como TRUE y expr3 si es de otra manera.

Por consiguiente lo único que se podría hacer:
$n = 2;
/* Si la expresion a evaluar es verdadera devuelve true
pero si no , devolverá false (o lo que le indiques)*/
$resultado = ($n === 2) ?: false;
$resultado; // true

$resultado = ($n === 5) ?: false;
$resultado; // false

Que es lo mismo que :
$n = 2;
$resultado = ($n === 2) ? true : false;
$resultado; // true

$resultado = ($n === 5) ? true : false;
$resultado; // false

Aqui en la documentación oficial de PHP hay un apartado que hablan sobre el operador ternario: Operadores de comparación de PHP

A: La misma palabra lo dice, ternario. La operación debe estar compuesta por 3 partes, la evaluación, y los dos tipos de retorno. Por sintaxis $n = 2 ? true; está mal hecho y te retornará errores, es por eso que su estructura no debe ser violada siguiendo el patrón:

Evaluación ? Si evaluación es verdadera : Si evaluación es falsa;

//Comparación booleana
$check = false;
$isChecked = $check ? true : false;

//Comparación numérica
$num = 5;
$isGrater = $num > 5 : true : false;

//Dos o más validaciones
$num = 5;
$isChecked = true;
$checkedAndGreater = $num > 5 && $isChecked ? true : false;

//Anidación ternaria
$getId = false;
$age = 18;
$barAccess = $getId ? 'Bienvenido' : $age === 18 ? 'Bienvenido, cerveza?' : 'No puedes pasar';

//Recuerda que en boolean cualquier número diferente de 0 es TRUE, por lo que si evalúas el 2, será siempre TRUE, la forma correcta sería
$n = 2;
$n = $n === 2 ? 'Es dos' : 'No es dos;

Todos los casos deben tener 3 partes, si no dejaría de ser evaluación ternaria, no puedes romper esa sintaxis.
Saludos


text:
Q: Adding multiple address prefixes to network subnet using Azure SDK I have existing network with subnet, which has its IPV4 address prefix specified.
Using Azure SDK in C# i need to add additional IPV6 address prefix without removing the existing one.
I managed to do this in portal and using Microsoft REST API, but my goal is to implement it using their SDK. Here is the piece of code I wrote so far:
await networkToUpdate.Update()
                        .UpdateSubnet(network.SubnetAzureId)
                        .WithAddressPrefix("10.0.0.0/21")
                        .WithAddressPrefix("ace:cab:dca:deed::/64")
                        .Parent()
                        .ApplyAsync();

Unfortunately, it allows to set only one address prefix, which is the IPV6 in this scenario.
Is there any way to add both address prefixes via SDK?

A: Please use the code below:
        var clientId = "xxx";
        var clientSecret = "xxx";
        var tenantId = "xxx";

        var creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);

        var azure = Azure.Configure()
            .Authenticate(creds)
            .WithDefaultSubscription();

        var myvnet = azure.Networks.GetById("/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Network/virtualNetworks/xxx");

        //use the code below to update multi address prefixes
        IList<string> list = new List<string>() { "172.18.3.0/24", "ace:cab:dca:deed::/64" };
        myvnet.Subnets["the_subnet_name"].Inner.AddressPrefix = "";
        myvnet.Subnets["the_subnet_name"].Inner.AddressPrefixes = list;

        myvnet.Update().Apply();

The test result:

Please let me know if you still have issues about that.


text:
Q: cuda to llvm bitcode conversion I want to convert CUDA code to llvm bitcode so I can instrument it. I have tried gpuocelot, which compile ptx into CPU executable code. Nevertheless, I couldn't get llvm bitcode from it so I can't instrument it. There have been activities trying to get CUDA supported in llvm. Can anyone provide a robust solution to convert CUDA to workable llvm bitcode? Thanks.

A: NVIDIA's nvcc is actually using LLVM IR as one of its steps. They might have changed it a little bit - I haven't seen the details. They have explained it under:
https://developer.nvidia.com/cuda-llvm-compiler

A: You should be able to use Clang to compile CUDA (mixed-mode) to LLVM IR now. Check this page out. Note that this support is still experimental. Feel free to report bugs to the LLVM community.


text:
Q: Importing HTML/CSS project into a visual front-end editor is that possible to import my project (HTML/CSS/JS) into any bootstrap editor and edit it from there?
I'm looking for a way that I can modify my existing web project using a visual editor (WYSIWYG).

A: I know this isn't exactly what you're asking, but have you tried Firefox and exporting all the css afterwards?

A: Absolutely. Several Bootstrap WYSIWYG editors will allow you to copy over your existing HTML/CSS/JS. With Divshot you can import your entire project at once and have all of your files appear in a file tree as you might expect with any desktop based text editor or IDE. Just click the + icon in the navigator panel and select Upload Files. From there you can move, duplicate, delete or rename your files and manage them however you'd like!


text:
Q: How to remove xmlns="" with xslt mapping I want to transform following xml
<IRheader>
    <Keys>
        <Key Type="TaxOfficeNumber">33</Key>
        <Key Type="TaxOfficeReference">33345</Key>
    </Keys>
    <PeriodEnd>2017-02-28</PeriodEnd>
    <Sender>Company</Sender>
</IRheader>

into
<IRheader>
    <Keys>
        <Key Type="TaxOfficeNumber">33</Key>
        <Key Type="TaxOfficeReference">33345</Key>
    </Keys>
    <PeriodEnd>2017-02-28</PeriodEnd>
    <IRmark Type="generic"></IRmark>
    <Sender>Company</Sender>
</IRheader>

I am using following xsl code to transform
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" />

    <xsl:template match="@*|node()" name="t1">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*[local-name()='PeriodEnd']">
        <xsl:call-template name="t1" />
        <xsl:element name="IRmark">
            <xsl:attribute name="Type"><xsl:text>generic</xsl:text></xsl:attribute>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

After that i am getting
<IRheader>
    <Keys>
        <Key Type="TaxOfficeNumber">33</Key>
        <Key Type="TaxOfficeReference">33345</Key>
    </Keys>
    <PeriodEnd>2017-02-28</PeriodEnd>
    <IRmark xmlns="" Type="generic"></IRmark>
    <Sender>Company</Sender>
</IRheader>

Kindly suggest how to remove unwanted xmlns=""

A: If you put the elements in the right namespace then the namespace declarations will generally take care of themselves. This problem usually occurs because the parent element is in a namespace but IRMark is not. If you generate IRMark in the desired namespace then the namespace declaration will usually disappear.
In your example the containing elements don't appear to be in a namespace. As your post shows no evidence that you understand namespaces, I'm wondering if you removed them from the code you have shown us because you didn't realise they mattered? If that's not the case, then I can't see why the xmlns="" undeclaration is present, and I would want to know which XSLT processor you are using.


text:
Q: Black status bar in ios 7 - secondary issue I know this question has been asked several times and the solutions I have seen have been very helpful. But since i have 2 conflicting requirements, I am a little stranded and hoping to find some help.
So here are the requirements:

*

*We have multiple View controllers out of which only one needs to be full screen (without status bar on the top).

*The other view controllers need to show a black status bar with a dark gray navigation bar

The First View controller is embedded in a navigation controller.
As recommended in some of the other posts, I did the following

*

*Set UIViewControllerBasedStatusBarAppearance to NO

*Added this code in app delegate
CGRect frame = [[UIScreen mainScreen] bounds];
self.window.frame =  CGRectMake(0,20,frame.size.width, frame.size.height-20);
self.window.bounds = self.window.frame;
It works fine if I only stay in those View controllers that have the status bar.
The moment I open the FULL screen view controller, that VC is cut off on the top as shown here.

Additionally when I come back to the Main view controller, now thats shifted up as well and the title bar is where the status bar was showing.

I have tried to push the views back down by resetting the view.frame and requesting layout but it doesnt take effect.
Any suggestions on how to resolve this?

A: Don't change self.window.bounds in app delegate. Instead, in your view controllers try something like this:
-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES/NO animated:YES];
    [self setNeedsStatusBarAppearanceUpdate]; // For showing/hiding status bar
    [super viewWillAppear:animated];
}

- (BOOL)prefersStatusBarHidden {
    return YES/NO;
}

You will have different frames for the view in ViewDidLoad according to whether status bar and navigation bar are there.


text:
Q: Telerik RadWindow does not fire ClientCallBackFunction after a ajax an __DoPostBack HI,
I have a Telerik radwindow that allows our users to upload files.  When the user first opens the radwindow and sees the upload fields, they can happily select a file and upload it.  The window then returns the id of the uploaded file back to the parent page via the ClientCallBackFunction.  This function then passes in the ID to a javascript function that calls __DoPostback so that we can populate  the list of uploaded files.  First time around it works a treat.
However all subsequent times it fails to call ClientCallBackFunction unless i refresh the entire page.  I also note that any other control on the parent page to uses an ajax postback also stops the ClientCallBackFunction begin called, even on the first time.
any ideas?
Thanks
Richard

A: ClientCallBackFunction was deprecated and removed from RadWindow a long time ago, so I am not sure what is the exact version that you are using.
Have you set DestroyOnClose to true? If so, try setting it to false and see how your app will behave. If this doesn't help, open a support ticket from your Telerik account and send a sample project where the problem could be reproduced so I could check it more closely.
Regards


text:
Q: horizontal form css+bootstrap3 (border) tell me how to do that would border separating INPUT did not reach the edge ?
i used to bootstrap3 Here is a layout:

 @
 <input type="text" class="form-control" placeholder="username">
 <input type="text" class="form-control" placeholder="e-mail">
 <input type="text" class="form-control" placeholder="tel">

or can you tell me another solution ? thank you.

A: Bootstrap seems to add padding to the input-group class.
You could possibly override that using:
.input-group{
padding:0;
}

Or, you could scrap bootstrap (best thing you'll do to learn css), and create your own class:

.group {
  background: blue;
  padding-left: 20px;
  position: relative;
}
.group:before {
  position: absolute;
  content: "@";
  left: 0;
}

  <input type="text" class="form-control" placeholder="username">
  <input type="text" class="form-control" placeholder="e-mail">
  <input type="text" class="form-control" placeholder="tel">


text:
Q: How can I post Audio using facebook SDK with android How can I post Audio using facebook SDK with android ? instead of uploading them to a third party server and share the link. Or use a third party app.

A: I don't believe that there is currently a way to do this. You'll have to upload it to a 3rd party service such as SoundCloud and then post a link. If the 3rd party service supports embedding in Facebook (and SoundCloud does), then your users will be able to listen to the audio right on their news feed.
Another option might be to use "feed gaming" -

Developers can leverage in-feed gaming to create engaging stories for
  users. This involves publishing a story on behalf of a user which has
  a flash object attached. When a user's friends see these attachments,
  they will be able to click to play them inline. This opens up some
  interesting scenarios for a small embeddable version of your game to
  be shown to a user's friends, at the end of which you can encourage
  them to click through to your canvas app.

This method is meant for gaming but if you develop your own audio player, you'll be able to let your users upload the audio file to your servers and them stream them though the inline swf.


text:
Q: Preserve associated row data while using importRange in the destination sheet For our construction company, we have a sheet that has all of the bills listed, along with relevant data that our accounting person would add to the master sheet.
I then have another sheet that pulls this data for the relevant people in the accounts for them to complete those steps. It filters to only the relevant columns (specifically, based on Column H - either "Yes" or "No") using query and importRange.
query(IMPORTRANGE("https://docs.google.com/spreadsheets/d/1pY53-XaGnUQ3BPmLh90mLSqIwSo7S2_QOPbD6JBQHOA/edit#gid=0","Master!A3:G"), "Select Col1, Col2, Col4, Col5, Col6, Col7 where Col6 is not null")

I want to include a few details in the destination sheet, which I have done.
The problem is typically associated with column H in the master sheet (Work Done required or not). For most cases, it is either a yes or no. However, in some cases, the accounting person doesn't know for sure whether it is a yes or no. But he wants to keep on adding other bill details.
When he fills the empty column later, the entered data on this second sheet doesn't dynamically shift with the imported data, thus causing the rows to misalign.
Unfortunately, as I mentioned, the rows don't stick together so as the dynamic order of the imported columns changes, the static order of the manual columns causes a mismatch.
Is there a way to make this work?

A: A solution would be to add an onEdit trigger in order to check if any changes have been made to the H column and later add the corresponding rows to the destination sheet, something similar to this:
function onEdit(e) {
  let destinationSheet = SpreadsheetApp.openById("SS_ID").getSheetByName('Input Sheet');
  let sourceSheet = SpreadsheetApp.getActiveSheet();
  let lastRow = destinationSheet.getLastRow();
  if (e.range.getColumn() == 8 && e.range.getValue() != null) {
    let billNo = sourceSheet.getRange(e.range.getRow(),1).getValue();
    // retrieve all the other values needed from the current row of the edit
    // current row of the edit > e.range.getRow()
    destinationSheet.getRange(lastRow+1,1).setValue(billNo);
    // copying the values to the destination sheet by using setValue()

  }
}

The above code makes use of the e event object in order to check if the edit has been made in the H column and if the value is different from null. If this condition checks, the values needed to be copied are being retrieved (here I have illustrated how to retrieve the billNo) and later set them in the destination sheet by retrieving the last row of it.
Note
You can also add a for loop in order to manage the copying the data easier and also add more conditions such that it the new entry is being pasted after a certain Actual Date or simply sort the values after the entry is being pasted.
Reference

*

*Apps Script Triggers;

*Apps Script Event Objects;

*Apps Script Range Class.

A: I have performed testing with the following formula, I found no issue even I remove certain value for certain cell in "Col H", and the result is still correct, am I miss out certain information? I just change the filter criteria based on Col H only
=query(IMPORTRANGE("https://docs.google.com/spreadsheets/d/1pY53-XaGnUQ3BPmLh90mLSqIwSo7S2_QOPbD6JBQHOA/edit#gid=0","Master!A3:H"),"Select Col1, Col2, Col4, Col5, Col6, Col7 where Col8 is not null")


text:
Q: Visual Studio 2010 debugger points to wrong line The debugger in Visual Studio 2010 is recently pointing at the wrong lines and/or skipping lines and I have no idea why this is. This is a CUDA project and only happens in CUDA files. I've noticed the following:

*

*It always happens at the same part of the program.

*The lines it points to are always the same, i.e. not random.

*Putting extra code after the culprit lines changes which lines it points to.

*It only happens in .cu-files. Moving the code to a .cpp-file does not recreate the problem.

What I have tried:

*

*Clean and rebuilt the solution.

*Install SP1 for MSVC10 and do all possible updates via Windows Updates

*Set the compiler to not use optimizations in debug mode for both C/C++ and CUDA C/C++

*Manually delete all created files and then rebuild from the solution folder.

*Deleting the folder C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

*Recreating the solution only using the source files.

*Disabling my extensions.

I've managed to reduce the code to the following which might reproduce the problem. Mind that this code has to be inside a .cu-file and most probably needs to be compiled with the cuda compiler for C/C++. Including boost is not really necessary, but this example does show what problems I'm having. A shorter example is at the back.
#include <boost/numeric/ublas/matrix.hpp>
using boost::numeric::ublas::matrix;

struct foo {
    foo() : mat(NULL) {}
    matrix<float>* mat;
};

bool func(foo *data) {
    bool status; // <- skipped line

    status = false;
    if (status) {
        std::cout << "test\n";
        return (status); // <- error reported here
    }

    int size = data->mat->size1(); // instead of here

    return status;
}

int main(int args, char* argv[]) {
    func(NULL); // force error by passing NULL pointer

    return 0;
}

Does anyone have any idea how to solve this or how this could be happening? It's pretty annoying having to debug this way.

Shorter example only showing the skipping lines. No external libraries necessary.
bool func() {
    bool status; // <- skipped line
    status = false;
    return status;
}

int main(int args, char* argv[]) {
    func();
    return 0;
}

A: Since the program only contains CPU instructions and variable declarations of types that have no construction contain no instructions, the debugger will not stop there. It just executes instructions and then uses the debugging information that the compiler provided to find the relevant line of source code.


text:
Q: Mindmap sibling angle in Tikz I am using the following tikz example (original source)
MWE:
% Author: Till Tantau
% Source: The PGF/TikZ manual
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{mindmap,trees}
\begin{document}
\pagestyle{empty}
\begin{tikzpicture}
  \path[mindmap,concept color=black,text=white]
    node[concept] {Computer Science}
    [clockwise from=0]
    child[concept color=green!50!black] {%
      node[concept] {practical}
      [clockwise from=90]
      child {node[concept] {algorithms} }
      child {node[concept] {data structures} }
      child {node[concept] {pro\-gramming languages} }
      child {node[concept] {software engineer\-ing} }
    }
    child[concept color=blue] {%
      node[concept] {applied}
      [clockwise from=-30]
      child {node[concept] {databases} }
      child {node[concept] {WWW} }
    }
    child[concept color=red] {node[concept] {technical} }
    child[concept color=orange] {node[concept] {theoretical} };
\end{tikzpicture}\end{document}

Output:

Where each child is spread 60 degrees apart. I presume you control this spacing with sibling angle=60 (got the idea from here), but I can't use it to change the spacing. Could someone modify the MWE to illustrate how to use it. I would very much appreciate it if you could use a different angle for each branch (including the main branch). Thank you.
EDIT:
There seems to be some confusion as people think I want to space things out randomly. What I want is this instead, if a node has two children, I want to define the spacing to be 180 degrees, if it has 3 children, I want the spacing to be 120 degrees, 4 children, 90 degrees, 5 children 72 degrees and so on. As is, I must have 6 children for it to not look weird.

A: The style set angles for level is used to append the correct sibling distance for level #1.
It can either used inside the level style or possibly in a .listed option.
Usage should vary depending on the use-case in a real document. It may preferable to append set angles for level to grow cyclic or create a custom special grow cyclic that used this solution.
Code
\documentclass[tikz,convert=false]{standalone}
\usetikzlibrary{mindmap,trees,graphs}
\tikzset{
  set angles for level/.style={level #1/.append style={sibling angle=360/\the\tikznumberofchildren}},
  level/.append style={set angles for level=#1}% solution 1
}
\begin{document}
\begin{tikzpicture}
  \path[
    mindmap,
    concept color=black,
    text=white,
    grow cyclic,
    nodes=concept,
%    set angles for level/.list={1,...,4}% solution 2
  ]
  node {Computer Science}
    child[concept color=green!50!black] {%
      node {practical}
      child {node {algorithms} }
      child {node {data structures} }
      child {node {pro\-gramming languages} }
      child {node {software engineer\-ing} }
      child {node {and a fifth}}
    }
    child[concept color=blue] { node[concept] {applied}
      child {node {databases} }
      child {node {WWW} }
    }
    child[concept color=red] {node {technical} }
    child[concept color=orange] {node {theoretical} };
\end{tikzpicture}
\end{document}

Output


text:
Q: "zf create controller" not creating PHPUnit tests Not quite sure why I'm not able to create PHPUnit tests automatically when I create a new Zend controller.
I'm working on Windows with XAMPP. I've installled PHPunit via pear and it's recognized in the command line (version 3.5.14)
The include_path in the php.ini contains c:\xampp\php\PEAR;c:\ZendFramework\library
I added this c:\ZendFramework\library as well to my PATH and ZEND_TOOL_INCLUDE_PATH variables.
But still when I create a new controller, no test cases are created with the following message:
Note: PHPUnit is required in order to generate controller test stubs.

Any idea of something I'm missing or I could try please?


text:
Q: Spark does not build in intellij due to external Flume project issues I have checked out from spark snapshot-2.0.0 and built it successfully on the command line via
mvn clean package -Psparkr -Djavadoc.skip=true -DskipTests=true -Phadoop-2.6
-Dhadoop.version=2.7.1 -Dmaven.javadoc.skip=true -Dscala-2.11 -Phive-thriftserver

However doing a full rebuild in Intellij results in errors in the flume external module:

Is anyone else seeing this problem / or has found a workaround?


text:
Q: PGF: 2 x axes without a second plot I would like to add a second x axis to my single plot. The first x axis goes from 0 to 2, the second one goes from 0 to 0.28. 0.28 on the second axis should be on the same x coordinate as 2 on the first one.
\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[latin1]{inputenc}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{compat=1.16}

\begin{document}
   \begin{tikzpicture}[scale=1.3,transform shape]
        \begin{axis}[
        xlabel={Spulenstrom [A]},
        ylabel={Spitze der Volumenverteilung [nm]},
        xmin=0,
        ymin=0,
        scale only axis,
        ]
        \addplot+[black, mark options ={fill = black}, mark=*, error bars/.cd, y dir=both, y explicit,] coordinates {
        (0.25, 53.92) +- (21.76, 21.79)
        (0.5, 33.9) +- (13.81,13.81)
        (0.75, 29.54) +- (11.72, 11.72)
        (1, 27.35) +- (12.42, 12.42)
        (1.25, 30.38) +- (12.66, 12.66)
        (1.5, 24.97) +- (15.08, 15.08)
        (1.75, 34.46) +- (16.92, 16.92)
        (2, 30.2) +- (13.34, 13.34)
        };
        \end{axis}
        \begin{axis}[
        xlabel = {magnetische Flussdichte [T]},
        xmin = 0, xmax = 0.28, axis x line*=top, axis y line = none, scale only axis,
        ]
        \end{axis}
    \end{tikzpicture}
\end{document}

This is my current code which isn't working. I tried several examples for second y and x axes but all of them assume a second plot.
https://i.stack.imgur.com/riLIB.png This is the picture I currently get with this code

A: I managed to fix it, but it seems like a really crufty hack.
I just plotted the same data again but made it transparent.
    \begin{tikzpicture}[]
        \begin{axis}[
        xlabel={Spulenstrom [A]},
        ylabel={Spitze der Volumenverteilung [nm]},
        xmin=0,
        ymin=0,
        scale only axis,
        ]
        \addplot+[black, mark options ={fill = black}, mark=*, error bars/.cd, y dir=both, y explicit,] coordinates {
        (0.25, 53.92) +- (21.76, 21.79)
        (0.5, 33.9) +- (13.81,13.81)
        (0.75, 29.54) +- (11.72, 11.72)
        (1, 27.35) +- (12.42, 12.42)
        (1.25, 30.38) +- (12.66, 12.66)
        (1.5, 24.97) +- (15.08, 15.08)
        (1.75, 34.46) +- (16.92, 16.92)
        (2, 30.2) +- (13.34, 13.34)
        };
        \end{axis}

        \begin{axis}[
        xlabel = {Magnetische Flussdichte [T]}, xmin = 0, ymin = 0, tick label style={/pgf/number format/fixed},
        axis x line*=top, axis y line = none, scale only axis, xtick = {0, 0.07, 0.14, 0.21, 0.28}
        ]
        \addplot+[black, draw opacity = 0, fill opacity = 0, mark options ={fill = black}, mark=*, error bars/.cd, y dir=both, y explicit, ] coordinates {
        (0.035, 53.92) +- (21.76, 21.79)
        (0.07, 33.9) +- (13.81,13.81)
        (0.105, 29.54) +- (11.72, 11.72)
        (0.14, 27.35) +- (12.42, 12.42)
        (0.175, 30.38) +- (12.66, 12.66)
        (0.21, 24.97) +- (15.08, 15.08)
        (0.245, 34.46) +- (16.92, 16.92)
        (0.28, 30.2) +- (13.34, 13.34)
        };
        \end{axis}
    \end{tikzpicture}


text:
Q: Count Occurrence of Specific Word in the Textarea (JavaScript) I want to write a simple JavaScript that Counts the number of times a word ( or a set of characters) that are typed into input field appear in the textarea field.
Example: Imagine someone pastes a long paragraph into textarea, and wants to see how many times does the word "dog" or phrase "dog on the leash" appears in the text.
Condition:

*

*The match should be case sensitive 'Dog' and 'dog' are not the same thing

*The match should consider spaces 'dog' and 'dog ' are not the same thing.

<textarea id="txtarea" cols="30" rows="5"></textarea>

<input type="text" id="input" cols="15" rows="1"></input>

Could someone please shed some light

A:

var temp = "This is a dog, Dog.";
console.log((temp.match(/dog/) || []).length);


text:
Q: R replace strings not like two strings? I am using the sub function in R to replace any string that does not start with an M OR does not start with T814. I have the code below that successfully keeps any string starting with M, but it isn't keeping the strings that start with T814.
attempt2$dx3 <- sub('^[^M].*| ^[^T814].*', "", attempt2$dx3)

Is there any way I can adjust the code to only keep the strings I'm interested in?
This is an example of what I have:
attempt2 <- data.frame(dx2 = c("M1234", "T8142", "M745", "T8149", "R234"),
                   dx3 = c("M356", "T1142", "M745", "T8146", "G234"))

and what I would like to have:
attempt2 <- data.frame(dx2 = c("M1234", "T8142", "M745", "T8149", ""),
                   dx3 = c("M356", "", "M745", "T8146", ""))

A: Since you're subbing the whole string, you can detect the  matches and then replace everything that doesn't match:
attempt2$dx3[!grepl("^(M|T184)", attempt2$dx3)] <- ""

I believe the other option is negative look-ahead, and Wiktor's comment is probably spot-on.

A: Using str_detect
library(stringr)
library(dplyr)
attempt2 %>%
   mutate(dx3 = replace(dx3, !str_detect(dx3, "^(M|T8146)"), ""))

A: There is a handy library for this:
library(inops)
attempt2 %out~% c("^M", "^T814") <- ""

Here %out~% matches all elements that do not match the regular expressions specified on the right side. You can then assign a replacement value to this expression at the end of the line.


text:
Q: Null Pointer Exception in Spark rdd.RDD.take Spark doesn't give very informative error messages in one's code, but for future reference, this question is for anyone who gets a Null Pointer Exception that looks like this:
java.lang.NullPointerException
    at org.apache.spark.rdd.RDD.take(RDD.scala:850)
    at org.apache.spark.rdd.RDD.first(RDD.scala:862)
    at modelBuilding$$anonfun$3.apply(modelBuilding.scala:46)
    at modelBuilding$$anonfun$3.apply(modelBuilding.scala:46)
    at scala.collection.Iterator$$anon$14.hasNext(Iterator.scala:390)
    at scala.collection.Iterator$$anon$20.hasNext(Iterator.scala:634)
    at scala.collection.Iterator$class.foreach(Iterator.scala:727)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
    at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
    at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
    at scala.collection.AbstractIterator.to(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
    at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
    at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$4.apply(RDD.scala:608)
    at org.apache.spark.rdd.RDD$$anonfun$4.apply(RDD.scala:608)
    at org.apache.spark.SparkContext$$anonfun$runJob$4.apply(SparkContext.scala:884)
    at org.apache.spark.SparkContext$$anonfun$runJob$4.apply(SparkContext.scala:884)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:109)
    at org.apache.spark.scheduler.Task.run(Task.scala:53)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$run$1.apply$mcV$sp(Executor.scala:211)
    at org.apache.spark.deploy.SparkHadoopUtil.runAsUser(SparkHadoopUtil.scala:45)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:176)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

A: Thankfully, there is a variant of the problem discussed here:
http://apache-spark-user-list.1001560.n3.nabble.com/java-lang-NullPointerException-met-when-computing-new-RDD-or-use-count-td2766.html
One way that this comes up is that RDD's cannot be referenced in the closure of a map call.
For example,
if my original code is
 val shiftRDD = qtRdd.filter { _.qtExtEvents.qt.date.getTime() != qtRdd.first().qtExtEvents.qt.date.getTime() }

you have to refactor the reference to the RDD out:
val firstVal = qtRdd.first().qtExtEvents.qt.date.getTime()
val shiftOneqtRdd = qtRdd.filter { _.qtExtEvents.qt.date.getTime() != first }


text:
Q: Given 4 integers, $a, b, c, d > 0$, does $\frac{a}{b} < \frac{c}{d}$ imply $\frac{a}{b} < \frac{a+c}{b+d} < \frac{c}{d}$? We were trying to come up with an easy way to generate a rational number in between two existing rational numbers with a fairly low numerator and denominator (the way we were doing this earlier was to find the average of the two rationals, but that results in a denominator of up to $c * d$. Does this inequality hold for all values of $a, b, c, d$?

A: That follows from the slightly more general statement:

For $a_1, \ldots, a_n \in \Bbb R$, $b_1, \ldots, b_n > 0$ we have
  $$
 \min_i \frac{a_i}{b_i} \le \frac{a_1 + \ldots + a_n}{b_1 + \ldots + b_n}
 \le \max_i \frac{a_i}{b_i} \, ,
$$
  and equality holds if and only if $\frac{a_1}{b_1} = \frac{a_2}{b_2}
= \dots \frac{a_n}{b_n}$.

(Note that the numerators need not be positive.)
Proof: Define
$$
 L =\min_i \frac{a_i}{b_i} \quad, \quad U = \max_i \frac{a_i}{b_i} \, ,
$$
 then
$$ \tag{*}
 b_i L \le \underbrace{b_i \frac{a_i}{b_i}}_{a_i}  \le b_i U
 \quad \text{for $i=1, \ldots, n$}
$$
and adding these inequality gives
$$
  L (b_1 + \ldots + b_n) \le a_1 + \ldots + a_n \le U (b_1 + \ldots + b_n) \, .
$$
Equality holds if and only if equality holds in $(*)$ for all $i$,
i.e. if all quotients $a_i/b_i$ are equal.

A: This is called the mediant. The inequality does indeed hold for all $a,\ b,\ c,\ d$.

A: Weighted average of two numbers with positive weight lies between the two numbers.
$$
x<y\phantom{x}\leftrightarrow\phantom{x}x<\frac{b}{b+d}\cdot x+\frac{d}{b+d}\cdot y<y
$$
Now substitute $x=\frac{a}{b}$ and $y=\frac{c}{d}$

A: Yes, the inequality holds. One standard approach to proving that $x\lt y\,$ is to show that $y-x\gt 0$.
Apply this to $x=\dfrac{a}{b}$ and $y=\dfrac{a+c}{b+d}$.
The difference is $\dfrac{a+c}{b+d}-\dfrac{a}{b}$, which simplifies to $\dfrac{bc-ad}{(b+d)b}$. But $bc\gt ad$ follows from our initial inequality.
The same method works for showing that $\dfrac{a+c}{b+d}\lt \dfrac{c}{d}$.

A: Hint $\ $ The middle term $\large \color{#0a0}{\frac{a+c}{b+d}}\:\!$ (known as the mediant), is the slope of the diagonal of the parallelogram with sides being the vectors $\color{blue}{(b,a)},\ \color{#c00}{(d,c)}.\:$ Clearly the slope of the diagonal lies between the slopes of the sides.
$\quad$

A: The setting where this occurs as a matter of course is simple continued fractions for, in this case, some positive quantity. If the "partial quotient" is some $k$ that is not necessarily equal to $1,$ the two related cases of the next "convergent" are
 $$\frac{a}{b} < \frac{a+kc}{b+kd} < \frac{c}{d},$$ which is what you get if the two convergents happen to be in increasing order, otherwise
  $$ \frac{c}{d}  > \frac{c + ka}{d + kb} > \frac{a}{b}$$  where the inequality signs need to be massaged as the two convergents happen to be in decreasing order. Anyway, both displayed inequalities are true.
See SIMPLE


text:
Q: How should I understand `let _ as s = "abc" in s ^ "def"` in OCaml? let _ as s = "abc" in s ^ "def"
So how should understand this?

I guess it is some kind of let pattern = expression thing?
First, what's the meaning/purpose/logic of let pattern = expression?
Also, in pattern matching, I know there is pattern as identifier usage, in let _ as s = "abc" in s ^ "def", _ is pattern, but behind as, it is an expression s = "abc" in s ^ "def", not an identifier, right?
edit:
finally, how about this: (fun (1 | 2) as i -> i + 1) 2, is this correct?
I know it is wrong, but why? fun pattern -> expression is allowed, right?

I really got lost here.

A: The grouping is let (_ as s) = "abc" -- which is just a convoluted way of saying let s = "abc", because as with a wildcard pattern _ in front is pretty much useless.

A: The expression let pattern = expr1 in expr2 is pretty central to OCaml. If the pattern is just a name, it lets you name an expression. This is like a local variable in other language. If the pattern is more complicated, it lets you destructure expr1, i.e., it lets you give names to its components.
In your expression, behind as is just an identifier: s. I suspect your confusion all comes down to this one thing. The expression can be parenthesized as:
let (_ as s) = "abc" in s ^ "def"

as Andreas Rossberg shows.
Your final example is correct if you add some parentheses. The compiler/toplevel rightly complains that your function is partial; i.e., it doesn't know what to do with most ints,
only with 1 and 2.
Edit: here's a session that shows how to add the parentheses to your final example:
$ ocaml
        OCaml version 4.00.0

# (fun (1 | 2) as i -> i + 1) 2;;
Error: Syntax error
# (fun ((1 | 2) as i) -> i + 1) 2;;
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
0
- : int = 3
#

Edit 2: here's a session that shows how to remove the warning by specifying an exhaustive set of patterns.
$ ocaml
        OCaml version 4.00.0

# (function ((1|2) as i) -> i + 1 | _ -> -1) 2;;
- : int = 3
# (function ((1|2) as i) -> i + 1 | _ -> -1) 3;;
- : int = -1
#


text:
Q: Determining the Length and Width of Objects in an Image with Java I want to be able to determine the length and width of all shapes in an image with a transparent background. Can anyone give me some tips in java on how to do this?
Here is an example

Edit: All pixels within each shape do not have the exact same RGB value, however, they are shades of the same color.

A: Depends on what you are starting with and how you define length and width.  Image analysis is a large field, and there are several nice image analysis packages/libraries written in Java (have a look at http://imagej.nih.gov/ij/ and http://fiji.sc/ImgLib2).
However, if you have access to the RGB values of your image, all pixels in each structure have the exact same RGB value, and you are interested in finding the width and length of the bounding box of the structures in your image, then you can iterate through the x and y coordinates of the image an keep track of the minimum and maximum x and y coordinate for each RGB value.  The difference between minimum and maximum in x will give the width, and in y will give you the height.


text:
Q: How to check length of lines inside a td for text and show more content on click I am trying to show "see more" which when clicked will show the full content inside a td.
The condition for see more is that it will appear when the text inside td has more than 3 lines, then show "see more" and onclick expand and show full content.
Here, width is set to 318px and user may or may not change.
I can give line-height to td to be 21px, and based on calculations I can calculate number of lines but in array the text are random and array size is increasing with scroll. The array size may be in 1000s or much more.  So I don't want to maintain array size which have 1000 or more elements which contain status for each text (array elements) about number of lines.
Is there, any better way where a simple trick can be applied to all text   (array elements).
here is stackblitz link:- https://stackblitz.com/edit/angular7-test-mndgc5?file=app%2Fapp.component.html
.ts
// textss is dyanamic and can be 100 or with a scroll

textsss = [
"In 2005, Nature published a peer review comparing 42 science articles from Encyclopædia Britannica and Wikipedia and found that Wikipedia's level of accuracy approached that of Britannica. Time magazine stated that the open-door policy of allowing anyone to edit had made Wikipedia the biggest and possibly the best encyclopedia in the world, and was a testament to the vision of Jimmy Wales.",
 "005, Nature published a peer review comparing 42 science articles from Encyclopædia Britannica and Wikipedia and found that Wikipedia's level of accuracy approached that of Britannica.",
"abcdffff",
"ished a peer review comparing 42 science articles from Encyclopædia Britannica and Wiki",
.
.
.
.
]

 ngAfterViewInit(){
  this.viewHeight = this.elementView.nativeElement.offsetHeight;
     console.log( this.viewHeight);
    this.lines = Math.round(this.viewHeight/ 21);
     console.log(this.lines);
     if(this.lines > 3){
       this.dynamicTextHeight = 3 * 21;
     }
  }

  expand(){
     this.dynamicTextHeight = this.lines * 21;
  }

.html

{{i + 1}}.  3" (click)="expand()">... see more{{text}}

A: Update:
Since CSS was not enough, I've refactored to handle each box as a component and made the height calculation at the beginning (AfterViewInit) and use it to display or not the extra lines.
Demo: https://stackblitz.com/edit/angular7-test-x7pqvp

You can achieve that with CSS + toggling the ngStyle:

*

*text-overflow + fixed height (calculated from font-size, line-height and number of lines to show). And SASS may help with that calculation.

*Display see more/less by switching the ngStyle definition.


text:
Q: Not able to edit sample invocations in directory listing I am getting trouble with editing sample invocation name in directory listing and also not able to see previous written sample invocations.My skill got not approved due to following reason
Your sample invocations are structured incorrectly. Make sure they all begin with "Ok Google", they all contain some reference to your invocation name or display name, and they all trigger one of your actions when said.
But i'm not able to see previous written sample invocations?
Here is the attached image
sample invocation showing error in directory listing
Previous entered sample invocations is not displaying in directory listing


text:
Q: Putting an icon on the corner of the border of a div with :before Apologies in advance this is my first post on SO so if I'm not giving what you need I'll try and figure it out. To give context: this is for the css of an .epub if that helps.
I am trying to place an image on the top corner of the border of multiple specific divs. I'm currently using :before, however if the div in question is not the first on the page, the icon isn't actually a part of the border, instead it is just at the top left corner of the page.
I made this JSFiddle to demonstrate what I'm trying to achieve, but it's not quite there. The icon is in the top corner of the div but that's not where I want it, I want it in the top corner of the border. If I remove position:absolute and position:relative from parent and child div then the icon goes to the top corner of the page.
Alternatively to JSFiddle:

    .other {
      margin-top: 20px;
      margin-left: 20px;
      margin-right: 20px;
      margin-bottom: 20px;
      border: 10px solid transparent;
      padding-left: 20px;
      padding-right: 20px;
      padding-top: 10px;
      padding-bottom: 20px;
      }
    .info {
      margin-top: 20px;
      margin-left: 20px;
      margin-right: 20px;
      margin-bottom: 20px;
      border: 10px solid transparent;
      padding-left: 20px;
      padding-right: 20px;
      padding-top: 10px;
      padding-bottom: 20px;
      border-image: url(https://i.ibb.co/YDRL4pQ/box.png) 30% round;
      position:relative;
    }
    .info:before {
        content: '';
        height: 50px;
        width: 50px;
        position: absolute;
        top: 5px;
        left: 5px;
        background:url(https://i.ibb.co/S5zFz5r/dig-deeper.png);
        }
Unrelated text further up the page

unrelated div further up the page

div with text for icon

Hopefully I've provided enough info and context! I've searched the site for similar subjects and nothing seems to be quite what I'm looking for, as my end code would look like: . The radius in the bottom corner would be good but not necessary.

A: Jus use propertys top and left in info:before to move it over the border. See example .... ;-)

.other {
    margin-top: 20px;
    margin-left: 20px;
    margin-right: 20px;
    margin-bottom: 20px;
    border: 10px solid transparent;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 10px;
    padding-bottom: 20px;
}

.info {
    margin-top: 20px;
    margin-left: 20px;
    margin-right: 20px;
    margin-bottom: 20px;
    border: 10px solid transparent;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 10px;
    padding-bottom: 20px;
    border-image: url(https://i.ibb.co/YDRL4pQ/box.png) 30% round;
    position: relative;
}

.info:before {
    content: '';
    height: 50px;
    width: 50px;
    position: absolute;
    /* use this values for positioning
    negative values move it over the border */
    top: -10px;
    left: -10px;
    background: url(https://i.ibb.co/S5zFz5r/dig-deeper.png);
}

    unrelated div further up the page

div with text for icon


text:
Q: Join me in welcoming Valued Associate #820: Shodipo Ayomide For some time now, I've been looking forward to announcing the following news. Our dedicated team of Community Managers has increased today with the addition of Shodipo Ayomide! Please help me welcome him to our communities!
Shodipo, who goes by Ayo (pronounced "I-O") brings 5 years of professional experience working as a full-stack engineer between companies. He was more of a JavaScript & PHP fan for those years but he has 9 years of experience in technology. While growing this experience, he worked many jobs both full-time and a number of contract jobs as an engineer. This eventually led him to notice online communities.

Ayo began developing a feel for dev communities when he got an offer as a software engineer from Techpoint, a Nigerian-based technology news publishing platform. He was able to attend events, learn and grow. He found himself appreciating the camaraderie with other developers. Ayo's first event was actually a "Women in Tech" conference in Nigeria that he says was so much fun! When he realized that he deeply appreciated developer communities, he joined Developers Circles Lagos from Facebook as a co-organizer and that started it all. He now leads unStack Africa, a workshop-based community now present in 6 African countries, and co-organizes Open Source Community Africa, the largest open source community in Africa with chapters across all technically active countries in Africa. They've raised $73k for their Open Source Festival in February 2020 and flew top-level execs from Google, Facebook, Microsoft, GitHub, SAP, and more down to Nigeria for NaijaHacks, the largest hackathon ever in Africa which raised a total of $120k in sponsorships in 2019. As you can see, Ayo loves the developer community and that will help him to be a phenomenal contributor and leader of the Stack Overflow community.
Ayo believes as we do, that online communities are the future. Connecting everyone all at once in a community without traditional barriers like expensive entrance fees or travel expenses means that more people can be reached and conferences/meetups for larger audiences can be planned. We have various kinds of people in our online community and the fact that our focus is the online community means that we can effectively plan for each kind of community member without thinking about venues, halls, food, and more.
In his personal time, Ayo enjoys watching movies - think "Netflix party with friends & co-workers," playing games, reading, building side projects, trying new food, traveling, meeting new people, and yes, spending time with his family. I'm sure we'll be seeing lots of him around the network so when you run into him, please say hello and help him feel welcomed.

A: Welcome Ayo!
While I haven't been to Nigeria, "Things Fall Apart" by Chinua Achebe and "Half of the Yellow Sun" by Chimamanda were two of the major works we had to study in the "African Literature" course I took when I was a student at Oxford. I also regularly cheer for Nigeria in the FIFA World Cup.
I look forward to the opportunity to get to know you, whether here on Meta.SE or in the various chat rooms!

A: Welcome to the CM family and I'm happy they now have two more hands to share the workload.
Let us know when we demand too much of you and your colleagues.
As you seem to like movies:

*

*What was the last movie you watched?

*Which movie do you recommend we should all go see?

Do you know we have a Movie & TV site? Are you planning on participating there?

A: Welcome, Ayo!
Your history seems to be jam-packed with community organizing where you live, and it's really awesome to see that. With all of that history backing you up, I'm sure you're going to fit in just fine here. Looking forward to seeing you in action, Ayo. You seem perfect for the role. :)

A: Welcome Ayo, and good luck! (You'll need it :P) Great to see a community manager who will (probably) be working during European African office hours, for a change.

A: Congratulations and welcome, Ayo! Nigeria has been a growing hub for tech & innovation for years now; it will be awesome to get some representation from that region and all the cool stuff happening there.

A: Welcome Ayo!
However, I do have a small concern.
Ayo does not appear to be involved in Stack Exchange, he was brought "from the outside". Did you (the existing Community Team) make any special efforts to explain how things work in Stack Exchange?

A: Welcome to the CM team Ayo. I hope we will see a lot of you around the network. If you ever feel like saying "Hi", and have some (informal) chat, do drop by at the Tavern, all others are welcome as well ;).
Seeing that recently it was discussed in this blogpost that the CM team will be divided in threefold, what (sub)team will Ayo become a part of?

A: Welcome Ayo!
I hope that your time with Stack Exchange will be long and fruitful.

A: A warm welcome to you, Ayo!
I hope your stay at Stack Exchange is a happy one (give it 6-8 weeks, you'll be fine;).


text:
Q: glDrawPixels of numpy array not showing up I am trying to draw conway's game of life with opengl. It works fine in regular pygame, but I've read that glTexImage2D is the way to go for fast drawing of stuff already in an array. I've checked out the examples and docs provided but not only are a fair amount of example links dead, but they were written for python 2 so I can't even run a lot of them without translating it. I've noticed that unlike most modern GUI packages, opengl doesn't really return anything so I think I'm just not applying the texture right. (as in, in pygame you'd generate the surface then apply the returned surface). The conways code works by taking in the alive and dead values and the dtype, then doing all the necessary checking based solely on the constructor arguments meaning that that I can change it from ubyte to float in the blink of an eye, so if that's the issue that's great.
At the moment it's just a black screen. When pygame.display.flip() is removed, it just stays white, so theoretically something is being drawn somewhere to change it to black. I have a feeling the problem lies around the glbindtexture method but honestly I don't know what the solution is.
I'll put the conways code in just in case anyone wants to run it. In the pygame mode I scale the image by the scale variable, but for opengl I just want it running first so the size of the conways array will be the window size for now, hence the 400. That means it'll take a bit, but once the window title is updated that's an indicator that the update has been completed.
opengl drawer:
import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *
from random import random,seed
import numpy as np
from conways3 import Conways
from time import time

size = 400;
scale = 1;

conways = Conways(size,dead=0.0,alive=1.0,dtype=np.ubyte)

pygame.init()
flags = OPENGL|HWSURFACE|DOUBLEBUF
display = pygame.display.set_mode((size*scale, size*scale),flags)
########OPTIMIZATIONS##########
pygame.event.set_allowed([pygame.QUIT]);
###############################

running = True

clock = pygame.time.Clock()
t1 = t2 = t3 = 0
glEnable(GL_TEXTURE_2D)
try:
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        clock.tick()
        t1 = time()
        Z = conways.update()
        t2 = time()
        tid = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, tid)
        glPixelStorei(GL_UNPACK_ALIGNMENT,1)
        glTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE, size,size,0,GL_LUMINANCE, GL_UNSIGNED_BYTE, Z)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

    ##    surf = pygame.surfarray.make_surface(Z)
    ##    display.blit(pygame.transform.scale(surf,(size*scale, size*scale)), (0, 0))
    ##    pygame.display.update()
        pygame.display.flip()
        t3 = time()
        pygame.time.wait(10)
        pygame.display.set_caption("fps: {:.4f} calc: {:.4f} draw: {:.4f} tot: {:.4f}".format(clock.get_fps(), t2-t1, t3-t2,t3-t1))
##        print(t2-t1)
except Exception as e:
    print('-'*20)
    print(e)

pygame.quit()

conways:
from random import random, seed
import numpy as np
from time import time

class Conways:
    def __init__(self,size,dead=False,alive=True,dtype = np.bool8):
        seed(1)

        self.using1 = True;

        self.size = size;
        self.dead = dead;
        self.alive = alive;
        self.dtype = dtype;

        self.arr1 = np.zeros((self.size,self.size),dtype=self.dtype);
        self.arr2 = np.zeros((self.size,self.size),dtype=self.dtype);

        for i in range(self.size):
                for j in range(self.size):
                        self.arr1[i][j] = self.alive*(random() < 0.5);
    def calcNeighbors(self,arr, i, j):
            count = -1*arr[i][j];
            for x in range(-1, 2):
                    for y in range(-1, 2):
                            count += (arr[(x+i)%self.size][(y+j)%self.size] == self.alive);
            return count;
    def calcEffi(self,arr, i, j):
            count = 0
            maxi = self.size - 1
            if i > 0:
                    count     += arr[i - 1][j] == self.alive
            if i < maxi:
                    count     += arr[i + 1][j] == self.alive
            if j > 0:
                    count     += arr[i][j - 1] == self.alive
                    if i > 0:
                            count += arr[i - 1][j - 1] == self.alive
                    if i < maxi:
                            count += arr[i + 1][j - 1] == self.alive
            if j < maxi:
                    count     += arr[i][j + 1] == self.alive
                    if i > 0:
                            count += arr[i - 1][j + 1] == self.alive
                    if i < maxi:
                            count += arr[i + 1][j + 1] == self.alive
            return count;

    def calc(self,arr1, arr2):
            for i in range(self.size):
                    for j in range(self.size):
                            neighbors = self.calcEffi(arr1, i, j);
                            if neighbors < 2 or neighbors > 3:
                                    arr2[i][j] = self.dead;
                            elif neighbors == 3:
                                    arr2[i][j] = self.alive;
                            else:
                                    arr2[i][j] = arr1[i][j];
    def update(self):
            if self.using1:
                    self.calc(self.arr1,self.arr2);
            else:
                    self.calc(self.arr2,self.arr1);
            self.using1 = not self.using1;
            return self.arr2 if self.using1 else self.arr1;

A: Since the array values are in the range [0, 1], you have to use float32 respectively GL_FLOAT:
conways = Conways(size,dead=0.0,alive=1.0,dtype=np.float32)

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, size, size, 0, GL_LUMINANCE, GL_FLOAT, Z)

But the major issue is that you don't draw anything. You have to draw a quad on the entire viewport, with the texture wrapped on it:
glBindTexture(GL_TEXTURE_2D, tid)
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, size,size, 0, GL_LUMINANCE, GL_FLOAT, Z)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

glBegin(GL_TRIANGLE_FAN)
glTexCoord2f(0, 1)
glVertex2f(-1, -1)
glTexCoord2f(1, 1)
glVertex2f(1, -1)
glTexCoord2f(1, 0)
glVertex2f(1, 1)
glTexCoord2f(0, 0)
glVertex2f(-1, 1)
glEnd()

Or use glEnableClientState, glVertexPointer, glTexCoordPointer and glDrawArrays to draw onto the viewport:
vertices   = np.array([-1, -1, 1, -1, 1, 1, -1, 1], dtype=np.float32)
tex_coords = np.array([0, 1, 1, 1, 1, 0, 0, 0], dtype=np.float32)

glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(2, GL_FLOAT, 0, vertices)
glEnableClientState(GL_TEXTURE_COORD_ARRAY)
glTexCoordPointer(2, GL_FLOAT, 0, tex_coords)

glDrawArrays(GL_TRIANGLE_FAN, 0, 4)

glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_TEXTURE_COORD_ARRAY)

But note, that drawing by glBegin/glEnd sequences and also client-side capability of the OpenGL fixed function pipeline is deprecated since decades.
Read about Fixed Function Pipeline and see Vertex Specification and Shader for a state of the art way of rendering.


text:
Q: Algorithm for approximating linear-interpolated curve Goal
Given a curve defined by a set of (x, y) coordinates with linear interpolation, we want to find the best approximation using a smaller set of points (w/ linear interpolation) that fall along a predefined grid. The number of points and the grid are chosen up front and are static. The following invariants must be held:

*

*Our approximation must not go below the original curve at any point. (Both curves are generated by sorting by the x-axis values and drawing lines between neighbors).

*The grid origin is (0, 0) and generated from an x-step and y-step values.

*Our approximation must fully cover the original curve.  This means that our first (x1) and last (x2) x-axis values are forced by the set of (x, y) coordinates of the original curve and x-axis step, and that our possible y-axis values are bounded below by the minimum y-step multiple that is >= min y-axis value found in the original curve (derived from first invariant).

*Y-axis values must fall between [0, 255].

*The best approximation will be the one that has the smallest area between the approximation and original curve.

Example
# Example arguments provided to algorithm
# curve - Contains 25 points, sorted by x-axis ascending, w/ linear interpolation between neighbors
original_curve = [(450, 38), (462.5, 28), (481.25, 28), ..., (887.5, 22)]
# Our answer must use points that fall along the grid generated by the below steps
x_step = 25
y_step = 1
# Number of points allowed in the approximation
num_points = 5

# We can compute the following boundaries based on the arguments
max_x_on_grid = 900
min_x_on_grid = 450
max_y_on_grid = 255
# The full dataset is not shown above, but the minimum y-axis value is 9, which is equal to a multiple of y_step
min_y_on_grid = 9

# We want our approximation to use 5 points, which means we can immediately determine the following
answer = [(450, ?), (?, ?), (?, ?), (?, ?), (900, ?)]

What I've tried
Originally I thought I might be able to do an exhaustive search, but the number of possibilities is way too high.
Number of possible x-axis selections = C(22, 3)
Number of possible y-axis selections = P(245, 5) (w/ replacement)
Number of possibilities = C(22, 3) * P(245, 5) = 1540 * 882,735,153,125 = 1.3594121e+15

I'm certain there is a more intelligent algorithm I could use.  I've implemented the genetic algorithm before, and I imagine it would get a good result, but I would like to get the best result. I've tried to play with the idea of starting at the max_y_on_grid and doing some type of search + backtracking from there, but I thought I would ask in case anyone has already done this.

A: Due to time constraints and our inability to come up with a better solution, we ended up using the genetic algorithm to compute our approximation.  It was able to generate a better approximation then any of our other attempts, and it did so efficiently (rust implementation took 1-15 seconds).  Here is a list of the genetic parameters we used if anyone is curious.
Population size: 1000
Mutation Rate: 1%
Elitism: 10%
Selection: Tournament
    Tournament size: 4
    Tournament probability: 0.75