text:
Q: Wordpress Theme: Box jumping in chrome Hoping someone here can help me, I installed a wordpress theme on a site ( http://nationalaviationinstitute.ie/ ) and I have an issue I can't resolve and the developer of the theme is refusing to acknowlege the issue!
If you visit the above site in Chrome, the bottom section of the site jumps up and covers the four service areas underneath the image slider. This only happens in Chrome, it's ok in all other browsers, it's obviously something to with the responsiveness of the site as if you resize the bottom section moves back to the correct position.
I'm fairly familiar with CSS and HTML so if anyone could give me a hand figuring out the cause of this and a possible solution I'd greatly appreciate it.
Thanks,
Anthony

A: There is a javascript bug which is giving the divs inside each
 tag style="height: 0px;" on resize event like the example below:

Our Courses

At NAI we have a number of different courses to suit everybody's needs, academic to professional.  read more →

if you find and fix the js that is causing this problem than the problem will be fixed.
But incase you need a faster fix you can add the following css:
.block-thumbnail{
     display: inline-block;
}

It will override the style="height: 0px;" added by the js and the bottom section will be pushed down


text:
Q: Gradient at a critical point Why should the gradient be $0$ at a critical point? I'm not sure the reason other then we set the gradient of a function to zero to find the critical points.

A: The critical point of $f(x,y)$ is defined where $f_x = 0 = f_y$,and the gradient of $f$ is defined $\nabla f = (f_x,f_y)$. Thus it would be zero at critical point. It should be a comment but I tried capitalize on it...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to speed up this query I used this query and it took too long for mysql to give results. The number of rows are 1.6 millions.
SELECT DISTINCT TB.ID,  Latitude, Longitude,
    111151.29341326*SQRT(pow(-6-`Latitude`,2)
        +pow(106-`Longitude`,2)*cos(-6*0.017453292519943)
        *cos(`Latitude`*0.017453292519943)) as Distance
FROM `tablebusiness` AS TB, `tablecity` AS TC, `businessestag` AS BC,
    `businessesdistricts` AS BD, `tabledistrict` AS TD,
     (SELECT ID,
         (SELECT Title
            FROM `tablebusiness` As TBuild
           WHERE TBuild.ID = TBB.Building) As BuildingTitle
      FROM `tablebusiness` As TBB) AS TBuilding
WHERE TB.City = TC.City AND BC.BusinessID = TB.ID AND BD.BusinessID = TB.ID
  AND TD.ID = BD.District AND TBuilding.ID = TB.ID
  AND (`Title` LIKE '%%' OR `Street` LIKE '%%'  OR TB.City LIKE '%%'
       OR Country LIKE '%%' OR Tag LIKE '%%' OR TD.District LIKE '%%'
       OR TBuilding.BuildingTitle LIKE '%%')
  AND (-6.0917668133836 < `Latitude` AND `Latitude` < -5.9082331866164
       AND 105.90823318662 < `Longitude` AND `Longitude` < 106.09176681338)
ORDER BY Distance LIMIT 0, 100

Even though the number of rows are 1.6 million part of the query namely
AND (-6.0917668133836 < `Latitude` AND `Latitude` < -5.9082331866164 AND 105.90823318662 < `Longitude` AND `Longitude` < 106.09176681338)

greatly restrict the number of rows. It seems as if mysql doesn't bother optimizing the query by searching for
AND (-6.0917668133836 < `Latitude` AND `Latitude` < -5.9082331866164 AND 105.90823318662 < `Longitude` AND `Longitude` < 106.09176681338) first.

I changed the query by moving the latitude longitude aspects on the front
SELECT DISTINCT TB.ID,  Latitude, Longitude,
    111151.29341326*SQRT(pow(-6-`Latitude`,2)
        +pow(106-`Longitude`,2)*cos(-6*0.017453292519943)
        *cos(`Latitude`*0.017453292519943)) as Distance
FROM `tablebusiness` AS TB, `tablecity` AS TC, `businessestag` AS BC,
    `businessesdistricts` AS BD, `tabledistrict` AS TD,
     (SELECT ID,
         (SELECT Title
            FROM `tablebusiness` As TBuild
           WHERE TBuild.ID = TBB.Building) As BuildingTitle
      FROM `tablebusiness` As TBB) AS TBuilding
WHERE (-6.0917668133836 < `Latitude` AND `Latitude` < -5.9082331866164
       AND 105.90823318662 < `Longitude` AND `Longitude` < 106.09176681338)
  AND TB.City = TC.City AND BC.BusinessID = TB.ID AND BD.BusinessID = TB.ID
  AND TD.ID = BD.District AND TBuilding.ID = TB.ID
  AND (`Title` LIKE '%%' OR `Street` LIKE '%%'  OR TB.City LIKE '%%'
       OR Country LIKE '%%' OR Tag LIKE '%%' OR TD.District LIKE '%%'
       OR TBuilding.BuildingTitle LIKE '%%')
ORDER BY Distance LIMIT 0 ,100

It's still just as slow.
What should I do then?

A: Searching for some part of the query is only possible with index. So you have to have an index. Since MySQL has extension for (geo)spatial data, you should look it up and use the R-tree index. That's the most efficient kind for range limit on two columns.

A: Do you have BTree index on Langitude and Longitude columns?

A: What does explain select ... and show create table tablebusiness \G say?
There are some restrictions to how MySQL can use an index for range queries, be sure to read up on that.
In my experience for many use cases, in MySQL using b-tree indexes is more efficient than the spatial indexes.  I'd suggest changing longitude and latitude to be integers (multiply by an appropriate number to get the "decimals" and making sure you have an index that span both columns (alter table tablebusiness add index latlon (latitude,longitude)).

A: Do you really need to include tablebusiness table in FROM clause three times? I have rewrited this one and used JOINs. Check your WHERE conditions. What is Title LIKE '%%'? Try this simplified query -
SELECT
  TB.ID,
  Latitude,
  Longitude,
  111151.29341326 * SQRT(POW(-6 - `Latitude`, 2) + POW(106 - `Longitude`, 2) * COS(-6 * 0.017453292519943) * COS(`Latitude` * 0.017453292519943)) AS Distance
FROM
  `tablebusiness` AS TB
  JOIN `tablecity` AS TC
    ON TB.City = TC.City
  JOIN `businessestag` AS BC
    ON BC.BusinessID = TB.ID
  JOIN `businessesdistricts` AS BD
    ON BD.BusinessID = TB.ID
  JOIN `tabledistrict` AS TD
    ON TD.ID = BD.District
  LEFT JOIN `tablebusiness` TBuilding
    ON TBuilding.ID = TB.ID
WHERE
  (`Title` LIKE '%%' OR `Street` LIKE '%%' OR TB.City LIKE '%%' OR Country LIKE '%%'
    OR Tag LIKE '%%' OR TD.District LIKE '%%' OR TBuilding.BuildingTitle LIKE '%%')
  AND (-6.0917668133836 < `Latitude` AND `Latitude` < -5.9082331866164
    AND 105.90823318662 < `Longitude` AND `Longitude` < 106.09176681338)
ORDER BY
  Distance
LIMIT
  0, 100

Adding indexes on the fields used in JOIN and WHERE clauses also will speed up the query.


text:
Q: Rest Service and Client in Java I devoloped the following Rest service:
@POST
@Path("getTokenUser")
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String getTokenUser(@QueryParam("User")String
User,@QueryParam("Password")String Password) throws Exception
{
    pToken ptoken=new pToken();
    return ptoken.getAuth_Token(User, Password).toString();
}

And the client:
try
  {
    Client cliente=Client.create();
    WebResource wresource=cliente.resource("http://Localhost:8084/API_FE/webresources/Facturacion/getTokenUser");
    String values="{\"User\":\"AbrahamV\",\"Password\":\"1234sa\"}";
    ClientResponse response = wresource.type("application/json").post(ClientResponse.class, values);
    String output = response.getEntity(String.class);System.out.println(output);
  }
  catch(Exception ex)
  {
      System.out.println("Error:"+ex.getMessage());
  }

But when I run the client,the rest service doesn't recive anything. I don't know what Im doing bad, I'm new in this.
Response Web Service Rest:
run:
{"Message":"Son necesarias las credenciales de acceso","Token":"","Code":"afe-e01"}

A: I could solve it.
try
  {
    Client cliente=Client.create();
    WebResource wresource=cliente.resource("http://Localhost:8084/API_FE/webresources/Facturacion/getTokenUser");
    MultivaluedMap<String,String> data=new  MultivaluedHashMap();
    data.add("User","Abraham01");
    data.add("Password","14235afe");
    ClientResponse response =wresource.queryParams(data).post(ClientResponse.class);
    String output = response.getEntity(String.class);System.out.println(output);
  }
  catch(Exception ex)
  {
      System.out.println("Error:"+ex.getMessage());
  }

Instead sending a json structure, I send a MultivaluedMap in a queryParams.


text:
Q: " Could not find API definition for name "JDO"" when launched through jar So when I try to connect to my hive metastore I'm getting this exception
javax.jdo.JDOFatalInternalException: Unexpected exception caught.
    at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation(JDOHelper.java:1193)
    at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:808)
    at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:701)
    at org.apache.hadoop.hive.metastore.ObjectStore.getPMF(ObjectStore.java:412)
    at org.apache.hadoop.hive.metastore.ObjectStore.getPersistenceManager(ObjectStore.java:441)
    at org.apache.hadoop.hive.metastore.ObjectStore.initialize(ObjectStore.java:336)
    at org.apache.hadoop.hive.metastore.ObjectStore.setConf(ObjectStore.java:292)
    at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:73)
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:133)
    at org.apache.hadoop.hive.metastore.RawStoreProxy.<init>(RawStoreProxy.java:60)
    at org.apache.hadoop.hive.metastore.RawStoreProxy.getProxy(RawStoreProxy.java:69)
    at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.newRawStore(HiveMetaStore.java:681)
    at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.getMS(HiveMetaStore.java:659)
    at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:708)
    at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:507)
    at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:78)
    at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:84)
    at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:6286)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:207)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:187)
    at com.bouygtel.jupiter.dic.catalogue.AspirationMetastore.aspirer(AspirationMetastore.java:146)
    at com.bouygtel.jupiter.dic.integration.adaptateurs.AdaptateurUpdate.lambda$updateDatabase$0(AdaptateurUpdate.java:68)
    at com.bouygtel.commun.summer.socle.coeur.threads.SummerExecutorServiceFactory$3.run(SummerExecutorServiceFactory.java:160)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException: null
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.jdo.JDOHelper$16.run(JDOHelper.java:1965)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.jdo.JDOHelper.invoke(JDOHelper.java:1960)
    at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation(JDOHelper.java:1166)
    ... 25 common frames omitted
Caused by: org.datanucleus.exceptions.NucleusUserException: Error : Could not find API definition for name "JDO". Perhaps you dont have the requisite datanucleus-api-XXX jar in the CLASSPATH?
    at org.datanucleus.api.ApiAdapterFactory.getApiAdapter(ApiAdapterFactory.java:93)
    at org.datanucleus.AbstractNucleusContext.<init>(AbstractNucleusContext.java:118)
    at org.datanucleus.PersistenceNucleusContextImpl.<init>(PersistenceNucleusContextImpl.java:170)
    at org.datanucleus.PersistenceNucleusContextImpl.<init>(PersistenceNucleusContextImpl.java:159)
    at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.<init>(JDOPersistenceManagerFactory.java:436)
    at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.createPersistenceManagerFactory(JDOPersistenceManagerFactory.java:314)
    at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.getPersistenceManagerFactory(JDOPersistenceManagerFactory.java:223)
    ... 33 common frames omitted

But I have this in my pom.xml
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jdo</artifactId>
<version>5.0.3</version>
</dependency>

The weird thing is that this only happens when I use my code through the jar, when I run it from eclipse, the thing works perfectly.
I double checked through "jar tf" and the jar that I run does contain the "datanucleus-api-jdo-5.0.3.jar".
I've searched for conflicts in my dependency hierarchy and there is one dependency that also use an older version of the "datanucleus-api-jdo", but it's omitted for conflict according to eclipse and excluding it does not solve the problem
Not sure if that helps but the run configuration within eclipse is "clean package spring-boot:run".
Any ideas of what is causing this?
If you think any information is missing please ask


text:
Q: Java Copy Constructor ArrayLists I am trying to create a copy constructor considering the object is mutable. My copy constructor is wrong; I can't seem to figure out what I am doing wrong.
Please do NOT tell me to use clone(). How would I complete the copy constructor in this situation? I am new to Java and would really appreciate any help.
public class MyList {

public ArrayList<Cool> people;

/**
 * "people" variable as a new (empty) ArrayList of Cool objects.
 */
public MyPersonList()
{
    people = new ArrayList<Cool>(0);
}

/**
 * A copy constructor which makes the right kind of copy considering
 * a Cool is mutable.
 */
public MyList(MyList other)
{
    people = new ArrayList<Cool>();

    for(Cool p:people)
    {
        people.add(p);
    }

}

A: Simply: you are iterating over people but you should iterate over other.people variable.
Just a note: ArrayList already provides a constructor to add all items of another collection:
ArrayList(Collection<? extends E> c)

so:
people = new ArrayList<Cool>(other.people);

is enough.

A: public MyList(MyList other)
{
    people = new ArrayList<Cool>();

    for(Cool p:people)
    {
        people.add(p);
    }

}

change it to :
public MyList(MyList other)
{
    people = new ArrayList<Cool>();

    for(Cool p : other.people)
    {
        people.add(p);
    }

}

A: Note: Cloning the lists, isn't the same as cloning the elements in the list.
None of these approaches work the way you want them to:
//1
people = new ArrayList<Cool>(other.people);

//2
people = new ArrayList<Cool>();
for(Cool p : other.people) {
    people.add(p);
}

The approaches above will fill people such that it contains the same elements as other.people.
However, you don't want it to contain the same elements. You want to fill it with clones of the elements in other.people.
The best approach would be something like this:
people = new ArrayList<Cool>(other.people.size());
for(Cool p : other.people) {
    people.add((Cool)p.clone());
}

Make sure Cool implements Cloneable. Override clone() if necessary.


text:
Q: Pelican blog - Verify ownership Bing webmaster To verify ownership of my blog, the bing webmaster requires one of the following three approaches:

*

*Upload the file "BingSiteAuth.xml" to my website as https://mywebsite/BingSiteAuth.xml

*Copy and paste a meta tag in my default webpage e.g. <meta name="msvalidate.01" content="...." />
An example given:
<html>
    <head>
        <meta name="msvalidate.01" content="...." />
        <title>Your SEO optimized title</title>
    </head>
    <body>
        page contents
    </body>
</html>

*Add CNAME record to DNS

Question:
What would be the easiest approach and what would be the steps for a beginner ?
Note I am using the AboutWilson template in Pelican. Thanks

A: Sounds like the copy and paste meta tag would be the easiest, i have done it on my blog. All you need to do is go to your theme template directory and paste the required meta tag line in the base.html file in the head section.


text:
Q: Ansible include_task based on condition (directory empty or certifcate is expired or 30 days remaining in expiry) I am using Ansible letsencrypt module to generate SSL certificates. The playbook is working fine, the certificate is generated and applied.
Now I want that this task is only played when certain conditions are matched, otherwise skipped this task.
Condition:

*

*If /etc/letsencrypt/certs directory is emtpy (when running first time)

OR

*

*If 30 days are remaining in certificate  expiry date

OR

*

*If certificate is expired

Could anyone please confirm the commands to achieve this.
Example:
- include_tasks: tasks/letsencrypt-issue-jetty.yml
  when: >

A: You may have a look into Ansible Conditionals.
- include_tasks: tasks/letsencrypt-issue-jetty.yml
  when: certs_in_dir == 0 or days_remaining <= 30 or certificate_expired

So in general your provided approach will work already.
For creating and and loading the variables with values, you may have a look into

*

*set_fact – Set host variable(s) and fact(s)

*Using Variables - Registering variables
as well into

*

*What's the difference between include_tasks and import_tasks?

A: I used the below steps to the achieve the target. It is working but let me know if anything can be corrected.
    - name: 'Check /etc/letsencrypt/certs is empty or not'
      command: ls /etc/letsencrypt/certs
      ignore_errors: True
      register: FoundFiles

    - name: "Get a cert from an https port"
      get_certificate:
        host: "{{ inventory_hostname }}"
        port: 443
      delegate_to: "{{ inventory_hostname }}"
      run_once: true
      ignore_errors: True
      register: cert

    - name: "Cert expiry status"
      vars:
       expire_status: "{{ (( cert.expired )) }}"
      shell: echo "{{ expire_status }}"
      ignore_errors: True
      register: Expiry_Result

    - name: "How many days until cert expires"
      vars:
        expire_days: "{{ (( cert.not_after | to_datetime('%Y%m%d%H%M%SZ')) - (ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%SZ')) ).days }}"
      shell: echo "{{ expire_days }}"
      ignore_errors: True
      register: Num_of_ExpiryDays

   - include_tasks: tasks/letsencrypt-issue-jetty.yml
when: FoundFiles.stdout == "" or Expiry_Result.stdout == 'True' or Num_of_ExpiryDays.stdout | int <= 14


text:
Q: Handling photo response from Microsoft Graph I can't figure out what actually is returned by this call and how I can display it in HTML as an img tag. When I use the same URI using the online Microsoft Graph Explorer test environment I get the image as intended.
var requestUri =
    "https://graph.microsoft.com/v1.0/barfoo.onmicrosoft.com/users/xxxxx-xxxxxx-xxxxx/photo/$value";

var request =
    new HttpRequestMessage(HttpMethod.Get, requestUri);

var accessToken =
    await _authenticationHelper.GetAccessTokenAsync();

request.Headers.Authorization =
    new AuthenticationHeaderValue("Bearer", accessToken);

var response = await client.SendAsync(request);

A: HttpClient can give you the response as a Stream.
In ASP.NET Core, I've done this with:
[HttpGet]
public async Task<IActionResult> ProfilePhoto()
{
    //removed all the code which you already have
    HttpResponseMessage res = await client.SendAsync(request);

    return File(await res.Content.ReadAsStreamAsync(), "image/jpeg");
}

"Classic" ASP.NET MVC should be pretty identical, you would replace IActionResult with ActionResult at least.
You can then link this to an image tag like:
<img src="/Home/ProfilePhoto"/>

A: Once you have the users photo response you should be able to render the image along the following lines:
    src="data:image/jpeg;base64,{{ user.profilePic }}"


text:
Q: Embed python in to iOS (iphone) app written in Objective-C/Swift/C/C++ (whatever language i can compile in Xcode and bridge to iOS) I Do Not Intend To Put The Project On The App Store

*

*Short Question -  is there any up-to-date PyObjC tutorial for embedding python scripts into an iOS app written in Objective-C and/or swift? If not if there any up-to-date method for achieving the same goal?

*Background: I want to run a bunch python scripts in an objective-c ios app. I have tried a couple of things:

*

*I have tried using the python.framework, but i get a "could not build Python module" error. After googling for help, I realized that python.framework does not work on iOS - Run python scripts in iOS app

*PyObjC - For the sake of experimenting, I managed to get the generated *.plugin working on OS X. I followed this tutorial - https://pythonhosted.org/pyobjc/tutorials/embedded.html
Using the same method on iOS, it fails to compile

A: If anyone is ever interested in calling python from swift, here is some helpful material I found(used) -

*

*use the python framework - https://developer.apple.com/library/ios/technotes/tn2328/_index.html

*PyObjC (a little more challenging) -

*cobbal - https://github.com/cobbal/python-for-iphone

*python docs (you would need to make C-Swift bridhe)

Most of it is for Objective-c, but if you need to use swift you can easily just create an ObjC-Swift bridge (super-super easy) - Lookup the apple docs
I managed to get the first two methods working on an OS X app, but I got some architecture errors for iOS(not important). I've pushed the project aside for now, I have a ton I need to get done.
Hope this will be helpful for anyone interested :-)


text:
Q: Update where select, guarantee atomicity I have a T-SQL query like this:
UPDATE
    [MyTable]
SET
    [MyField] = @myValue
WHERE
    [Id] =
    (
        SELECT TOP(1)
            [Id]
        FROM
            [MyTable]
        WHERE
            [MyField] IS NULL
            -- AND other conditions on [MyTable]
        ORDER BY
            [Id] ASC
    )

It seems that this query is not atomic (the select of 2 concurrent executions can return the same Id twice).
Edit:
If I execute this query, the Id returned by the SELECT will not be available for the next execution (because [MyField] will not be NULL anymore). However, if I execute this query twice at the same time, both executions could return the same Id (and the second UPDATE would overwrite the first one).
I've read that one solution to avoid that is to use a SERIALIZABLE isolation level. Is that the best / fastest / most simple way ?

A: As I can see, UPDLOCK would be enough (test code confirms that)

A: Calculate the max ID first then use it in a cross join for the the update.
SQL DEMO
WITH cte as (
    SELECT TOP 1 ID
    FROM [MyTable]
    WHERE MYFIELD IS NULL
    ORDER BY ID
)
UPDATE t
SET [ID] = cte.[ID]
FROM [MyTable] t
CROSS JOIN  cte;

OUTPUT

A: This would result the top 1 value but if its the same you have the potential to return more than one value.
Try using DISTINCT
I understand that top(1) should only return 1 row but the question states its returning more than one row. So i thought it might be because the value is the same. So you could possibly use something like this
    SELECT DISTINCT TOP 1 name FROM [Class];

Its either that or where clause to narrow results


text:
Q: Maximum size of a ruleset – Firestore what should someone do if the maximum size of a Firestore ruleset was reached (64kb)? I don't have complex rules but rather lots of variables to check. Mostly I check for type and value. Guess they added up quickly :( What is the preferred course of action here? Should someone not be thorough and not check for variables types, for example, in order to not exceed the limit? I was trying to be as thorough as possible and then I ran into the size limitation. Is there any way to circumvent the limit or an advice on what to check for and what not?

A: There are a few things you can do to reduce the total size, depending on what your rules actually do:

*

*Use functions to share redundant code across rules

*Use recursive wildcards to apply common rules to documents in nested subcollections

*Shorten the names of any wildcards

*Write code to compact rules before uploading by eliminating unnecessary leading whitespace

It's not advisable to eliminate rules entirely.  If you do need to do that for whatever reason, you will need to make a judgement call.  We can't tell you which rules are more important than others for your particular use cases.
I also suggest filing a feature request with Firebase support to indicate what you need from the system.


text:
Q: Conditionally construct default-constructible classes of a parameter pack I have a template class Container with a template constructor defined as follows:
template<class... Objects>
class Container
{
public:
    template<class... Objs>
    Container(Objs*... objs)
    {
        // initialize all pointers of m_objs to nullptr
        objs_init<Objects...>();

        // initialize the pointers of m_objs corresponding to parameters pack objs...
        objs_init<Objs...>(objs...);
    }

private:
    template<class Obj, class O1, class ...On>
    void objs_init()
    {
        objs_init<Obj>();
        objs_init<O1, On...>();
    }
    template<class Obj, class O1, class ...On>
    void objs_init(Obj* obj, O1* o1, On*... on)
    {
        objs_init<Obj>(obj);
        objs_init<O1, On...>(o1, on...);
    }
    template<class Obj>
    void objs_init(Obj* obj = nullptr)
    {
        std::get<Obj*>(m_objs) = obj;
    }

    std::tuple<Objects*...>     m_objs;
};

and some classes A, B, C, ... defined as follows:
class A { public: A(bool) {} };
class B { /*trivial default ctor*/ };
class C { public: C(int) {} };

If I create a Container<A,B,C> object this way:
    Container<A,B,C> cnt(new A(true), new C(1));

assuming all classes specified in template parameters are different, the Container<> template constructor works as expected, i.e.:

*

*all pointers of the m_objs tuple are first set to nullptr, then

*the 1st (A*) and 3rd (C*) pointers of m_objs are set to the values returned by new A(true) and new C(1) respectively.

Now, I would like the Container<> constructor to default-construct every uninitialized pointers of m_objs. But I don't know how to achieve this.
I tried adding the following template member functions to Container<>:
    template<class Obj, class O1, class ...On>
    void objs_ctor()
    {
        objs_ctor<Obj>();
        objs_ctor<O1, On...>();
    }
    template<class Obj>
    void objs_ctor()
    {
        Obj*& obj = std::get<Obj*>(m_objs);
        if (obj == nullptr)
            obj = new Obj;
    }

and a call to objs_ctor<> in Container<> constructor:
        // default-construct unitialized pointers of `m_objs`
        objs_ctor<Objects...>();

however, this obviously does not work because the way I implemented objs_ctor<> requires that a default constructor exists for every classes of the parameter pack (which I don't want to); so I get the following compiler error:
error C2512: 'A' : no appropriate default constructor available

In order for this to work,I also need to check if the object I try to automatically create is default-constructible. I think this could be achieved using std::is_default_constructible<> but I don't know how to use it properly.
Thanks for help.

A: Hypothesis.
Add a call to objs_ctors<Objects...>(); in constructor
  template<class... Objs>
     Container(Objs*... objs)
      {
        objs_init<Objects...>();
        objs_init<Objs...>(objs...);
        objs_ctors<Objects...>();
      }

and define objs_ctor<>() and objs_ctors<>() in this way
  template <typename Obj>
     typename std::enable_if<true == std::is_default_constructible<Obj>::value, void>::type objs_ctor ()
      {
        Obj * & obj = std::get<Obj*>(m_objs);

        if ( obj == nullptr)
           obj = new Obj;
      }

  template <typename Obj>
     typename std::enable_if<false == std::is_default_constructible<Obj>::value, void>::type objs_ctor ()
      { }

  template <typename Obj, typename O1, typename ... On>
     void objs_ctors()
      {
        objs_ctor<Obj>();
        objs_ctors<O1, On...>();
      }

  template <typename Obj>
     void objs_ctors ()
      {
        objs_ctor<Obj>();
      }

Attention, please: I suppose your example
    Obj*& obj = std::get<Obj*>(m_objs);
    if (obj != nullptr)
        obj = new Obj;

was wrong.
I suppose your intention was modify (allocate) obj when obj is a nullptr, so
    Obj*& obj = std::get<Obj*>(m_objs);
    if (obj == nullptr)
        obj = new Obj;

p.s.: sorry for my bad English.


text:
Q: iPad loading local HTML into web view with images and javascript Edit:
So the answer was in this post: Loading javascript into a UIWebView from resources
You'll find everything you need to know for loading an HTML5 app with directories there, just make sure you drop files on your Xcode project clicking the radio button that reads "Create folder references for any added folders". Then just use the code on that links I've added up there.
Thanks to Sergio for the help.

I've been through StackOverflow several times already and none of the code I find there can display the images of my html5 App. The hard part seems to be loading files from different subdirectories. I do not want to throw everything in the root and then use the groups in Xcode because I would have to re-factor a lot of the HTML5 code.
I'd like to build this in as a light container, not have to use PhoneGap. Besides PhoneGap comes with a bigger bagage of bugs (I tested our app and it crashed on the iPad and worked on the iPhone). It's hard enough to deal with the HTML5 side of things and Cocoa Touch.
So here's how I load the HTML page:
[webView loadRequest:[NSURLRequest requestWithURL:
       [NSURL fileURLWithPath:[[NSBundle mainBundle]
       pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

I have found some solution that it's getting me closer to "Create folder references for any added folders" when adding the files to the resources folder, I can now see some of the images being loaded. The JS doesn't seem to be working properly. I have tested this app loading it from a URL running on a local server and it does work in that case.
So CSS is obviously working, images too but JS seems to be an issue.
Hopefully I'll find the answer soon.

Old
(this is when I was including the folders the wrong way)
So as you guys don't have to be wondering what am I seeing ( it looks to me like js and images are not loading and I do have subdirectories on the HTML5 app ):

Interesting posts which are related to this:
Loading javascript into a UIWebView from resources
Link to resources inside WebView - iPhone

A: Indeed, you can load a local HTML in a UIWebView by means of:
– loadHTMLString:baseURL:

The only thing you should be aware of is how to specify the baseURL so that it goes to your local resources directory. So, if you add in your HTML:
<img src="localImage.png" />
<link rel="stylesheet" type="text/css" href="theme.css" />
<script type="text/javascript" src="filename.js"></script>

this will be found among your project resources.
It definitely works. Possibly there is some "issue" with your HTML and javascript source (like, e.g., using subdirectories or absolute URLs).
EDIT:
If you need to organize your resources (images and scripts) in directories inside of the Resources directory of your app, see this S.O. topic.
To get the path to your Resources directory, use:
 NSString* filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];

An alternative could be hosting all of your file in the Documents directory of your app (which is reserved for user content). In this case, I suppose you could download an archive of your app and install it in the document directory.


text:
Q: Edited PostLowQualityAuto still get a downvote Per this post from Jeff, the Very Low Quality flag:

*

*The VLQ flag now carries a downvote from community. It is like "spam flag lite", meaning, no reputation penalty but like spam, it
  incurs a downvote from the community user.

*If a post is edited, any pending VLQ flags are now cleared (without harm) from the post. It is unclear that a post is still VLQ if it has
  been edited since it was flagged.

I am not sure if #2 is applying to PostLowQualityAuto flags.  I was able to reproduce this by

*

*Clicking on the link in the flag listing.

*Editing the post (in my case it was an answer, see https://drupal.stackexchange.com/a/78282).

*Dismissing the flag as helpful

When I dismissed the flag, the score remained at 0, but when I refreshed the page, it went down to -1.


text:
Q: Why is using IComparable slower than strings in comparisons? I'm using Mergesort to order 50.000.000 Strings and there are two different results depending on what parameter-type I use.
Using the Interface IComparable:

*

*20226 ms

Using Strings directly:

*

*10912 ms

Mergesort Code:
public class Mergesort2
{
    static private StringComparer comparer1 = StringComparer.Ordinal;
    public static void merge(IComparable[] a, IComparable[] aux, int lo, int mid, int hi)
    {

        for (int k = lo; k <= hi; k++)
        {
            aux[k] = a[k];
        }

        // merge back to a[]
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; k++)
        {
            if (i > mid)
            {
                a[k] = aux[j++];
            }
            else if (j > hi)
            {
                a[k] = aux[i++];
            }
            else if (less(aux[j], aux[i]))
            {
                a[k] = aux[j++];
            }
            else
            {
                a[k] = aux[i++];
            }
        }

    }

    private static void sort(IComparable[] a, IComparable[] aux, int lo, int hi)
    {
        if (hi <= lo)
        {
            return;
        }
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid + 1, hi);
        merge(a, aux, lo, mid, hi);
    }

    public static void sort(IComparable[] a)
    {
        IComparable[] aux = new IComparable[a.Length];
        sort(a, aux, 0, a.Length - 1);
    }

    ///*********************************************************************
    ///  Helper sorting functions
    /// **********************************************************************

    // is v < w ?
    private static bool less(IComparable v, IComparable w)
    {
        return (comparer1.Compare(v, w) < 0);
    }

    // exchange a[i] and a[j]
    private static void exch(Object[] a, int i, int j)
    {
        Object swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    /// <summary>
    ///*********************************************************************
    ///  Index mergesort
    /// **********************************************************************
    /// </summary>
    // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
    private static void merge(IComparable[] a, int[] index, int[] aux, int lo, int mid, int hi)
    {

        // copy to aux[]
        for (int k = lo; k <= hi; k++)
        {
            aux[k] = index[k];
        }

        // merge back to a[]
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; k++)
        {
            if (i > mid)
            {
                index[k] = aux[j++];
            }
            else if (j > hi)
            {
                index[k] = aux[i++];
            }
            else if (less(a[aux[j]], a[aux[i]]))
            {
                index[k] = aux[j++];
            }
            else
            {
                index[k] = aux[i++];
            }
        }
    }

    // return a permutation that gives the elements in a[] in ascending order
    // do not change the original array a[]
    public static int[] indexSort(IComparable[] a)
    {
        int N = a.Length;
        int[] index = new int[N];
        for (int i = 0; i < N; i++)
        {
            index[i] = i;
        }

        int[] aux = new int[N];
        sort(a, index, aux, 0, N - 1);
        return index;
    }

    // mergesort a[lo..hi] using auxiliary array aux[lo..hi]
    private static void sort(IComparable[] a, int[] index, int[] aux, int lo, int hi)
    {
        if (hi <= lo)
        {
            return;
        }
        int mid = lo + (hi - lo) / 2;
        sort(a, index, aux, lo, mid);
        sort(a, index, aux, mid + 1, hi);
        merge(a, index, aux, lo, mid, hi);
    }
}

This code produces the slow runtimes.
If I would change all IComparable types to String the performance would increase. Why are there so huge performance differences using the different types?

A: To answer the question about performance: your test used strings that were small enough that the additional type checks required to use the non-generic IComparable interface, along with the use of interface-dispatch instead of virtual-dispatch (a low-level detail of virtual machines like .NET and the Java VM) were more expensive than the string comparisons. If you used strings with long common prefixes, the comparison operation would become the dominant performance cost and the gap between the two forms would close. Edit: running the test on a Release build of the code may close the gap as well (did not run the test locally, and I'm not sure what build the OP used for testing).
Now more importantly to the experiment as a whole, ignoring all other issues with the code, I'll point out specifically the common practice for supporting "comparable" items in a generic manner in .NET.

*

*Do not restrict the generic type T (might or might not be string, if fact it might or might not implement IComparable).

*Use an IComparer<T> to compare elements. If the user passes a null for the comparer argument to one of the public methods, default to Comparer<T>.Default.

Here is the updated code:
public class Mergesort2
{
    public static void merge<T>(T[] a, T[] aux, int lo, int mid, int hi, IComparer<T> comparer)
    {
        comparer = comparer ?? Comparer<T>.Default;

        for (int k = lo; k <= hi; k++)
        {
            aux[k] = a[k];
        }

        // merge back to a[]
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; k++)
        {
            if (i > mid)
            {
                a[k] = aux[j++];
            }
            else if (j > hi)
            {
                a[k] = aux[i++];
            }
            else if (less(aux[j], aux[i], comparer))
            {
                a[k] = aux[j++];
            }
            else
            {
                a[k] = aux[i++];
            }
        }

    }

    private static void sort<T>(T[] a, T[] aux, int lo, int hi, IComparer<T> comparer)
    {
        if (hi <= lo)
        {
            return;
        }
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid, comparer);
        sort(a, aux, mid + 1, hi, comparer);
        merge(a, aux, lo, mid, hi, comparer);
    }

    public static void sort<T>(T[] a, IComparer<T> comparer)
    {
        comparer = comparer ?? Comparer<T>.Default;
        T[] aux = new T[a.Length];
        sort(a, aux, 0, a.Length - 1, comparer);
    }

    ///*********************************************************************
    ///  Helper sorting functions
    /// **********************************************************************

    // is v < w ?
    private static bool less<T>(T v, T w, IComparer<T> comparer)
    {
        return (comparer.Compare(v, w) < 0);
    }

    // exchange a[i] and a[j]
    private static void exch<T>(T[] a, int i, int j)
    {
        T swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    /// <summary>
    ///*********************************************************************
    ///  Index mergesort
    /// **********************************************************************
    /// </summary>
    // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
    private static void merge<T>(T[] a, int[] index, int[] aux, int lo, int mid, int hi, IComparer<T> comparer)
    {

        // copy to aux[]
        for (int k = lo; k <= hi; k++)
        {
            aux[k] = index[k];
        }

        // merge back to a[]
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; k++)
        {
            if (i > mid)
            {
                index[k] = aux[j++];
            }
            else if (j > hi)
            {
                index[k] = aux[i++];
            }
            else if (less(a[aux[j]], a[aux[i]], comparer))
            {
                index[k] = aux[j++];
            }
            else
            {
                index[k] = aux[i++];
            }
        }
    }

    // return a permutation that gives the elements in a[] in ascending order
    // do not change the original array a[]
    public static int[] indexSort<T>(T[] a, IComparer<T> comparer)
    {
        comparer = comparer ?? Comparer<T>.Default;
        int N = a.Length;
        int[] index = new int[N];
        for (int i = 0; i < N; i++)
        {
            index[i] = i;
        }

        int[] aux = new int[N];
        sort(a, index, aux, 0, N - 1, comparer);
        return index;
    }

    // mergesort a[lo..hi] using auxiliary array aux[lo..hi]
    private static void sort<T>(T[] a, int[] index, int[] aux, int lo, int hi, IComparer<T> comparer)
    {
        if (hi <= lo)
        {
            return;
        }
        int mid = lo + (hi - lo) / 2;
        sort(a, index, aux, lo, mid, comparer);
        sort(a, index, aux, mid + 1, hi, comparer);
        merge(a, index, aux, lo, mid, hi, comparer);
    }
}

A: IMHO, i would have to say simply this: the size of the object itself... so every time you declare a ICompare, which contains a bunch of extra properties, methods, etc, it takes more time, than if you declare the lesser String...


text:
Q: adjust Bitmap width and height in MapField in BlackBerry I am drawing circles around a location point in the MapField like in the code given below:
 public void drawCircleMap(int [] radius)
{
   int i = 0;
    Graphics graphics = null;
    int x2,y2;
    bmparr = new Bitmap[radius.length];
    for(int j=0;j<radius.length;j++)
    {
                XYPoint fieldOut = new XYPoint();
                convertWorldToField(mPoints[1], fieldOut);
                x2 = fieldOut.x;
                y2 = fieldOut.y;
                bmparr[i] = new Bitmap(getWidth(), getHeight());
                bmparr[i].createAlpha(Bitmap.ALPHA_BITDEPTH_8BPP);
                graphics = Graphics.create( bmparr[i]);
                graphics.setColor(Color.BLUE);
                graphics.drawEllipse(x2, y2, x2+radius[j], y2, x2,y2+radius[j], 0, 360);
                graphics.fillEllipse(x2, y2, x2+radius[j], y2, x2,y2+radius[j], 0, 360);
                i++;
    }

}
protected void paint(Graphics graphics) {
    super.paint(graphics);

    for(int i =0 ;i < bmparr.length;i++)
    {
        graphics.setGlobalAlpha(100);
        graphics.drawBitmap(0, 0,  bmparr[i].getWidth(), bmparr[i].getHeight(), bmparr[i], 0, 0);
    }

}
I want to draw 4 circles, now as i draw more number of circles, the map seems to fade out, Can someone please tell me how i could solve this issue?

A: I have solved this problem by drawing a transparent background for every bitmap:
bmparr = new Bitmap[radius.length];
for(int j=0;j<radius.length;j++)
{
  XYPoint fieldOut = new XYPoint();
  convertWorldToField(mPoints[1], fieldOut);
  x2 = fieldOut.x;
  y2 = fieldOut.y;
  bmparr[i] = new Bitmap(getWidth(), getHeight());
  bmparr[i].createAlpha(Bitmap.ALPHA_BITDEPTH_8BPP);
  int[] argb = new int[getWidth() * getHeight()];
  bmparr[i].getARGB(argb, 0, getWidth(), 0, 0, getWidth(), getHeight());
  for(int k = 0; k < argb.length; k++)
  {
      argb[k] = 0x00000000;
  }
  bmparr[i].setARGB(argb, 0, getWidth(), 0, 0, getWidth(), getHeight());
  graphics = Graphics.create( bmparr[i]);
  graphics.setColor(Color.BLUE);
  graphics.drawEllipse(x2, y2, x2+radius[j], y2, x2,y2+radius[j], 0, 360);
  graphics.fillEllipse(x2, y2, x2+radius[j], y2, x2,y2+radius[j], 0, 360);
  i++;
}

A: I believe your problem is with alpha blending.  You are drawing each image, one on top of the other, with approximately 50% alpha.  So, the first radius "covers" half of the existing pixel intensity.  Then the next radius covers half of the remaining intensity, or 75% of the original intensity.  And so on... each time you draw an image, it is covering up more and more of the original intensity.
If you want all of your circles to have a common intensity, you will need to re-think your approach.  For example, consider drawing all of your circles in a single bitmap before drawing that on top of the map.  Or consider having each larger circle leave a 100% transparent "hole" where the smaller circles will be.


text:
Q: tensorflow js how to load weights from another model I have two models m1 and m2,
I would like to update the weights of model m1 to be like m2,
In python with PyTorch it could be done with this line of code:
m1.load_state_dict(m2.state_dict())
but I couldn't find any information on the internet about it.
The only thing I found according to this documentation:
https://www.tensorflow.org/js/guide/save_load
is to save m2 via local-storage for example and then to load it completely to m1, but it doesn't make sense to me to download and save it again just so I could update the weights.

A:
Loading the weights of another model.

As indicated in the question, this can be done by saving the first model and then loading it as another model.

it doesn't make sense to me to download and save it again just so I could update the weights.

It does not make sense to completely update a model 2 by a model 1 weights if both are not identical meaning they have the same topology. There is no method to clone a model directly and assign it to another variable. To do it, the model needs to be loaded as another model or its weights copied and assigned to another model with the same topology.
model.getWeight and model.setWeights can be used
model2.setWeights(model1.getWeights());

If the model 2 is to be updated partially , ie update the weights of some layers, it has been discussed in these answers here and there

A: So after reading the documentation better,
I found this:
m1.setWeights(m2.getWeights());

I also tried to fit one of them to see that it won't learn the other and it had no problem.
Note that they both should have the same structure, full example:
const model = tf.sequential();
model.add(tf.layers.dense({ units: 4, inputShape: [8] }));
model.add(tf.layers.dense({ units: 4 }));
model.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });

const model2 = tf.sequential();
model2.add(tf.layers.dense({ units: 4, inputShape: [8] }));
model2.add(tf.layers.dense({ units: 4 }));
model2.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });

model2.setWeights(model.getWeights());

console.log(model.getWeights()[0].dataSync());
console.log(model2.getWeights()[0].dataSync());


text:
Q: Javascript to run a function when input focus What is the code to run a function, say called "myfunction" when a user clicks within an input box (focus).
I have seen examples in jquery but I cant see how to do it with straight javascript.

A: use the onfocus attribute
<input type="text" onfocus="someFunc()">

<script>
  function someFunc(){

  }
</script>

A: var addEvent = (function(){
  /// addEventListener works for all modern browsers
  if ( window.addEventListener ) {
    /// I'm returning a closure after the choice on which method to use
    /// has been made, so as not to waste time doing it for each event added.
    return function(elm, eventName, listener, useCapture){
      return elm.addEventListener(eventName,listener,useCapture||false);
    };
  }
  /// attachEvent works for Internet Explorer
  else if ( window.attachEvent ) {
    return function(elm, eventName, listener){
      /// IE expects the eventName to be onclick, onfocus, onkeydown (and so on)
      /// rather than just click, focus, keydown as the other browsers do.
      return elm.attachEvent('on'+eventName,listener);
    };
  }
})();

Using the above cross browser function you can then do the following (once the dom is fully loaded):
addEvent(document.getElementById('your_input'),'focus',function(e){
  var input = e.target || e.srcElement;
  alert('this input has gained focus!');
});

A: document.getElementById("elementId").addEventListener("focus",function(e){
 //Do Something here
});


text:
Q: Wordpress: force wp_tag_cloud to display empty categories? I'm using wp_tag_cloud() to display the categories in my custom taxonomy:
$args = array
(
    'format'                    => 'list',
    'orderby'                   => 'name',
    'order'                     => 'ASC',
    'topic_count_text_callback' => default_topic_count_text,
    'link'                      => 'view',
    'taxonomy'                  => 'my_tax',
    'echo'                      => true
);

wp_tag_cloud( $args );

The problem is that only categories with posts are displayed, so instead of seeing 40+ categories I only see 3.
Is there a way to force wp_tag_cloud to display all categories?

A: Some spelunking in wp_tag_cloud() (line 526 in wp-includes/category-template.php) shows that it calls get_terms() (line 1114 in wp-includes/taxonomy.php) and passes through the $args array that was passed to wp_tag_cloud(). get_terms() has a param called hide_empty that defaults to true.
This is untested, but I think if you simply add "hide_empty" => false" to your $args you'll get what you want. There may be other args to get_terms() that are of interest to you.


text:
Q: How to display html content with image inside json file? Reactjs The external image is working.
I want to display HTML content with  image from my src folder.
The HTML text part is working.
JSON
[
{
    "title": "Sample Blog",
    "image": "https://source.unsplash.com/12mi25fTAmM/538x302",
    "content" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque quis sem ut diam lacinia placerat. Vestibulum pharetra velit sit amet bibendum faucibus. Phasellus sit amet scelerisque diam. Suspendisse potenti. Nulla quis odio quis arcu venenatis condimentum. Proin lectus est, suscipit a lorem non, blandit vestibulum lacus. Sed eu volutpat eros.  Aenean ullamcorper orci vulputate lectus maximus blandit. Fusce leo mauris, tempus non cursus id, scelerisque aliquet ante. Fusce venenatis, orci nec sollicitudin consectetur, sapien velit ultrices purus, eget suscipit quam mauris ut ipsum. Praesent pulvinar nunc id scelerisque vehicula. Nunc vitae leo eleifend, finibus metus non, varius libero.
   Fusce nisl leo, faucibus quis massa sed, ornare cursus augue. Donec at lorem tortor. Phasellus porttitor nisi sit amet dui pellentesque interdum. Vestibulum tempor velit sit amet viverra ornare. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce odio ex, mattis id libero non, posuere ullamcorper mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam venenatis molestie consectetur. Etiam luctus eu diam et imperdiet. Vestibulum imperdiet elementum nibh. Sed quis dui et orci facilisis fermentum. Nam laoreet molestie dui, ac iaculis nisl convallis non. Aenean ultricies hendrerit sem nec tempor. Donec fringilla fermentum lorem, at pharetra odio pretium vel. Donec eget nisl ullamcorper, finibus nibh ut, ornare arcu."
},
{
    "title": "Sample Blog 2",
    "content": "Fusce odio ex, mattis id libero non,
   posuere ullamcorper mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam venenatis molestie consectetur. Etiam luctus eu diam et imperdiet. Vestibulum imperdiet elementum nibh. Sed quis dui et orci facilisis fermentum. Nam laoreet molestie dui, ac iaculis nisl convallis non. Aenean ultricies hendrerit sem nec tempor. Donec fringilla fermentum lorem, at pharetra odio pretium vel. Donec eget nisl ullamcorper, finibus nibh ut, ornare arcu.",
    "image": "https://source.unsplash.com/WLUHO9A_xik/538x302"
}
]

JS
{data.map(({title, content, image}, index) => (

          {image ?  : ''}

{ title }

            <ShowMoreText
                lines={3}
                more='[view more]'
                less='[view less]'
                anchorClass='view-more'
                onClick={this.executeOnClick}
                expanded={false}
              >

                  <FacebookProvider appId="639804143068124">
                    <Comments href={window.location.href + title} data-numposts="1" width="500" />
                  </FacebookProvider>

            </ShowMoreText>

            <FacebookProvider appId="639804143068124">
              <Like href={window.location.href + title} colorScheme="light" showFaces share />
            </FacebookProvider>

    ))}

How to display html content with image inside json file? Reactjs, JSON

A: Short: You need to use different string delimiters.
In your JSON code you use " to delimit the keys and values.
You are trying to have that image source as a string within JSON,
thus you need to:

*

*either escape the delimiters: \"https://localhost:3000\"

*or use different delimiters like 'https://localhost:3000'


text:
Q: Db2 - how to assign value to a variable with EXECUTE statement in db2 I'm tring to execute query in a db2 procedure:
CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30))
LANGUAGE SQL
BEGIN
DECLARE statmnt2 VARCHAR(1000);
DECLARE VAR_COD_TIPO_ARQU CHAR(1);
DECLARE stmt1 STATEMENT;

SET statmnt2 = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY';
PREPARE stmt1 FROM statmnt2;
SET VAR_COD_TIPO_ARQU = EXECUTE (stmt1);
END@

This gives following error:
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0206N  "STMT1" is not valid in the context where it is used.  LINE
NUMBER=33.  SQLSTATE=42703

What's the right way to set VAR_COD_TIPO_ARQU with COD_TIPO_ARQU value dynamically?
ThankYou.

A: The problem is the way you are setting the result from the execution:
EXECUTE stmt1 into VAR_COD_TIPO_ARQU ;

This is the complete code that is executed succefuly
CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30))
LANGUAGE SQL
BEGIN
DECLARE statmnt2 VARCHAR(1000);
DECLARE VAR_COD_TIPO_ARQU CHAR(1);
DECLARE stmt1 STATEMENT;

SET statmnt2 = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY';
PREPARE stmt1 FROM statmnt2;
EXECUTE stmt1 into VAR_COD_TIPO_ARQU ;
END@

A: Hi is it correct solutuion:
SET statmnt = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY';
PREPARE stmt1 FROM statmnt;

BEGIN
    DECLARE c1 CURSOR FOR stmt1;
    OPEN c1;
    FETCH c1 into sttmresult;
    CLOSE c1;
END;

TY.

A: I know it's been a while since this question was asked, but I found that none of the given answers worked.
@AngocA's solution was close but, as @Mani_Swetha pointed out, the EXECUTE statement fails due to the SELECT bit.
After searching and combining solutions around the web, this is what finally worked for me:
CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30))
LANGUAGE SQL
BEGIN
DECLARE statmnt2 VARCHAR(1000);
DECLARE VAR_COD_TIPO_ARQU CHAR(1);
DECLARE stmt1 STATEMENT;

SET statmnt2 = 'set ? = (SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY)';
PREPARE stmt1 FROM statmnt2;
EXECUTE stmt1 into VAR_COD_TIPO_ARQU ;
END@

Note that now the executed command is a set statement with a SELECT inside, rather than a pure SELECT statement. This is what makes the trick.

A: Thanks @Marcos EXECUTE... INTO ... worked.
Additionally, creating the stored proc with OUT parameter will let you access the value set by EXECUTE... INTO ... outside the stored proc.
CREATE OR REPLACE PROCEDURE ISH.SAMPLEPROC (OUT o_result VARCHAR(5))
specific proc_user_data_retrieval
dynamic result sets 1
reads sql data
language sql
BEGIN
DECLARE stmt varchar(5000) default null;
DECLARE VAR_X VARCHAR(5);
DECLARE stmt_final STATEMENT;
SET stmt = 'SET (?) = ('||'SELECT JOB_ROLE FROM ISH.USER_DATA LIMIT 1'||')';
PREPARE stmt_final FROM stmt;
EXECUTE stmt_final INTO VAR_X;
SET o_result = VAR_X;
END

Then call the stored proc using CALL ISH.SAMPLEPROC(?);


text:
Q: Can I make an array of functions? Can I make an array of functions and execute the functions with a foreach loop?
Like:
// This is the beginning of the php file
global $actions = array();

// This is the function where functions need to be added.
function HeadFunction(){
 foreach($actions as $action)
 $action;
}

This is the function to add the action
function add_action($action){
global $actions;
$actions[] = $action;
}

This is a example function:
function check_Url(){
 if(isset($_GET['gettest'])){
    echo '<script>alert(\'This is a test\');</script>';
 }
}

and then add the function with: add_action(check_Url());

A: Use call_user_func.
global $actions = array();

function add_action($action){
global $actions;
$actions[] = $action;
}

add_action('check_Url');
add_action('function2');

foreach ($actions AS $action) {
    call_user_func($action);
}


text:
Q: How to create a table in email body? I'am using mail message to send email in C# and I want to add a table in the mail body.
I am using a string variable to store html code but its printing the whole string as it is in the mail body.
string EPT;
string PRINTER;
string CID;
string htmlString= "<!DOCTYPE html> Hi All,

 Please find below, status of PDS SPOS Devices

 Device Name 	 Online Status 	 Device Status 	 EPT Status 	 PRINTER Status 	 CID Status
 ";

foreach (RetrieveDeviceData deviceData in SPOSStatusList)
{
    if (deviceData.EPTStatus.Contains("EPT is not returning any error on commands"))
    {
        EPT = "EPT OK";
    }
    else if (!deviceData.EPTStatus.Contains("NA"))
    {
        EPT = "EPT Not OK";
    }
    else
    {
        EPT = "NA";
    }

    if (deviceData.PRINTERStatus.Contains("PRINTER - OK"))
    {
        PRINTER = "PRINTER OK";
    }
    else if (!deviceData.PRINTERStatus.Contains("NA"))
    {
        PRINTER = "PRINTER Not OK";
    }
    else
    {
        PRINTER = "NA";
    }

    if (deviceData.CIDStatus.Contains("CID-OK"))
    {
        CID = "CID OK";
    }
    else if (!deviceData.CIDStatus.Contains("NA"))
    {
        CID = "CID Not OK";
    }
    else
    {
        CID = "NA";
    }

    htmlString = htmlString + "
" + deviceData.DeviceName.ToString() + "	" + deviceData.OnlineStatus.ToString() + "	" + deviceData.DeviceStatus.ToString() + "	" + EPT.ToString() + "	" + PRINTER.ToString() + "	" + CID.ToString() + "
";
}

htmlString = htmlString + "

 Regards
 Presto CTSS ";

MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["mailFrom"].ToString());
mailMessage.To.Add(new MailAddress(ConfigurationManager.AppSettings["mailTo"].ToString()));
mailMessage.Subject = "PDS SPOS Device Status Report - " + DateTime.Now;
mailMessage.IsBodyHtml = true;
mailMessage.Body = htmlString;

SmtpClient client = new SmtpClient();
Attachment attachment = new Attachment(reportPath + "\\SPOSStatusReport.csv");
mailMessage.Attachments.Add(attachment);
client.Host = ConfigurationManager.AppSettings["mailServerIp"].ToString();
try
{
    client.Send(mailMessage);
    writer.WriteLine("Email sent");
}
catch(Exception e)
{
    writer.WriteLine(e.ToString());
}

expected result- mail body with a table data
actual- value of htmlString variable in above code is printed as it is in mail.


text:
Q: How to add weights in fitting? I have a set of data as:
data = {{0, 0.046}, {40, 0.111}, {80, 0.291}, {120, 0.808}, {160, 1.742}, {200, 3.319}, {240, 5.017}, {280, 5.503}, {320, 5.897}}

With Standard deviations as:
sd = {0.003, 0.012, 0.023, 0.056, 0.083, 0.216, 0.526, 0.366, 0.313}

Then I fit the data by taking inverse variances as weights:
data2 = data;
data2[[All, 2]] = Log[data2[[All, 2]]];
nlm2 = NonlinearModelFit[data2, Log[a/(1 + E^(-k (t - t0)))], {{a, 1}, {t0, 50}, {k, 0.1}}, t, Weights -> 1/sd^2];
nlm2["ParameterConfidenceIntervalTable"]

But it returns an error: "NonlinearModelFit::sszero: The step size in the search has become less than the tolerance prescribed by the PrecisionGoal option, but the gradient is larger than the tolerance specified by the AccuracyGoal option. There is a possibility that the method has stalled at a point that is not a local minimum."
How can I fix this?

A: Your estimate of k is bad. With k=1 you get:
data2 = data;
data2[[All, 2]] = Log[data2[[All, 2]]];
nlm2 = NonlinearModelFit[data2, Log[a/(1 + E^(-k (t - t0)))], {{a, 1}, {t0, 50}, {k, 1}}, t, Weights -> 1/sd^2];
nlm2["ParameterConfidenceIntervalTable"]

Plot[nlm2[t], {t, 0, 330}, Epilog -> Point[data2]]


text:
Q: GridLookUpEdit Set Index On a GridLookUpEdit I want to change position with two buttons
I can get Index by
XGridLookUpEdit.Properties.GetIndexByKeyValue(XGridLookUpEdit.EditValue);

but I do not know how to set it
thanks

A: int x = XGridLookUpEdit.Properties.GetIndexByKeyValue(XGridLookUpEdit.EditValue);
XGridLookUpEdit.EditValue =
    XGridLookUpEdit.Properties.View.GetRowCellValue(x + 1, "id");


text:
Q: How do number of partitions and iterations work in Spark Word2Vec? I'm currently training an embedding on a large dataset using Spark Word2Vec, implemented on Python.
In the inputs for the model there are numPartitions and numItertions. Up until now I have been training on 1 partition and 1 iteration. The dataset is 3TB of text data. So this is taking a long time. How should I determine the number of partitions and iterations?
How do number of partitions in PySpark ML work?


text:
Q: Difference between two mixed effects models I have a question about how to tell two different mixed effects models apart.  In the simple case both involve fitting a model with a random group effect and a covariate. I fit the model with lme4 in R.  Here is a visualization of the two different scenarios.

library(ggplot2)
library(lme4)
gen_dat2 <- function(group.m,group.v,int, sl,n){
      x <- vector()
      y <- vector()
      g <- vector()
         for(i in 1:length(group.m)){
         x.t <- rnorm(n,group.m[i],group.v[i])
         y.t <- rnorm(n,group.m[i],group.v[i])+int + sl*x.t
         x <- c(x,x.t)
         y <- c(y,y.t)
         g <- c(g,rep(i,n))
        }
     return(cbind(x,y,g))
}

group.m <- runif(5,1,20)
group.v <- runif(5,1,1.5)

dat2 <- data.frame(gen_dat2(group.m,group.v,1,4,14))
ggplot(dat2,aes(x=x,y=y,colour=as.factor(g),group=g))+geom_point()+stat_smooth(method="lm",se=F)
m2 <- lmer(y~x + (x|g),data=dat2)

Then I can generate and fit the other scenario with similar code:

 gen_dat <- function(group.m,group.v,int, sl,n){
      x <- vector()
      y <- vector()
      g <- vector()
         for(i in 1:length(group.m)){
         x.t <- rnorm(n,0,1)
         y.t <- rnorm(n,group.m[i],group.v[i])+int + sl*x.t
         x <- c(x,x.t)
         y <- c(y,y.t)
         g <- c(g,rep(i,n))
        }
     return(cbind(x,y,g))
}

group.m <- runif(5,1,20)
group.v <- runif(5,1,1.5)

dat1 <- data.frame(gen_dat(group.m,group.v,1,4,14))
ggplot(dat1,aes(x=x,y=y,colour=as.factor(g),group=g))+geom_point()+stat_smooth(method="lm",se=F)
m1 <- lmer(y~x + (x|g),data=dat1)

My central question is how do I tell these two models apart?  Am I incorrectly fitting the first one, and I need an extra term in there to model the relationships between groups and the x variable as well as y?  Both detect substantial between group variation in the intercept and not much in the slope as I would predict.  But I need a way to tell these two apart.  Any thoughts would be helpful.

Edits:
This has been helpful in me restating the question.  So I want to re-ask the question with an example which I hope will make it clear why I want to be able to tell these two models apart. Let's imagine that Y is the average student test score at a school, and X is spending per student in that school.  Our grouping variables are 5 different school districts.
Data in the top figure shows that an increase in spending within a district means that test scores increase.  It also shows that between districts there are differences is scores, but that's clearly because some districts spend more student than others.
Data in the second figure show similarly that within a district student scores increase as spending increases.  It also shows that between districts there are differences in test scores.  However we don't know what is driving those differences, unlike in the first set of data.  This is a pretty common situation I've encountered in building models.  The former is not.
So what I'm asking is what is the appropriate model that captures the following features from the first dataset:

*

*Test scores increase as spending per student does

*There is also variance between districts in student test scores

*Part of that difference between districts is because of the underlying relationship between spending and test scores, which also varies with district.

More generally stated, how do you handle a scenario where you're building a hierarchical model where the grouping variable is correlated with one of your continuous independent variables (e.g. the first scenario).  I feel like the model I've presented get's at points 1. and 2., but not point 3.  So I'm really seeking a way to tease these two scenarios apart.
Normally I might add an extra level of hierarchy if there was another group level explanatory variable.  Continuing our example, maybe in the 2nd dataset there are differences between district because in some districts parents have more time to spend on homework with students.  So we would add that as a group level predictor in a hierarchical model.  But that wouldn't work in the first scenario.

A: You don't need extra terms in the models, less actually. It is plain to see by your plots, but if you look at summary(m2) you will see that the variance for random effect for x is really small, and the variance for the intercept is quite small as well.
Similarly for the m1 model, you can see from the plot that the slopes are all the same, but the intercept varies. You can use an F-test to check the model with only random intercepts versus the model with random slopes and intercepts you specified.
m1 <- lmer(y~x + (x|g),data=dat1)
m1RInt <- lmer(y~x + (1|g),data=dat1)
anova(m1,m1RInt)

Also just looking at the variance estimates of the random intercepts and effects for summary(m1) you would have come to the same conclusion that using random slopes adds nothing to the model.


text:
Q: Error in local repository with Hashes of expected file I have a local repository with ubuntu 16.04 and 18.04, however 18.04 is not working fine, we are using this source.list:
deb [ arch=amd64 trusted=yes ] http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic bionic main restricted universe multiverse
deb [ arch=amd64 trusted=yes ] http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic-updates bionic-updates main restricted universe multiverse
deb [ arch=amd64 trusted=yes ] http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic-backports bionic-backports main restricted universe multiverse
deb [ arch=amd64 trusted=yes ] http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic-security bionic-security main restricted multiverse restricted
deb [ arch=amd64 trusted=yes ] http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic-proposed bionic-proposed main restricted universe multiverse

And the error is the next:
Err:8 http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic-security bionic-security/main amd64 DEP-11 Metadata
  File has unexpected size (3541 != 204). Mirror sync in progress? [IP: 172.22.29.45 80]
  Hashes of expected file:
   - Filesize:204 [weak]
   - SHA256:c52cce5fb5a2a386224fe297d20e47786e11f72e7bcf3c2cf8ec6a54ca724315
   - SHA1:788fc9972a69cf1e84b2be50d7b0e05c3b67f58e [weak]
   - MD5Sum:85a92be526a2f6bed09a79e4b8f3adc3 [weak]
  Release file created at: Mon, 14 May 2018 13:29:23 +0000
Reading package lists... Done
E: Failed to fetch http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic-security/dists/bionic-security/main/dep11/Components-amd64.yml.xz  File has unexpected size (3541 != 204). Mirror sync in progress? [IP: 172.22.29.45 80]
   Hashes of expected file:
    - Filesize:204 [weak]
    - SHA256:c52cce5fb5a2a386224fe297d20e47786e11f72e7bcf3c2cf8ec6a54ca724315
    - SHA1:788fc9972a69cf1e84b2be50d7b0e05c3b67f58e [weak]
    - MD5Sum:85a92be526a2f6bed09a79e4b8f3adc3 [weak]
   Release file created at: Mon, 14 May 2018 13:29:23 +0000
E: Some index files failed to download. They have been ignored, or old ones used instead.

The script to update the repo was executed yesterday and everything was fine.
If I quit "main" from this line the repo work fine:
deb [ arch=amd64 trusted=yes ] http://das-repo.cimex.com.cu/Repositorios/ubuntu/bionic-security bionic-security main restricted multiverse restricted

How I can fix this problem?


text:
Q: Flutter Invalid reference to "this" expression issue in Card This is my widget Card code.
I have Invalid reference to "this" expression issue here "this.tdbucreti = value;"
How can I fix that? thanks for help.
String tdbucreti;
 Widget buildResultCard(BuildContext context , data) {

  return Card(
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
  elevation: 5,
  child: ExpansionCard(

    title: Column(
      children: [
        TextField(
          decoration: InputDecoration(hintText: 'TDB Ücreti'),
          onChanged: (value) {
            this.tdbucreti = value;
          },
        ),

         Row(
          children: [
            Padding(
              padding: EdgeInsets.fromLTRB(5, 0, 5, 1),
              child: Text(data['anlasilantutar'],
                style:  GoogleFonts.montserrat(color: Colors.blueGrey[700], fontSize: 20 , textStyle:
            TextStyle(fontWeight: FontWeight.w400)),
                textAlign: TextAlign.center,
              ),
            ),

          ],
        ),
.
.
.
.

A: the variable is in the class which does not contain buildResultCard, your class's closing parentheses are above the buildResultCard.
} //your class finishes here
Widget buildResultCard(BuildContext context , data) {

  return Card(

wrap buildResultCard with above class's closing parentheses like this:
Widget buildResultCard(BuildContext context , data) {

  return Card(....)
 } //your class finishes here

for this reason your function can't see class's varibales


text:
Q: how compare a str object with None I have meet a problem, when I develop a web use python3+flask, when name has no in put, I am confused, the result is True in print
name = request.args.get('name')
if name is not None:
    print('True')
else:
    print('False')

I refer to python documents, "A is not B" means A and B is not same object.
And I make the following test:
print(name) #None
print(type(name)) #<class "str">
print(type(None)) #<class "NoneType">

I found the answer, but when I use the following format
if name:
    print('True')
else:
    print('False')

it prints True and print(name) I get None
I have to write like the following:
if name != str(None):
    print('True')
else:
    print('False')

I feel it a little uncomfortable when use it like this, how I can compare it in a elegant way.

A: Getting a string "None" as part of a request commonly happens when you return a None value as part of a previous response.
Example:
# given a variable that is passed to a jinja template as None
# instead of as an empty string
name = None

Will result in a link with "None" as a string.
click here

Instead of trying to handle for a string "None" in any given request where you expect a string, you should output the original variable as an empty string:
name = None
...

# convert Nones to empty strings right before sending to jinja
if not name:
    name = ''

A: print(True if "None" not in name else False)

I think that's more elegant way of printing out in your case.


text:
Q: In a replica set, why primary instance has almost same no of connection as of secondary instance in mongodb? I have replica set with 1 primary, 2 secondary and 1 arbiter instance, in which no of connection to Primary and secondary are almost same. Why the connection is high in primary, while it should be only 1 are as much we have no of app server which are pointing to Primary for write operations. Please let us know.

A:
By default, an application directs its read operations to the primary
  member in a replica set. Because write operations are issued to the
  single primary, reading from the primary returns the latest version of
  a document.

But In some circumstances, two nodes in a replica set may transiently believe that they are the primary, but at most, one of them will be able to complete writes with {w: majority} write concern. The node that can complete {w: majority} writes is the current primary, and the other node is a former primary that has not yet recognized its demotion, typically due to a network partition. When this occurs, clients that connect to the former primary may observe stale data despite having requested read preference primary.
For an application that does not require fully up-to-date data, you can improve read throughput or reduce latency by distributing some or all reads to secondary members of the replica set.

So Read preference describes how MongoDB clients route read operations to  the members of a replica set.

In mongoDB have 5 Read Preference Modes.

*

*primaryDefault mode. All operations read from the current replica
set primary.

*primaryPreferred   In most situations, operations read
from the primary but if it is unavailable, operations read from
secondary members.

*secondary All operations read from the
secondary members of the replica set.

*secondaryPreferred In most
situations, operations read from secondary members but if no
secondary members are available, operations read from the primary.

*nearest Operations read from member of the replica set with the
least network latency, irrespective of the member's type.

How to use-
db.collection.find().readPref( { mode: 'nearest', tags: [ {'dc': 'east'} ] } )
More @ MongoDB Docs
You can also Call the setReadPref() method on a Mongo connection object to control how the client will route all queries to members of the replica set.
ex- db.getMongo().setReadPref('primaryPreferred')
More @ MongoDB Docs


text:
Q: Tabular border style \begin{tabular}{|c|c|c|}
Column 1 & Column 2 & column3 \\
\hline
second row & & \\
\hline
\end{tabular}

How do I change the border style? Using | I can draw thin solid vertical lines and \hline draws thin solid horizontal lines. I would like a thick outer border and thin dotted lines of various sizes and colors in the table. In short I would like to achieve similar functionality of attached screenshot of MS word table options in LaTeX. Also the reason for asking this is to put all table borders related answers in one place.
Thanks for your help.

A: There is the hhline package and the arydshln package. You can get colour in the table with the xcolor package.
You might have your reasons to typeset your tables with many different line styles... I'd usually recommend to avoid vertical lines at all and to draw horizontal lines with commands provided by the booktabs package.
In case you are writing something related to science, more or less all textbooks seem to roughly follow similar guidelines. Rarely you will find a vertical line.

A: An alternative solution with tblr environment of tabularray package:
\documentclass{article}

\usepackage{tabularray}
\usepackage{xcolor}

\begin{document}

\begin{tblr}{|[2pt,cyan3]c|[dashed,purple3]c|[dotted]c|[2pt,cyan3]}
\hline[2pt,cyan3]
Column 1   & Column 2 & column3 \\
\hline[purple3,dashed]
Second Row & Alpha    & Beta \\
\hline[dotted]
Third Row  & Gamma    & Delta \\
\hline[2pt,cyan3]
\end{tblr}

\end{document}

A:
Here are a few table layouts, with my favourite one last.
\documentclass{article}
\usepackage{xcolor}
\usepackage{booktabs}
\begin{document}
    \begin{tabular}{p{6cm}p{6cm}}
        \begin{tabular}{|c|c|c|}
        \hline
        Column 1 & Column 2 & Column 3 \\
        \hline
        second row & & \\
        \hline
        third row & & \\
        \hline
        \end{tabular}
        &
        \begin{tabular}{ccc}
        Column 1 & Column 2 & Column 3 \\
        \hline
        second row & & \\
        \hline
        third row & & \\
        \hline
        \end{tabular}
        \\[5em]
        \begin{tabular}{|ccc|}
        \hline
        Column 1 & Column 2 & Column 3 \\
        \hline
        second row & & \\
        third row & & \\
        \hline
        \end{tabular}
        &
        \begin{tabular}{|c|c|c|}
        \hline
        Column 1 & Column 2 & Column 3 \\
        \hline
        second row & & \\
        third row & & \\
        \hline
        \end{tabular}
        \\[5em]
        \begin{tabular}{ccc}
        Column 1 & Column 2 & Column 3 \\
        second row & & \\
        third row & &
        \end{tabular}
        &
        \begin{tabular}{lll}
        \toprule
        Column 1 & Column 2 & Column 3 \\
        \midrule
        second row & & \\
        third row & & \\
        \bottomrule
        \end{tabular}
        \\[5em]
        % Colour for the rulings in tables:
        \makeatletter
           \def\rulecolor#1#{\CT@arc{#1}}
           \def\CT@arc#1#2{%
           \ifdim\baselineskip=\z@\noalign\fi
           {\gdef\CT@arc@{\color#1{#2}}}}
           \let\CT@arc@\relax
          \rulecolor{gray!50}
        \makeatother
        \begin{tabular}{@{}lll@{}}
        \toprule
        Column 1 & Column 2 & Column 3 \\
        \midrule
        second row & & \\
        third row & & \\
        \bottomrule
        \end{tabular}
       &
        \begin{tabular}{@{}lll@{}}
        \toprule
        Column 1 & Column 2 & Column 3 \\
        \cmidrule(r){1-1}\cmidrule(lr){2-2}\cmidrule(l){3-3}
        second row & & \\
        third row & & \\
        \bottomrule
        \end{tabular}
   \end{tabular}
\end{document}

A: \documentclass{article}
\usepackage{array,booktabs,arydshln,xcolor}
\newcommand\VRule[1][\arrayrulewidth]{\vrule width #1}

\begin{document}

\begin{tabular}{!{\VRule[2pt]}c!{\VRule}c!{\color{red}\VRule[3pt]}c!{\VRule}}
Column 1 & Column 2 & column3 \\\specialrule{3pt}{0pt}{0pt}
second row & & \\\hdashline
third row  & & \\\specialrule{4pt}{0pt}{0pt}
\end{tabular}

\end{document}

A: With nicematrix, you have an environment {NiceTabular} constructed upon {tabular} (of array).

*

*You can use the classical tools provided by array for the rules.

*You can use the classical packages which apply to the tabulars of LaTeX (eg: aryshln for dashed rules).

*{NiceTabular} has a built-in command \hdottedline and a letter : for dotted rules (with dots which are true circles).

*In fact, nicematrix creates PGF/Tikz nodes under the cells, columns and rows of the environment, and so, it's possible to use Tikz to draw whatever rule you want (with the styles of Tikz).
However, you need several compilations (because nicematrix uses PGF/Tikz nodes).
\documentclass{article}

\usepackage{nicematrix}
\usepackage{tikz}

\begin{document}

\begin{NiceTabular}{|c:c|}
\hline
A & B \\
\hdottedline
C & D \\
\hline
\end{NiceTabular}

\bigskip
\begin{NiceTabular}{ccc}
A & B & C \\
E & F & G \\
H & I & J
\CodeAfter
\begin{tikzpicture}
\draw [dotted] (1-|1) -- (1-|4) ;
\draw [loosely dashed] (2-|1) -- (2-|4) ;
\draw [dash dot dot] (3-|1) -- (3-|4) ;
\draw [red, thick] (4-|1) -- (4-|4) ;
\draw [dotted] (1-|1) -- (4-|1) ;
\draw [loosely dashed] (1-|2) -- (4-|2) ;
\draw [dash dot dot] (1-|3) -- (4-|3) ;
\draw [red, thick] (1-|4) -- (4-|4) ;
\end{tikzpicture}
\end{NiceTabular}

\end{document}

A: You can use all the flexibility permitted by LaTeX:
\usepackage{arydshln}
...

\begin{table}[h]
\begin{tabular}{lll}
\multicolumn{1}{c}{\textbf{Title 1}} &  & \multicolumn{1}{c}{\textbf{Title 2}} \\
\cline{1-1} \cline{3-3}
\multicolumn{1}{|l|}{Cell 1} & & \multicolumn{1}{|l|}{Cell 2} \\
\cdashline{3-3}
\multicolumn{1}{|l|}{Cell 3} & & \multicolumn{1}{|l|}{Cell 4} \\
\cline{3-3}
\multicolumn{1}{|l|}{Cell 5} & & \\
\cline{1-1}
\end{tabular}
\end{table}

The result is:


text:
Q: Derivation help: gain of 2 NMOS in series I am trying to find the gain (Vout/Vin) of the circuit below, this is not a real circuit that I have, I am just trying to learn more about circuit analysis. The circuit reminds me of a cascode circuit where the gates are the same potential instead of one being Common Gate.
How/where do I start to derive this?
Why is M1 in triode region?
Why is M2 in saturation region?
I did a small signal model analysis followed by short circuiting the output to ground. I followed this up with inserting a test voltage and setting vin to 0V.
Out of this, I got a gain of  gm1*(ro1+ro2) . However I am not sure if this is correct. Any help is appreciated

A: As stated in my previous answer, I thought that the intrinsic gain was \$ G_{eq} = g_{m}*(r_{o1}+r_{o2}) \$.
So I tried simulating both the circuit in question with 2 identical N-mosfets and a normal N-mosfet common source amplifier. for my simulations I've used the Microcap spice simulator with the 2N7002 model for the mosfets.
First, the CS Amplifier :

I've chosen to run the simulations at the operating point : \$V_{gs}=3.5V , I_{D}=100mA\$ (Dont mind the "AC 0.1", the plots were adjusted accordingly)
For your circuit, I thought that I would see a \$+6dB\$ increase. However the gain doubled (well, in decibels..):

The gain got squared ! It went from \$ 49.3 dB \$ to \$ 98.6 dB \$. This looks exactly like a cascode amplifier but with the  \$ 180° \$ phase shift of a CS amplifier.
For a sanity check, I've simulated the equivalent cascode amplifier :

The intrinsic gain isn't the same since the operating point definition is different for each amplifier. But overall the two amplifiers behave similarly in term of gain.
Back to the drawing board
Let's try to find the Gain and Output impedance of your Amplifier with two different mosfets.
Gain :
The hybrid Pi-model for low frequencies is the following (By Krishnavedala - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=36311653):

The amplifier then becomes (Drawn by me):

The output voltage can be written as (Implying an Ideal current source):
\begin{equation}
V_{out} = V_{DS2} + V_{S2}
\end{equation}
with :
\begin{equation}
V_{DS2} = -g_{m2}r_{o2}(V_{in}-V_{S2})
\end{equation}
and
\begin{equation}
V_{S2} = -g_{m1}r_{o1}V_{in}
\end{equation}
After substitution :
\begin{equation}
V_{out} = -[g_{m1}g_{m2}r_{o1}r_{o2}+g_{m1}r_{o1}+g_{m2}r_{o2}-1]V_{in}
\end{equation}
So, the intrinsic Gain can be approximated to :
\begin{equation}
G = -g_{m1}g_{m2}r_{o1}r_{o2}
\end{equation}
This approximation works since the gain \$ g_{m}r_{o} \$ is always higher than 20.
At this stage, we can see that \$ V_{S2} \$ is always \$ g_{m2}r_{o2} \$ times lower than \$ V_{out} \$. This might explain why M1 is in triode region.
Output Impedance : #### (In progress)

A:  >How/where do I start to derive this?
I don't know how to derive  \$ G_{eq} = g_{m}*(r_{o1}+r_{o2}) \$ from two random transistors with different characteristics.
However, if I suppose that the 2 mosfets are planar and have the same \$ W\$  and \$ L\$  (channel width and length), we can think of them as stacked-up mosfets :

(Image drawn by me)
The equivalent mosfet would have a channel length of \$ 2L\$  (approx.) and a width of \$ W\$.
The output resistance formula is :
\$ r_{o,eq} \approx \frac{1}{\lambda I_D}\$
with \$ \lambda \approx {\frac {\Delta L}{V_{E}L_{eq}}} \$
Since we have doubled the channel Length, then \$ r_{o,eq} \approx 2*r_{o} \$
Then, transconductance can be simplified as \$ g_{m,eq} \approx \sqrt{2 \mu_n C_{ox,eq} (\frac{W_{eq}}{L_{eq}}) I_D} \$
With :

*

*\$ L_{eq} = 2L \$

*\$ C_{ox,eq} = 2C_{ox} \$ since we doubled the area of the gate = W*2L

We can conclude that \$ g_{m,eq} \approx g_{m}  \$
And thus, the 2 stacked-up mosfets would have double the Gain : \$ G_{eq} \approx 2*G  \$.

Why is M1 in triode region?

Why is M2 in saturation region?

I am going to simulate this circuit during the weekend and update my post accordingly. But if it's the case, why is the gain  \$ G_{eq} = g_{m1}*(r_{o1}+r_{o2})  \$ ?
Shouldn't M1 be in saturation while M2 should be in the triode region acting as a Drain resistor for M1. (According to the gain you've found)

A: Why is M1 in triode region?
Why is M2 in saturation region?
Start by assuming same W/L ratio for both devices.
Then, if you imagine that both devices have a specific Id vs Vds curve for one specific Vgs and Ir, then each has one specific Vgs that will give Ir for the specific W/L and Vgs.
If this is true (which it is), then you can see that if vin = Vgs1 the voltage at the gate only has enough voltage to supply one full Vgs to both devices, but the M2 would have 0 volt left to supply M1 vds > 0. And M1 vds needs to be a minimum value to be saturated. So right away, M1 cannot be saturated.
M1 has a fixed Id vs Vds curve for a fixed Vgs, but M2 can adjust it's Vs, or equivalently, shift its specific Vgs curve, to get both devices to some operating point to have the same Id (via loop feedback in the circuit configuration).
Now, M1 will move backwards on it's fixed (Vgs) Id vs Vds curve until both currents equalize to a lower value and M1 moves all the way to triode, the top device M2, will adjust by shifting its Vgs (by adjusting the s value and hence Vd to M1) to give equivalent Id as this new M1 operating point in triode. So top device M2 is now is still in saturation (but on a shifted Id/Vds Vgs operating curve), and M1 is the original Id/Vds Vgs curve but operating way back in triode. You'll also notice the original expected current is no longer the same, because the current had to drop for the devices to equalize to the same current.


text:
Q: ComponentResolutionException after upgrading to Castle 3.0 I've just upgraded a solution from .NET 3.5 to .NET 4
In the same time, I've upgraded all external libraries to the latest version, so Castle is now upgraded from 2.5.2 to v3.0
I've some code that register db access that throw now an Exception when I try to resolve:

[Castle.MicroKernel.ComponentResolutionException] {"Could not obtain
  scope for component DF.MailFlowAdapter. This is most likely either a
  bug in custom IScopeAccessor or you're trying to access scoped
  component outside of the scope (like a per-web-request component
  outside of web request
  etc)"}    Castle.MicroKernel.ComponentResolutionException

The component is registered this way:
Container
    .AddFacility<WcfFacility>()
    .AddFacility<DataAccessAdapterFacility>()
    .Register(Component
        .For<SD.LLBLGen.Pro.ORMSupportClasses.IDataAccessAdapter>()
        .ImplementedBy<MailFlowAdapter>()
        .LifeStyle.PerWcfOperation())

The problem comes from the PerWcfOperation LifeStyle, but I don't know why: The project is a WCF project and the component is resolved when calling a WCF method.
This registration is working fine in the branch that use Castle 2.5.
The exception is thrown when Validating the wcf login/pwd (in a IAuthorizationPolicy that use a UserNamePasswordValidator), because I resolve an IDataAccessAdapter (to check login/pwd in the db).
Other piece of information:
The DataAccessAdapterFacility is an old code that register a component activator, I had to slightly change de code because model.Service changed to model.Services:
void Kernel_ComponentModelCreated(ComponentModel model)
{
    foreach (var service in model.Services)
    {
        if (service == typeof(SD.LLBLGen.Pro.ORMSupportClasses.IDataAccessAdapter))
        {
            model.CustomComponentActivator = typeof(DataAccessAdapterActivator);
        }
    }
}

And the DataAccessAdapterActivator has in charge to create the object using a connection string in the config file:
protected override object InternalCreate(CreationContext context)
{
    var connectionString = string.Empty;
    if (ConfigurationManager.ConnectionStrings["Main"] != null)
        connectionString = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
    return new MailFlowAdapter(connectionString);
}

I think the code with DataAccessAdapterFacility/DataAccessAdapterActivator could be simplify using Factory but it's not the question here :)
So does someone have an idea on why I can't use PerWcfOperation lifestyle ?

A: I don't believe an OperationContext.Current is available at the point where a custom UserNamePasswordValidator is called.  Is it possible to use another lifestyle for that component?

A: Ok Let's resume my discussion with Craig Neuwirt on the castle mailing list:

*

*The behaviour has changed,  in v2.5 is was falling back on a
transient lifestyle. But as it was not consistent (No info on when
the component was PerWcfOperation and when it was Transient) this has
been removed.

*It's possible to do the same using a custom lifestyle scope accessor

I'll not post my code here as it's trivial once you've read how the Hybrid lifestyle are done in the castlecontrib project


text:
Q: VisualBasic- How to tell a Log to make a new line? ^^ So I made a TextBox and I want to display a small test log in there.
I told my button to print a Test Text there whenever it gets pressed:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Button1Click As Boolean
    TextBox2.Text = Random()
    Button1Click = True
    If Button1Click Then
        TextBox1.Text = ("Generated ID:" & Random())
    Else
        TextBox1.Text = "LELELELELLE"
    End If
    Button1Click = False
End Sub

The function Random just prints some random numbers there. Ofc it is working and it prints out that: GeneratedID: asd293r04orwr04fjdl BUT the Random numbers always get generated new IN THAT LINE. I want the button to add new lines whenever it is pressed so it looks like that:

*

*GeneratedID: asd293r04orwr04fjdl

*GeneratedID: asdsaghbnmk777777

*GeneratedID: ad49kvß4ßfg3ßtß4

Without the 1,2,3... just because of the strange formatting here.
But how? ^^ I tried vbNewLine but it just didnt work.

A: First make sure that TextBox1.Multiline is true.
TestBox1.AppendText("Generated ID:" & Random() & Environment.NewLine)

should work.


text:
Q: How to test JavaScript? Although been coding JS for a while I never really focused on formal testing any more then usual clicking around in hope that something will break. Now I would like to see how this should be done properly and wonder how testing is performed while coding JavaScript web app. As I understand, in a nutshell, test are written for every method and return values asserted.
Now, how this fits into JavaScript development where JS interacts with DOM, JS animates things around, calculates distances based on browser window and so on and on. How would I test for possible problems other then click around till something breaks? In addition multiple browser and all this got me really confused.
My web app uses module pattern, is coded in strict mode, uses jQuery and bunch of plugins. Clicking till breaks approach works fine so far but I'm sure there is better way and if someone could give me an idea how this should be done that would be much appreciated.

A: In general, the kind of testing you describe with UI interactions is done using a tool which emulates browser behavior.
For example, Selenium can be used to automate different browsers and click on things, and then assert the page's state is as expected.
Another useful tool is phantomjs, which essentially is a headless scriptable browser.
These can be used to do integration/feature testing of the full page. Using these, you would write a test script which defines some interactions ("click X, hover over Y"), and then verify the page's state is what you want (for example, by checking if a CSS selector matches or if a div is visible etc.)
There is also a wide variety of unit testing tools for JavaScript which can be used to test individual JS modules that don't use DOM or such.


text:
Q: Can't build, qmake.exe crashes in Qt Creator I'm using Qt Creator on Windows XP SP3. I want to develop C++ desktop applications.
I made a new project. Everytime I click build, it appears a window which says:

qmake.exe has encountered a problem and needs to close. We are sorry for the inconvenience.

In Qt Creator, something similar to this appears:
20:36:55: Running build steps for project yyy...
20:36:55: Starting: "d:\qtsdk\desktop\qt\4.8.1\mingw\bin\qmake.exe" D:\...\yyy.pro -r -spec win32-g++ "CONFIG+=declarative_debug"
20:38:00: The process "d:\qtsdk\desktop\qt\4.8.1\mingw\bin\qmake.exe" crashed.
Error while building project yyy (target: Desktop)
When executing build step 'qmake'

I can't build, I have reinstalled the software but it keeps giving the same error.
Can you give me any idea of what is happening?

A: Running the qmake command from the command line via a bat file works.


text:
Q: Make python chromedriver script run faster (change send_keys *too slow*) Hello I have built a program script that goes onto a website and selects a size and auto checks out an Item for me it works very well but I have 2 concerns
1.I want to have this script run faster before the script ran pretty fast (so fast that it basically added to cart and went to the checkout page before the Item could even load into the cart (which resulted in errors) and so I added there script to my code
wait = WebDriverWait(driver, 10)  and this one which I mainly used to wait until the item loaded into the cart and all the "add to cart" buttons showed up
wait.until(EC.presence_of_element_located((By.NAME, 'commit')))
but I want this script to run faster I tried changing the
wait = WebDriverWait(driver, 10) into something like
wait = WebDriverWait(driver, 1) and
wait = WebDriverWait(driver, 100) but I see no difference is there anything I can do to make the script run faster?(it doesnt have to do with the wait= thing Ill take any thing I can get to even shave off milaseconds.

*I am currently using the send_keys option for autofill which is PAINFULLY SLOW is there anything I can use that will fill all the stuff instanstly alltogether? ik there are some "JAVA-scripts simular to this that can do it but im not sure how to right java script or more importantly how to even combine them

Can anyone help me out I just want my selenium python chromedriver script to run as fast as possible.
Thank you.
(for my script im using select for the size and just .click()   and a couple of if statements which depends on how many items they want to cart   and lots of def fweuf
fweuf()   (i forget what those are called lol) )

A: For sending values with JS you can do this:
js= "document.getElementById('YOURELEMENT').value = '" + str(YOURVALUE) + "';"
driver.execute_script(js)

Hope this helps.


text:
Q: Uploading Multiple Images to Firebase Storage, and Then Calling the Download URL's to Firebase Database I am trying to upload multiple images to firebase storage simultaneously and then call them down into a firebase database. I have this working with singular images, but I am not sure how I need to modify my code to allow multiple images. When I select multiple images to be uploaded, they successfully upload to firebase storage, however, only the first image uploaded will be assigned to the featuredImage array and therefore displayed. Any help would be much appreciated.
Here is my code:
class OtherEdit extends Component {
constructor(props) {
    super(props);

    this.state={
        id: '',
        info: {
            title: '',
            subtitle: ''
        },
        article: {
            featuredImage: []
        }
    }
}

...
uploadImageCallBack = (e) => {
    return new Promise(async(resolve, reject) => {
        const file = e.target.files[0]
        const fileName = uuidv4()
        storageRef.ref().child("OtherMedia/" + fileName).put(file)
        .then( async snapshot => {

            const downloadURL = await storageRef.ref().child("OtherMedia/" +fileName).getDownloadURL()

            resolve({
                success: true,
                data: {link: downloadURL},

            })
        })
    })
}

...
<FormGroup className='edit-featured-image'> Featured images
                            <Input type="file" multiple accept='image/*' className="image-uploader"
                            onChange={async (e) => {
                                const uploadState = await this.uploadImageCallBack(e)
                                if(uploadState.success) {
                                   await this.setState({
                                        hasFeaturedImage: true,
                                        article: {
                                            ...this.state.article,
                                            featuredImage: uploadState.data.link
                                        }

                                    })

                                }
                            }}>
                            </Input>

                            {
                                this.state.hasFeaturedImage ?
                                     : ''
                            }

                        </FormGroup>

A: You could loop through all files selected and upload each file in a promise, then wait for all promises to resolve, like so:
const uploadImageCallBack = async (e) => {
  const uploads = [];
  const promises = [];

  e.target.files.forEach(file => {

    const path = storageRef.ref().child(`OtherMedia/${uuidv4()}`);
    const uploadPromise = path.put(file).then(async snapshot => {
      /** @TODO it's a good idea to do some error handling here */
      const downloadURL = await path.getDownloadURL();
      uploads.push({
        success: true,
        data: { link: downloadURL },
      });
    });
    promises.push(uploadPromise);

  });

  await Promise.all(promises); // Wait for all promises to complete
  return uploads;
};

Now you can update your state from the Input's onChange:
<Input type="file" multiple accept='image/*' className="image-uploader"
  onChange={async (e) => {
    const uploads = await this.uploadImageCallBack(e);
    const featuredImages = uploads.filter(upload => upload.success).map(upload => upload.data.link);
    await this.setState({
      hasFeaturedImage: true,
        article: {
          ...this.state.article,
          featuredImages // I took the liberty to rename this to plural, as this is an array
        }
    });
  }}>
</Input>

You might want to ditch your hasFeaturedImage state, as you could simply display al images like this (if the array is empty, no images will be displayed).
{
  this.state.article.featuredImages.map((imageSrc, index) => (
    <img key={`image-${index}`} src={imageSrc} />
  ))
}

Note: I have not tested the code above, so feel free to comment if there's something wrong and I'll update it.