text:
Q: Calculating the averages for each KEY in a Pairwise (K,V) RDD in Spark with Python I want to share this particular Apache Spark with Python solution because documentation for it is quite poor.
I wanted to calculate the average value of K/V pairs (stored in a Pairwise RDD), by KEY. Here is what the sample data looks like:
>>> rdd1.take(10) # Show a small sample.
[(u'2013-10-09', 7.60117302052786),
(u'2013-10-10', 9.322709163346612),
(u'2013-10-10', 28.264462809917358),
(u'2013-10-07', 9.664429530201343),
(u'2013-10-07', 12.461538461538463),
(u'2013-10-09', 20.76923076923077),
(u'2013-10-08', 11.842105263157894),
(u'2013-10-13', 32.32514177693762),
(u'2013-10-13', 26.249999999999996),
(u'2013-10-13', 10.693069306930692)]

Now the following code sequence is a less than optimal way to do it, but it does work. It is what I was doing before I figured out a better solution. It's not terrible but -- as you'll see in the answer section -- there is a more concise, efficient way.
>>> import operator
>>> countsByKey = sc.broadcast(rdd1.countByKey()) # SAMPLE OUTPUT of countsByKey.value: {u'2013-09-09': 215, u'2013-09-08': 69, ... snip ...}
>>> rdd1 = rdd1.reduceByKey(operator.add) # Calculate the numerators (i.e. the SUMs).
>>> rdd1 = rdd1.map(lambda x: (x[0], x[1]/countsByKey.value[x[0]])) # Divide each SUM by it's denominator (i.e. COUNT)
>>> print(rdd1.collect())
  [(u'2013-10-09', 11.235365503035176),
   (u'2013-10-07', 23.39500642456595),
   ... snip ...
  ]

A: Now a much better way to do this is to use the rdd.aggregateByKey() method. Because this method is so poorly documented in the Apache Spark with Python documentation -- and is why I wrote this Q&A -- until recently I had been using the above code sequence. But again, it's less efficient, so avoid doing it that way unless necessary.
Here's how to do the same using the rdd.aggregateByKey() method (recommended):
By KEY, simultaneously calculate the SUM (the numerator for the average that we want to compute), and COUNT (the denominator for the average that we want to compute):
>>> aTuple = (0,0) # As of Python3, you can't pass a literal sequence to a function.
>>> rdd1 = rdd1.aggregateByKey(aTuple, lambda a,b: (a[0] + b,    a[1] + 1),
                                       lambda a,b: (a[0] + b[0], a[1] + b[1]))

Where the following is true about the meaning of each a and b pair above (so you can visualize what's happening):
   First lambda expression for Within-Partition Reduction Step::
   a: is a TUPLE that holds: (runningSum, runningCount).
   b: is a SCALAR that holds the next Value

   Second lambda expression for Cross-Partition Reduction Step::
   a: is a TUPLE that holds: (runningSum, runningCount).
   b: is a TUPLE that holds: (nextPartitionsSum, nextPartitionsCount).

Finally, calculate the average for each KEY, and collect results.
>>> finalResult = rdd1.mapValues(lambda v: v[0]/v[1]).collect()
>>> print(finalResult)
      [(u'2013-09-09', 11.235365503035176),
       (u'2013-09-01', 23.39500642456595),
       (u'2013-09-03', 13.53240060820617),
       (u'2013-09-05', 13.141148418977687),
   ... snip ...
  ]

I hope this question and answer with aggregateByKey() will help.

A: Just adding a note about an intuitive and shorter (but a bad) solution to this problem. The book Sam's Teach Yourself Apache Spark in 24 Hours has explained this problem well in the last chapter.
Using groupByKey one can solve the problem easily like this:
rdd = sc.parallelize([
        (u'2013-10-09', 10),
        (u'2013-10-09', 10),
        (u'2013-10-09', 13),
        (u'2013-10-10', 40),
        (u'2013-10-10', 45),
        (u'2013-10-10', 50)
    ])

rdd \
.groupByKey() \
.mapValues(lambda x: sum(x) / len(x)) \
.collect()

Output:
[('2013-10-10', 45.0), ('2013-10-09', 11.0)]

This is intuitive and appealing, but don't use it! groupByKey does not do any combining on the mappers and brings all the individual key value pairs to the reducer.
Avoid groupByKey as much as possible. Go with the reduceByKey solution like @pat's.

A: To my mind a more readable equivalent to an aggregateByKey with two lambdas is:
rdd1 = rdd1 \
    .mapValues(lambda v: (v, 1)) \
    .reduceByKey(lambda a,b: (a[0]+b[0], a[1]+b[1]))

In this way the whole average calculation would be:
avg_by_key = rdd1 \
    .mapValues(lambda v: (v, 1)) \
    .reduceByKey(lambda a,b: (a[0]+b[0], a[1]+b[1])) \
    .mapValues(lambda v: v[0]/v[1]) \
    .collectAsMap()

A: A slight enhancement to the answer of prismalytics.io.
There could be a case where computing the sum might overflow number because we are summing huge number of values. We could instead keep the average values and keep computing the average from the average and counts of two parts getting reduced.
If you have two parts having average and counts as (a1, c1) and (a2, c2), the overall average is:
total/counts = (total1 + total2)/ (count1 + counts2) = (a1*c1 + a2*c2)/(c1+c2)
If we mark R = c2/c1, It can be re-written further as a1/(1+R) + a2*R/(1+R)
If we further mark Ri as 1/(1+R), we can write it as a1*Ri + a2*R*Ri
myrdd = sc.parallelize([1.1, 2.4, 5, 6.0, 2, 3, 7, 9, 11, 13, 10])
sumcount_rdd = myrdd.map(lambda n : (n, 1))
def avg(A, B):
    R = 1.0*B[1]/A[1]
    Ri = 1.0/(1+R);
    av = A[0]*Ri + B[0]*R*Ri
    return (av, B[1] + A[1]);

(av, counts) = sumcount_rdd.reduce(avg)
print(av)

This approach can be converted for key-value by simply using mapValues instead of map and reduceByKey instead of reduce.
This is from: https://www.knowbigdata.com/blog/interview-questions-apache-spark-part-2


text:
Q: XMLReader not reading cdata I have a problem. I wrote this code but I can't read <![CDATA[Epsilon Yayınları]]>.  Items with cdata, when I get them it's empty. Is there an alternative solution?
XML:
<urunler>
  <urun>
    <stok_kod>9789753314930</stok_kod>
    <urun_ad><![CDATA[Kırmızı Erik]]></urun_ad>
    <Barkod>9789753314930</Barkod>
    <marka><![CDATA[Epsilon Yayınları]]></marka>
    <Kdv>8,00</Kdv>
    <satis_fiyat>9,5000</satis_fiyat>
    <kat_yolu><![CDATA[Edebiyat>Hikaye]]></kat_yolu>
    <resim>http://basaridagitim.com/images/product/9789753314930.jpg</resim>
    <Yazar>Tülay Ferah</Yazar>
    <Bakiye>2,00000000</Bakiye>
    <detay><![CDATA[]]></detay>
  </urun>
</urunler>

$xml = new XMLReader;
    $xml->open(DIR_DOWNLOAD . 'xml/'.$xml_info['xml_file_name']);
    $doc = new DOMDocument;

    $product_data = array();

    $i=0;

    while ($xml->read() && $xml->name !== 'urun');
    while ($xml->name === 'urun') {  $i++;

        $node = simplexml_import_dom($doc->importNode($xml->expand(), true));

        var_dump($node->urun_ad); die();

Dump print:
object(SimpleXMLElement)#143 (1) {
  [0]=>
  object(SimpleXMLElement)#145 (0) {
  }
}

A: It just comes down to how your printing out the value.  If you change the var_dump to either of the following, you will get what your after...
//var_dump($node->urun_ad)
echo $node->urun_ad.PHP_EOL;
echo $node->urun_ad->asXML().PHP_EOL;

outputs...
Kırmızı Erik
<urun_ad><![CDATA[Kırmızı Erik]]></urun_ad>

One thing to note is that if you want to use the value in another method, you may have to cast it to a string (echo does this automatically).  So the first one would be (for example)...
$urun_ad = (string)$node->urun_ad;

redpajama_set_name: RedPajamaStackExchange


text:
Q: client_side_validation and devise Gem not working When I am installing client_side_validation in my project its giving error
ArgumentError in Devise::Sessions#new
wrong number of arguments (3 for 2)
in
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>

Its working fine if I am removing gem client_side_valiation from my gem file. I tried searching on stackoverflow but not working.
Thanks in advance.

A: Try this:
<%= form_for(resource, :validate => true, :as => resource_name, :url => registration_path(resource_name)) do |f| %>

And you can find useful info here:
Client side validations with Devise


text:
Q: Get file data to parse on server i am trying to do a simple pdf file upload.
i used express-fileupload to do the job on uploading the file to the server, everything ok here, the problem arrives that i need to create the file with the buffer that i receive, basicly i need to store the files on the server. How can i do that?
At the moment in my server i am receiving this data:
{ name: 'sda.pdf',
  data: <Buffer 25 50 44 46 2d 31 2e 35 0d 25 e2 e3 cf d3 0d 0a 31 20 30 20 6f 62 6a 0d 3c 3c 2f 4d 65 74 61 64 61 74 61 20 32 20 30 20 52 2f 4f 43 50 72 6f 70 65 72 ... >,
  encoding: '7bit',
  mimetype: 'application/pdf',
  mv: [Function: mv] }

i log the data on the upload route:
router.post('/upload', function(req, res, next) {
  console.log(req.files.curriculum);
});

any help?

A: You can see the mv function on the express-fileupload object. Use this function to put the file where you want on your server. (from the express-fileupload readme)
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
        return res.status(500).send(err);
    res.send('File uploaded!');
});


text:
Q: Java - Change Attribute of Subclass Object I have the following java superclass with constructor and getters and setters for each attribute:
public  class vehicle {
     int vehicleId;

public vehicle(int vehicleId) {
        super();
        this.vehicleId = vehicleId;

    }

     public int getVehicleId() {
    return vehicleId;
}

public void setVehicleId(int vehicleId) {
    this.vehicleId = vehicleId;
}

And a car subclass that extends the vehicle super class and has a few unique attributes:
public class car extends vehicle{

private String wheels;

//constructor
    public car( int vehicleId, String wheels) {
        super(vehicleId);
        this.wheels = wheels;
    }

//getters and setters

public int getWheels() {
    return wheels;
}

public void setWheels(int wheels) {
    this.wheels = wheels;
}

I create a new linked list of vehicle objects and add a new car object to it:
LinkedList<vehicle> gbm = new LinkedList<vehicle>();
car car = new car(0, "");
car.setVehicleId(1);
car.setWheels("alloy");
gbm.add(car);

I can change any of the attributes that belong to the vehicle super class with a function like this:
public static void editVehicleId(int vid, int vehicleId) {

        for (vehicle obj : gbm) {
            if (obj.vehicleId == vid) {
                obj.setVehicleId(vehicleId);

            } else {
                System.out.println("No matching vehicle Id found - please check input");
            }
        }

    }

But when I try to create a similar function to change one of the subclass attributes, i get this error: "the method setWheels(int) is undefined for the type vehicle".
public static void editWheels(int vid, int wheels) {

        for (vehicle obj : gbm) {
            if (obj.vehicleId == vid) {
                obj.setWheels(wheels);

            } else {
                System.out.println("No matching vehicle Id found - please check input");
            }
        }

    }

Can somebody tell me how to edit one of the subclass specific attributes?

A: Your for loop variable is a vehicle type. Since this is a method for the car class, make it a car object:
for (vehicle obj : gbm) {
    if (obj.vehicleId == vid) {
        if (obj instanceof car) {
            ((car)obj).setWheels(wheels);
        }
    }
    ... rest of loop ...
}


text:
Q: transform: translate Not working across all browsers I have an issue.
image {
  transform: translate(40px, 40px);
}

Isn't working on Internet Explorer 11
Full Working Code:
https://jsfiddle.net/f7u38uds/
This is how it looks in in internet explorer 11.
Screenshot
Is there something that I can use that will work across all browsers?

A: Try this:
image {
  transform: translate(40px, 40px);
  -ms-transform: translate(40px, 40px);
}


text:
Q: When closing, don't show closed questions as original When a question gets closed as an exact duplicate, I often see that the original, which the question gets closed as a duplicate of, is itself closed.
This is not very nice behaviour.
My proposal is for the system to check, when a question gets closed, if the original is itself closed, and if so, don't show a link to that original, but to the original's original.
Or in other words, if question B is closed as a duplicate of A

(and B has a link "Possible duplicate: A") then when question C gets closed by people as a duplicate of B, let the system show a link to question A instead of B.

So that new readers of question C won't end up in another closed question when they click the "Possible duplicate" link.

A: I don't like this idea.
By removing the inner link you are removing possibly useful information and changing a series of questions that someone can click through finding out more information into a single node with a lot of single links coming off it.
It assumes that the "original" has the best / most appropriate answers, which is not always the case.
Freehand red circles... what happens if a poster finds Question C; this doesn't quite solve their problem but Question B would. In your scenario they might not find Question B and post their question. We want them to find Question B.

However, by doing the same work you can list all the duplicates in the chain when a question gets closed as such. This may be an improvement as the chain is now in one easily visible place. If a new poster doesn't quite find the answer they're looking for in the original question there is an immediately obvious list of questions and answers that they could look for, which might make it less likely that duplicate questions would be avoided.


text:
Q: Java: is there a way to construct a max-heap from an array in O(n) using PriorityQueue? Correct me if I'm wrong, but I think the PriorityQueue(Collection c) constructor will create a min-heap from a collection in time O(n). However, I couldn't find a constructor where I can pass both a collection and a comparator (in order to convert the min-heap to a max-heap). So I was wondering if  there is a way to construct a max-heap from an array (say, int array) in O(n) using PriorityQueue?

A: No, having a set of elements arranged in a min-heap does not provide any advantage for rearranging them into a max-heap.  Also, you seem to be assuming that the PriorityQueue constructors that accept a collection have O(n) asymptotic complexity.  That's plausible -- even likely -- but it is not documented, so it is not safe to rely on it.


text:
Q: WCF consume Https service Currently I consume third party Web Services in my application, the Web Services is 1 way SSL but after I consume the Services in my Visual Studio. At the Web.Config files binding services become no SSL it should download the Https but now is Http. Below are my Web Service. Anyone here. Please help. Thanks
http://ws2.oriongateway.com:22836/willani2/services/ogltngws (No way SSL)
https://ws2.oriongateway.com:22837/willani2/services/ogltngws (1 way SSL)

My app.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                 initializeData="FileLogWriter"/>
            <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
            <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
        </sharedListeners>
    </system.diagnostics>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="OglTngWsSoap11Binding1" />
            </basicHttpBinding>
            <customBinding>
                <binding name="OglTngWsSoap12Binding1">
                    <textMessageEncoding messageVersion="Soap12" />
                    <httpTransport />
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="http://ws2.oriongateway.com:22836/willani2/services/ogltngws.OglTngWsHttpSoap12Endpoint/"
                binding="customBinding" bindingConfiguration="OglTngWsSoap12Binding1"
                contract="aService.OglTngWsPortType" name="OglTngWsHttpSoap12Endpoint1" />
            <endpoint address="http://ws2.oriongateway.com:22836/willani2/services/ogltngws.OglTngWsHttpSoap11Endpoint/"
                binding="basicHttpBinding" bindingConfiguration="OglTngWsSoap11Binding1"
                contract="aService.OglTngWsPortType" name="OglTngWsHttpSoap11Endpoint1" />
        </client>
    </system.serviceModel>
</configuration>

A: Try next changes:
        <basicHttpBinding>
            <binding name="OglTngWsSoap11Binding1" />
            <security mode="Transport"> // add security mode
        </basicHttpBinding>

Change endpoint address to https and don't forget change port as well:
            <endpoint address="https://ws2.oriongateway.com:22837/willani2/services/ogltngws.OglTngWsHttpSoap11Endpoint/"
            binding="basicHttpBinding" bindingConfiguration="OglTngWsSoap11Binding1"
            contract="aService.OglTngWsPortType" name="OglTngWsHttpSoap11Endpoint1" />

Let me know if it works.


text:
Q: How to change video drivers from the CLI I've read a few things but can't get a definitive answer.
So to confirm, is it
sudo ubuntu-drivers devices
sudo apt-get install nvidia-381

and then to switch back, it would be simply
sudo apt-get install xserver-xorg-video-nouveau

So just to clarify, to switch to the video drivers you want, you're essentially installing them rather than just enabling them?

A: Yes sudo apt-get install nvidia-340 would be how you switch to the Nvidia-340 driver. Basically you're installing the drivers like software and the old driver is automatically uninstalled.


text:
Q: Implementing analaytical integration for a series expansion in Python I would very much like to implement analytical integration in my calculator. I have used numerical integration prior to this attempt with success. However, I can't seem to make my code work.
I'm using the scipy.integrate module and the error code I get is TypeError: can't convert expression to float
My code is:
from sympy.functions import sin,cos,tan
from sympy.abc import x
from sympy import series
import scipy.integrate as integrate
import scipy.special as special

function1   = str(input("The function that should be expanded: "))
x0          = float(input("Point of developement: "))
n           = 1 + int(input("Grade of polynomial: "))
# input 0 -> n=1 -> konstant  (1 term, konstant)
# input 1 -> n=2 -> lineær    (2 termer, konstant + linear)
# input 2 -> n=3 -> kvadratisk (3 termer, konstant + linear + kvadratisk)
# ...

function2 = series(function1, x, x0, n)
print(function2)

a = float(input("Integrate from: "))
b = float(input("Integrate to: "))

def f(x):
    return function2.removeO()

x = Symbol('x')
result = integrate.quad(lambda x: f(x), a, b)

print("...................")
print("Here is your answer: ")
print(result)

I believe it might be due to the code using different modules (sympy and scipy) or that I just need to convert the expression in some way. I attempted to use lambdify but without success.
def f(x):
    return function2.removeO()
lam_f = lambdify(x, f(x))
result = integrate.quad(lambda x: lam_f, a, b)

And got another TypeError, since lambdify turns the expression into a function instead.
Can anyone help?


text:
Q: Spring Boot YAML Auto Data Source Configuration Issue - Data Source URL not picked up Currently, We are creating a spring boot project for our newer modules.
Technology We have used as follows :

*

*Java 1.8

*Maven 3.5.2

*Spring Boot: 1.5.6.RELEASE (spring-boot-starter-parent)

public class Application {
public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Autowired
private DataSource datasource;

}
application.properties

*

*spring.datasource.url=jdbc:oracle:XXX:@XXX:XXX/XXX

*spring.datasource.username=XXX

*spring.datasource.password=XXX

*spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

application.yml

*

*spring:

*

*profiles:

*active: "dev"

*main:

     - banner-mode: "off"

*spring:

*

*profiles: dev

*datasource:

*

*url:jdbc:oracle:XXX:@XXX:XXX/XXX

*username:XXX

*password:XXX

*driver-class-name:oracle.jdbc.driver.OracleDriver

When we are adding data source information as properties file the application working as expected. But information as YAML means showing below error.
ERROR
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testapplication': Unsatisfied dependency expressed through field 'datasource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active).

A: Yml standards dictate us to specify a space after colon(:). Please have a look at the documentation
  Change your yml like this and It should work fine.
spring:
  profiles: dev
  datasource:
     url: jdbc:oracle:XXX:@XXX:XXX/XXX
     username: XXX
     password: XXX
     driver-class-name: oracle.jdbc.driver.OracleDriver


text:
Q: Why does SQL foribben to execute SELECT query? I try to execute query in phpmyadmin and get error:
#1142 - SELECT command denied to user 'cpses_tkdpmnyjWW'@'localhost' for table 'user'

So, user cpses_tkdpmnyjWW'@'localhost is created dynamically and I can not set privileges for this user.
How to fix this?

A: Use SHOW GRANTS to show your current user privileges. It sounds as though the output may be similar to:
GRANT USAGE ON *.* TO 'Unnamed'@'localhost'

This would mean the account could sign into the server but do little else. This page gives a more detailed breakdown, as you'll see there are quite a few permutations.
The solution is you need to either find an account with more privileges or create/update one.
If the above is not an option, one quick trick I may try is connecting to '127.0.0.1' instead of 'localhost'. In MySQL the source of the connection can form part of the username so it's plausible that connecting on an IP instead of socket if you are on Unix flavoured OS.
Additionally, if you have admin/root access to the server, it is possible to create users when MySQL starts which is very useful in some scenarios.


text:
Q: Prevent tab change event in angular material md-tab Is it possible to prevent tab change in angular-material's md-tabs or md-tab directive?
I use the md-on-select directive to execute a function once a tab is clicked and set the md-active value to false for a specific tab. But the tab switch still happens and I seem not to be able to prevent it:
<md-content>
        <md-tabs md-dynamic-height md-border-bottom>
            <md-tab label="Tab1" md-active="ctrl.selectTab1" md-on-select="ctrl.tabClicked('Tab1')">
                <md-content>
                    myContent
                </md-content>
            </md-tab>
            <md-tab label="Tab2" md-active="ctrl.selectTab2" md-on-select="ctrl.tabClicked('Tab2')">
                <md-content>
                    mycontent
                </md-content>
            </md-tab>
        </md-tabs>
</md-content>

In the controller function I have
function tabClicked(tab) {
        switch (tab) {
            case 'Tab1':
                vm.selectTab1 = true;
                vm.selectTab2 = false;
                break;
            case 'Tab2':
                vm.selectTab1 = false;
                vm.selectTab2 = true;
                break;
        }
}

A: This is an exemple but im not sure if this what you want
Exemple

  <md-content>
      <md-tabs md-dynamic-height md-border-bottom md-selected="selected"    >
          <md-tab label="Tab1" ng-click="tabClicked('Tab1')">
              <md-content>
                  myContent 1
              </md-content>
          </md-tab>
          <md-tab label="Tab2" ng-click="tabClicked('Tab2')">
              <md-content>
                  mycontent 2
              </md-content>
          </md-tab>
      </md-tabs>
   </md-content>

angular.module("myApp",['ngMaterial']).controller("MyCtrl", function($scope) {

  $scope.selected = 0

  $scope.tabClicked = function(tab) {
    switch (tab) {
        case 'Tab1':
             $scope.selected = 0
            break;
        case 'Tab2':
            $scope.selected = 0
            break;
    }
  }

});

I hope that help you


text:
Q: Is it possible to use a wildcard certificate generated via cert-manager (Lets Encrypt) in multiple K8S clusters I would be using different subdomains for different services, but those services would reside in different K8S clusters. I would like to know if I can just copy the wildcard certificate across the clusters. Also, if there is a similar example somewhere please link me to it.
Any help would be appreciated.

A: So there is no native handling of multiple clusters in cert-manager.
That said, there is nothing to stop you copying across the resulting 'Secret' resource between clusters, either manually or automatically.
The 'kubed' project (by appscode) has support for syncing Secrets between clusters: https://github.com/appscode/kubed. Full information can be found on their website: https://appscode.com/products/kubed/0.8.0/guides/config-syncer/inter-cluster/
I hope this helps!

A: i know, i am a bit late to the party but writing an answer might be helpful to someone
For wildcard cert DNS-01 method, auth is required. You can use any DNS as per use case or which ever you are using.
Note : You might require to first add the CAA record in your DNS.
CAA record can get added into DNS zone
example :
            Type       Value

devops.in   CAA       0 issuewild "letsencrypt.org"

get your records details from : https://sslmate.com/caa/
First we have to create the secret for storing the access key using the command
kubectl create secret generic route53-secret --from-literal=secret-access-key="skjdflk4598sf/dkfj490jdfg/dlfjk59lkj"

Here sharing the example issuer.yaml
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    email: test123@gmail.com
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - selector:
        dnsZones:
          - "devops.in"
      dns01:
        route53:
          region: us-east-1
          hostedZoneID: Z2152140EXAMPLE
          accessKeyID: AKIA5A5D7EXAMPLE
          secretAccessKeySecretRef:
            name: route53-secret
            key: secret-access-key
---
apiVersion: cert-manager.io/v1alpha2
kind: Certificate
metadata:
  name: le-crt
spec:
  secretName: tls-secret
  issuerRef:
    kind: Issuer
    name: letsencrypt-prod
  commonName: "*.devops.in"
  dnsNames:
    - "*.devops.in"

Also make sure your user have necesarry permission to manage the Route53
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "route53:GetChange",
      "Resource": "arn:aws:route53:::change/*"
    },
    {
      "Effect": "Allow",
      "Action": "route53:ChangeResourceRecordSets",
      "Resource": "arn:aws:route53:::hostedzone/*"
    },
    {
      "Effect": "Allow",
      "Action": "route53:ListHostedZonesByName",
      "Resource": "*"
    }
  ]
}


text:
Q: How can I limit the number of HTTP connections in OpenLiberty? I want to limit the number of HTTP connections for web applications on OpenLiberty. Which parameters should I change to do this? I'm looking at the docs, should I change maxConcurrentStreams in HTTPOption or maxThread in executer?

A: There isn't an existing property to specifically limit HTTP connections, so I'd recommend using maxOpenConnections, which is a tcpOptions configuration[1]. That property allows you to restrict the number of open connections for a TCP endpoint. The default value is 128000.
maxConcurrentStreams applies specifically to HTTP/2 the number of streams that are allowed per HTTP/2 (TCP) connection, and maxThread won't directly accomplish what you want.
[1] https://openliberty.io/docs/21.0.0.2/reference/config/httpEndpoint.html#tcpOptions


text:
Q: MathJax in Comment Gets Corrupted MathJax bug:
(Of course I don't know whether the bug is in the MathJax engine or in StackExchange code.)
When I enter the following comment in a math.stackexchange.com page, the second \alpha in sin(α_1+α_2) gets split up for some reason, yielding sin(α_1+\a lpha_2), which displays with the \a in red as an unrecognized escape sequence.

It depends on what you mean by "closed-form". Since it is only piecewise differentiable, I don't think you can avoid the presence of constructs like "max" that correspond to an "if-then" in a program, although they can be hidden using closed-form constructs like "if A then B else C"$=B\,sgn(A)^2+C(1-sgn(A)^2)$. Given 2 angles $\alpha_1,\alpha_2$, you can assume a unit-diameter circumcircle and construct all the other parameters: $(s_1,s_2,s_3,\phi_1,\phi_2,\phi_3)=(sin(\alpha_1),sin(\alpha_2),sin(\alpha_1+\alpha_2),0,\alpha_1+\alpha_2,\alpha_2)$. These two tricks should give you what you want.

A: This is the Stack Exchange™ WhiteSpace EnforcementOfficer™ at work. It inserts zero-width space in comments that have overly long strings of characters with no whitespace. When this happens inside your long formula, too bad: it's no longer valid markup for MathJax.
Workaround: use some whitespace in long formulas when you post them in comments. Something like $(s_1,s_2,s_3,\phi_1,\phi_2,\phi_3)= (sin(\alpha_1),sin(\alpha_2), sin(\alpha_1+\alpha_2),0, \alpha_1+\alpha_2,\alpha_2)$ is safe to use.
I think it's not feasible for the simple comment processor to correctly decide what's a formula and what's not. (Why, oh why did Knuth use symmetric delimiters for math?). Perhaps a more realistic solution would be to train MathJax to ignore HTML entities , but this is something you'd need to bring up with MathJax team.  For now, manual insertion of whitespace will have to do.


text:
Q: How to prevent XMLHttpRequest from throwing an error on connection failure I'm using XMLHttpRequest to consume APIs on the background. Everything's working fine! My only problem is that when there's no internet, it prints an error message on the console even when it's handled by XMLHttpRequest.onerror
I'm making a PWA that can work offline... it will try to connect but if it failed, that's okay...
Simplified experimental scenarios:
Running the following code shows an error when the internet is disconnected (after installing the app):
let x = new XMLHttpRequest();
x.onload = //do something...
x.onerror = //do another thing...
x.open("GET", "/someresource");
x.send();

And even the following still shows an error when there's no internet:
try {
  let x = new XMLHttpRequest();
  x.onerror = (e) => {
    console.log(
      "Don't worry about anything! \
     This error was handled successfully"
    );
    e.preventDefault();
    return true;
  };
  x.open("GET", "/some-resource");
  x.send();
} catch (e) {
  console.log("It's all under control");
}

Screenshot of the error that should not happen
Which triggers some OCD tendencies for me! I can't sleep before this error is handled...


text:
Q: Decomposing U.S. Imports of Goods by Customs Basis from China I'm working on a project which aims at analyzing the dataset U.S. Imports of Goods by Customs Basis from China (IMPCH). The main point is to make some prediction but we also want to do a little inference from the data.
As far as I know, the first step is to decompose the time series. There are at least five decomposition methods and the residual (remainder) of all of them passes the unit root tests, indicating the results are stationary, which is desired. However, now I have to pick one of them to proceed, but all seem good.
Which one should I choose, decompose, HoltWinters, forecast::ets, stl, or seasonal::seas?
# dataset
# https://fred.stlouisfed.org/series/IMPCH

IMPCH <- read.csv("IMPCH.csv")
imp <- IMPCH$IMPCH
imp.ts <- ts(imp, frequency = 12, start = 1985)
log.imp.ts <- log(imp.ts)
ts.plot(log.imp.ts)

## Decomposition
library(tseries)

# Stock decompose
log.imp.ts.dcps <- decompose(log.imp.ts)
plot(log.imp.ts.dcps)
log.imp.ts.dcps.remainder <- na.remove(log.imp.ts.dcps$random)
adf.test(log.imp.ts.dcps.remainder)
pp.test(log.imp.ts.dcps.remainder)
kpss.test(log.imp.ts.dcps.remainder)

# Holt-Winters Filtering
log.imp.ts.hw <- HoltWinters(log.imp.ts)
plot(log.imp.ts.hw)
log.imp.ts.hw.remainder <- resid(log.imp.ts.hw)
adf.test(log.imp.ts.hw.remainder)
pp.test(log.imp.ts.hw.remainder)
kpss.test(log.imp.ts.hw.remainder)

# ETS
library(forecast)
log.imp.ts.ets <- ets(log.imp.ts)
plot(log.imp.ts.ets)
log.imp.ts.ets.remainder <- resid(log.imp.ts.ets)
adf.test(log.imp.ts.ets.remainder)
pp.test(log.imp.ts.ets.remainder)
kpss.test(log.imp.ts.ets.remainder)

# STL
log.imp.ts.stl <- stl(log.imp.ts, s.window = "periodic", robust = TRUE)
plot(log.imp.ts.stl)
log.imp.ts.stl.remainder <- log.imp.ts.stl$time.series[, "remainder"]
adf.test(log.imp.ts.stl.remainder)
pp.test(log.imp.ts.stl.remainder)
kpss.test(log.imp.ts.stl.remainder)

# X-13ARIMA-SEATS
library(seasonal)
log.imp.ts.seas <- seas(log.imp.ts)
plot(log.imp.ts.seas)
log.imp.ts.seas.remainder <- resid(log.imp.ts.seas)
adf.test(log.imp.ts.seas.remainder)
pp.test(log.imp.ts.seas.remainder)
kpss.test(log.imp.ts.seas.remainder)

A: Holt-Winters is not telling us a lot about the data in terms of additive decomposition, it's only really doing some smoothing. I definitely wouldn't go with that.
Next, ETS. It's better than HW, but it's not segregating the random component of the data. Looking at your results, it seems to be distributing the random variability between the slope and the season components as opposed to isolating it. Also, I don't feel the slope is really telling us much here, it's a bit redundant when you have the level. So, I wouldn't use ETS.
The tseries results look clean and the components are what I would expect. Much better than the previous 2.
STL: personally, I would go with STL. The results you got are more or less as clean as the decompose ones, but I prefer STL because it uses local regression, is robust to outliers, and lets you control the smoothness of the trend cycle.


text:
Q: How do I parse and find a string in a C# script? I've been trying to parse and search for a specific word in a big string, but I can't seem to be able to figure it out. I have created a script that connects a Twitch Channel's chat into unity.
An example of a message would be:

"@badge-info=subscriber/4;badges=moderator/1,subscriber/3,bits/1;bits=1;color=;display-name=TwitchUser1234;emotes=;flags=;id=da6ec4c6-af61-4346-abc-123456789;mod=1;room-id=12345678;subscriber=1;tmi-sent-ts=160987654321;turbo=0;user-id=123456789;user-type=mod :TwitchUser1234@TwitchUser1234.tmi.twitch.tv PRIVMSG #thechannelyouarewatching :PogChamp1 Another Test Bit"

I tried parsing and searching for the string 'bits' the message by doing:
 private void GameInputs(string ChatInputs)
 {
    string Search;
    Search = ChatInputs.Split(";", "=");
    if(string "bits" in Search)
    {
        print("I made it here.");
    }
}

I'm at a complete loss and have no idea how to do this. Any help is appreciated.
If my full code is needed it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.ComponentModel;
using System.Net.Sockets;
using System.IO;

public class TwitchChat : MonoBehaviour
{

    private TcpClient twitchClient;
    private StreamReader reader;
    private StreamWriter writer;

    public string username, password, channelName; // http://twitchapps.com/tmi

    // Start is called before the first frame update
    void Start()
    {
        Connect();
    }

    void Update()
    {
        if(!twitchClient.Connected)
        {
            Connect();
        }

        ReadChat();
    }

    private void Connect()
    {
        twitchClient = new TcpClient("irc.chat.twitch.tv", 6667);
        reader = new StreamReader(twitchClient.GetStream());
        writer = new StreamWriter(twitchClient.GetStream());

        writer.WriteLine("PASS " + password);
        writer.WriteLine("NICK " + username);
        writer.WriteLine("USER " + username + " 8 * :" + username);
        writer.WriteLine("JOIN #" + channelName);
        writer.WriteLine("CAP REQ :twitch.tv/tags");
        writer.Flush();
    }

    private void ReadChat()
    {
        if (twitchClient.Available > 0)
        {
            var message = reader.ReadLine();

            print(message);

            GameInputs(message);
        }
    }

    private void GameInputs(string ChatInputs)
    {
        string Search;
        Search = ChatInputs.Split(";", "=");
        if(string "bits" in Search)
        {
            print("I made it here.");
        }
    }
}

A: If you want to pull the value of "bits=xx" out, this would do it:
var b = value.Split(';').FirstOrDefault(s => s.StartsWith("bits="))?[5..];

b will be null if "bits=" is not present
If you're going to parse a lot of values out of this string consider turning it into a dictionary:
var c = new []{'='};

var d = value.Split(';').ToDictionary(s => s.Split(c,2)[0], s => s.Split(c,2)[1]);

It's slightly inefficient to split twice, if it bothers you, you can sub string:
value.Split(';').ToDictionary(s => s[..s.IndexOf('=')], s => s[s.IndexOf('=')+1..]);

This gives a dictionary of string, so you can do like:
if(d.ContainsKey("bits")){
  var bits = int.Parse(d["bits"]);
  ...

A: String has a method Contains(string) that does the job:
if (ChantInputs.Contains("bits")
{
     print("I made it here.");
}

A: You can try below.
private void GameInputs(string ChatInputs)
{
string[] Search = ChatInputs.Split(new char[] { ';', '=' });
foreach(string s in Search)
 {
  if(s == "bits")
  {
    print("I made it here.");
  }
 }
}

Below is the working code.
using System;

namespace ConsoleApp3
{
class Program
{
    static void Main(string[] args)
    {
        string str = "one;two;test;three;test+test";

        string[] strs = str.Split(new char[] { ';', '+' });

        foreach(string s in strs)
        {
            if(s == "test")
            {
                Console.WriteLine(s);
            }
        }

        Console.ReadLine();
    }
}
}


text:
Q: VB.Net Properly shutdown an asynchronous socket server running on a background worker I have a Class called SocketSvr which handles an asynchronous socket server. It is called via the BackgroundWorker from my main form. Basically, I just want it to display my socket data information inside a textbox in the main form, and have a server start/stop button available on the main form to do those things.
Here is the code from Form1.vb:
Public Class Form1

    Dim WithEvents Socketsvr As New SocketSvr

    Private Sub ToggleServerButton_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles ToggleServerButton.Click

        If ToggleServerButton.Text = "Stop Server" Then
            ToggleServerButton.Text = "Start Server"
            Socketsvr.StopServer()
        Else
            ToggleServerButton.Text = "Stop Server"
            Socketsvr.StartServer()
        End If
    End Sub

    Private Sub UpdateOutput_Event(ByVal sender As Object, _
        ByVal text As String) Handles Socketsvr.UpdateOutput
        Me.ServerOutputTextbox.AppendText(text + vbCrLf)
    End Sub

End Class

The above is very simple, basically calls the StartServer() or StopServer() function. The event below is a Raised event which I am using to update the textbox via an invoked event from the background process.
Below is some of the code for Socketsvr.vb -- I remove irrelevant code to minimize blating of post.
Public Sub StopServer()
    bw.CancelAsync()
    allDone.Set()
End Sub 'StopServer

Public Sub StartServer()
    bw.WorkerSupportsCancellation = True
    bw.RunWorkerAsync()
End Sub 'StartServer

Private Sub bw_DoWork(ByVal sender As System.Object, _
    ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
    ' Data buffer for incoming data.
    Dim bytes() As Byte = New [Byte](1023) {}

    ' Establish the local endpoint for the socket.
    Dim ipHostInfo As New IPHostEntry
    ipHostInfo.AddressList = New IPAddress() _
        {New IPAddress(New [Byte]() {127, 0, 0, 1})}
    Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
    Dim localEndPoint As New IPEndPoint(ipAddress, 8888)

    ' Create a TCP/IP socket.
    Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

    ' Bind the socket to the local endpoint and listen for incoming connections.
    listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1)
    listener.Bind(localEndPoint)
    listener.Listen(100)
    While True
        ' If cancellation is pending, shut down server
        If bw.CancellationPending Then
            Out("Server stopped at " + DateTime.Now.ToString())
            Exit While
        End If
        Out("Server started at " + DateTime.Now.ToString())
        ' Set the event to nonsignaled state.
        allDone.Reset()

        Try
            ' Start an asynchronous socket to listen for connections.
            listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        ' Wait until a connection is made and processed before continuing.
        allDone.WaitOne()
    End While
End Sub

I am uncertain how to properly shut down requests from the client when the StopServer() function is run. In the code above, I place a cancellation queue for the background process. The funny thing is that once StopServer() is run, it will accept one more connection, then stop accepting thereafter.
If I remove the following line from the code above:
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1)

-- it crashes when I attempt to start the server a second time (complaining that I cannot reuse the socket, obviously) My guess is that I need to add something to the bw.CancellationPending call on the background worker?
Any insight would be appreciated, please let me know if more information is required from my end.

A: I don't really like MSDN's example code because it uses a while loop that makes you think it's necessary; if it were necessary, then you would actually need to listen on another thread. Luckily, you don't need to use a BackgroundWorker, and you can easily do everything outside of a while loop without locking down the UI thread.
First, create a Shared method (to go along with the other shared callbacks and methods) called Accept(Socket) that will do the Socket.BeginAccept. Another method is easier because it will be run in two places, and you may later find the need to catch exceptions. Somewhere in your main Form, after binding the IPEndPoint and listening, you'll add your first call to Accept, providing the socket used for listening.
I would also recommend creating a Receive(Socket) method, where the socket is the newly connected client obtained in AcceptCallback. This will also improve organization because more code than just BeginReceive will be there, such as catching exceptions.
In your AcceptCallback method, after you do your Receive, you'll once again call Accept. This will continuously loop between Accept and AcceptCallback. In order to break this loop to stop listening, just call the Socket.Close method, set the socket field to Nothing, and catch these exceptions:

*

*SocketException (which is really unrelated to Close)

*ObjectDisposedException (since Close is a dispose)

*NullReferenceException (an occasional race condition will occur where a nullity (Nothing) check will pass but, just after that, the Socket will be disposed and set to null)

In your StopServer method, remember to set the Socket to Nothing (after closing the socket), which will signal that the socket has been disposed. You should also check to see that the listener is not Nothing before running any methods on it (which would be your Accept and AcceptCallback methods), making sure to catch NullReferenceExceptions for that occasional race condition.
Here's a basic model as to what your Accept method will look like. This is a similar model to the rest of the code, though.
Private Shared Sub AcceptCallback(ar As IAsyncResult)
    Dim listener As Socket = DirectCast(ar.AsyncState, Socket)

    If listener Is Nothing Then Return

    Try
        Dim newClient As Socket = listener.EndAccept(ar)

        Receive(newClient)
    Catch ex1 As SocketException
        Return
    Catch ex2 As ObjectDisposedException
        Return
    Catch ex3 As NullReferenceException
        Return
    End Try

    Accept(listener)
End Sub


text:
Q: Sympy fails to integrate the product of a piecewise continuous function and a complex function across the discontinuity If I do:
from sympy import *
x, L = symbols('x L', real=True)
f = Piecewise((1, x<=0), (-1, x<1), (0, True))
g = exp(-x * 1j)
integrate(f * g, (x, 0, L))

I get:

Piecewise((1.0*I*exp(-1.0*I*L) - 1.0*I, L <= 0), (-1.0*I*exp(-1.0*I*L) + 1.0*I, L < 1), (-1.0*I*exp(-1.0*I) + 1.0*I, True))

But if I change the last line to:
integrate(f*g, (x, L/2, L))

I get:

Integral(Piecewise((exp(-1.0*I*x), x <= 0), (-exp(-1.0*I*x), x < 1), (0, True)), (x, L/2, L))

Any insight would be appreciated!

A: I guess it's not implemented yet. It probably doesn't know how to deal with the case where both limits are symbolic. You should report it.
A workaround is integrate(f*g, (x, 0, L)) - integrate(f*g, (x, 0, L/2)).


text:
Q: TypeScript's conditional always return never I have a type that can have multiple vendors within, like so:
{ data: { vendor1?: {} } | { vendor2?: {} } }

I thought that creating a conditional type to make sure that it's there will be suiting, unfortunately I am always getting never. My current type looks like this:
type Mapping<T> = T extends { vendor1: unknown } ? T["vendor1"] : never;

And usage:
function someFn(input: Mapping<{ data: { vendor1?: {} } }>) {
  return input //never
}

Also, I tried with
function someFn(input: Mapping<{ data: { vendor1?: {} } }>) {
  if ("vendor1" in input) {
    return input // still never
  }

}

I understand that this is because vendor1 is always optional, but I thought this is what conditionals are for. What can I do with this?


text:
Q: Rails: Elasticsearch has indexed records that have been removed from database Hi Im having toruble with Elasticsearch.
I have a model and Im using
include Tire::Model::Search
include Tire::Model::Callbacks

for index the records that are created, but for some reason when I test the search it shows me 404 page not found error
then checking the server logs I could notice that elasticsearch has indexed data that does not exists in my database, it means that I deleted some records of that model but elastic search still has those records indexed so when I try to search it finds those records that are not in my database now so that's why i get that page not found error, also I tried in the console and I get the error
ActiveRecord::RecordNotFound: Couldn't find Ofert with 'id'=3

So how to maintain records synchronized with the indexed data at elasticsearch? I mean, I want that when I delete a record it also should be removed from index at elasticsearch
Thanks for you help

A: Well, what you have to do is delete the indexes and create them again, however we do not recommend do this in production.
First delete all the indexes of you desired model in this case ofert
Tire.index("*oferts").delete

Then you will get the following exception: IndexMissingException[[products] missing]
That's because you are trying to look for an index that does not exist, then you just need to create it again:
rake environment tire:import CLASS='Ofert'

The above command will create the index and also import all your already created records to the ElasticSearch indexes.
We hope have helped you.


text:
Q: Can someone help me identify why C# tooltips show when they shouldn't? I have tool tips running on a C# form and i have a checkbox to disable them showing up.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBox1.Checked)
    {
        Tool_Tips = false;
    }
    else
        Tool_Tips = true;
}

where Tool_Tips is a Global public bool.
each time I hover over a button I use the code:
private void Edge_Down_B_MouseHover(object sender, EventArgs e)
{
    if (Tool_Tips)
    {
        Tool_Tip(Tool_Help.Edge_Down, Edge_Down_B);
    }
}

my problem is that i have 4 buttons out of like 30 that will display a tooltip regardless of the boolean value. If i put a breakpoint in their code it works correctly, but if i remove the breakpoint their tooltip will show up when it shouldnt. I did clean build of release mode, rebuilt the project and tried debug mode and they continue to show a tooltip when they shouldnt.
I even changed the code of those 4 buttons to look like:
private void BlackandWhite_B_MouseHover(object sender, EventArgs e)
{
    if (Tool_Tips)
    {
        if (!checkBox1.Checked)
            Tool_Tip(Tool_Help.BlackWhite, BlackandWhite_B);
    }
}

and they still show up in normal running mode. they won't show up if i place a breakpoint in.
Can anyone tell me why?
EDIT:
if i run my program, it will start with tooltips disabled with the checkbox checked. I will uncheck the box and i will see tooltips. if i recheck the box to disable the tooltips, the tooltips i have viewed will still show up even though they are disabled.

A: first of all, make sure there aren't any other event handlers attached to those 4 buttons' Click.
after that try changing your method as:
    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        Application.DoEvents();
        Tool_Tips  = !checkBox1.Checked;
    }

the events might had gotten fired before the checkbox have been checked.
and if that did not work either, inside your Tool_Tip method write:
if (checkbox1.Checked) return;

and if none of those helped, shoot me in the head :D!
before shooting me, do this:
in debug mode disable(or delete) all your breakpoints and put one just in your Tool_Tip method's first line.
make the bug show up and your breakpoint be hit.
then from the debug menu, open Call Stack and check that from where your method has been called. this might lead you to the problem, because I think you method is being called from an unwanted point of code.


text:
Q: Saving *.asc files as Excel files I have *.asc files to open, reformat, and then save as an Excel file with the same name as the original (with the xls extension).
I used the Macro Recorder and code I found online to open individual files and reformat them as desired. That part of the code works.
I cannot save as an Excel file. It gives me the Run Time error of 1004 Method 'SaveAs' of object '_Workbook' failed.  I have tried lots of different code I found online (still in there, just commented out) but none work.
Two questions:

*

*Can you offer suggestions to fix the SaveAs problem?

*Can you offer suggestions of how to automate the opening and saving of all the files in one folder?
Here is the code I have:
Sub OpenFormatSave()
'
' OpenFormatSave Macro
'

Dim StrFileName As String
Dim NewStrFileName As String
    ChDir _
        "C:\Users\Owner\Documents\work_LLRS\GoM\NASA_data\Satellite_files_GoM_3Dec2012"
    StrFileName = Application.GetOpenFilename("NASA Files (*.asc), *.asc")
    If TypeName(StrFileName) <> "Boolean" Then
        Workbooks.OpenText Filename:=StrFileName, _
        Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=False, _
        Comma:=False, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _
        Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), _
        Array(9, 1), Array(10, 1)), TrailingMinusNumbers:=True
    End If
    Rows("1:1").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "Year"
    Range("B1").Select
    ActiveCell.FormulaR1C1 = "Day_of_Year"
    Range("C1").Select
    ActiveCell.FormulaR1C1 = "Longitude"
    Range("D1").Select
    ActiveCell.FormulaR1C1 = "Latitude"
    Range("E1").Select
    ActiveCell.FormulaR1C1 = "Chla_mg_m-3"
    Range("F1").Select
    ActiveCell.FormulaR1C1 = "POC_mmolC_m-3"
    Range("G1").Select
    ActiveCell.FormulaR1C1 = "SPM_g_m-3"
    Range("H1").Select
    ActiveCell.FormulaR1C1 = "aCDOM355_m-1"
    Range("I1").Select
    ActiveCell.FormulaR1C1 = "DOC_mmolC_m-3"
    Range("J1").Select
    ActiveCell.FormulaR1C1 = "L2_flags"

    Columns("A:B").Select
    Selection.NumberFormat = "0"
    Columns("C:D").Select
    Selection.NumberFormat = "0.0000"
    Columns("E:E").Select
    Selection.NumberFormat = "0.000"
    Columns("F:F").Select
    Selection.NumberFormat = "0.0"
    Columns("G:H").Select
    Selection.NumberFormat = "0.000"
    Columns("I:I").Select
    Selection.NumberFormat = "0.0"
    Columns("J:J").Select
    Selection.NumberFormat = "0.00E+00"

'Mid(StrFileName, 1, InStrRev(StrFileName, ".")) = "xlsm"

'With ActiveWorkbook
     'NewStrFileName = Replace(.StrFileName, ".asc", ".xls")
   ' .SaveAs Filename:=FullName, FileFormat:=xlsx, AddToMRU:=False
   ' .Close SaveChanges:=True
'End With

StrFileName = ThisWorkbook.Name
GetName:
StrFileName = Application.GetSaveAsFilename(NewStrFileName, _
    fileFilter:="(*.xlsm), *.xlsm, (*.xlsx), *.xlsx,(*.xls), *.xls")

' FileMonth is the Workbook name, filter options to save a older version file
'If Dir(NewStrFileName) = "" Then
 '   ActiveWorkbook.SaveAs NewStrFileName
'Else
 '   If MsgBox("That file exists. Overwrite?", vbYesNo) = vbNo Then GoTo GetName
  '  Application.DisplayAlerts = False
   ' ActiveWorkbook.SaveAs Filename:=NewStrFileName, FileFormat:=xlsx, AddToMRU:=False
    'Application.DisplayAlerts = True
'End If
    'ActiveWorkbook.Close SaveChanges:=True

ActiveWorkbook.SaveAs Filename:=NewStrFileName, FileFormat:=xlsx, CreateBackup:=False

'With ThisWorkbook
    'FullName = Replace(.StrFileName, ".asc", ".xlsx")
    '.Save
    '.SaveAs StrFileName, FileFormat:=xlsx
    '.Close
    'SaveChanges:=True
'End With

'StrFileName = Split(ActiveWorkbook.FullName, ".xls")(0)

'ActiveWorkbook.SaveAs Filename:="...", FileFormat:=xlsx, AddToMRU:=False
'ActiveWorkbook.Close SaveChanges:=True

'ActiveWorkbook.Save
End Sub

A: Change the FileFormat portion of your SaveAs method to this:
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

A: To iterate through all the files in a folder, you have two options.

*

*Use the built-in VBA Dir function.

*Use methods in FileSystemObject.

I'll give an example of Dir because it doesn't require adding a reference in your VBA project. Unfortunately the Dir interface is a lot less intuitive and less modern than FileSystemObject.
Dim path As String

path = Dir("C:\Users\example\Documents\AscFiles\*.asc")
Do
    If path = vbNullString Then Exit Do

    ' do something with path here
    Debug.Print path

    path = Dir
Loop

A: You have two variables StrFileName (presumably intended as the current filename) and NewStrFileName (presumably intended to be the new filename).
In this piece of code:
StrFileName = Application.GetSaveAsFilename(NewStrFileName, _
    fileFilter:="(*.xlsm), *.xlsm, (*.xlsx), *.xlsx,(*.xls), *.xls")

you have used these variables the wrong way round. The suggested filename when the "Save As" dialog opens is based on NewStrFileName but this has never been given a value and is thus an empty string "". The value chosen by the user is then saved into StrFileName
When you come to save the file with this code:
ActiveWorkbook.SaveAs Filename:=NewStrFileName, FileFormat:=xlsx, _
    CreateBackup:=False

the NewStrFileName variable still contains "" and thus you are trying to save a file without giving it a name which obviously produces an error.
For a simple fix, just swap the two variables in the call to GetSaveAsFilename:
NewStrFileName = Application.GetSaveAsFilename(StrFileName, _
    fileFilter:="(*.xlsm), *.xlsm, (*.xlsx), *.xlsx,(*.xls), *.xls")

This is not the best way to achieve what you want but it should at least work

A: here is a very simply code to convert a folder of ASC files to Excel files. It also works with CSV files. So all you have to do is change the .asc to .csv
Just make sure you set the delimiter to TAB wherever you are getting the data from.
Sub import_ascFile()

    Dim file As FileDialog
    Dim filePath As String
    Dim text As String
    Dim wsheet As String

    Application.DisplayAlerts = False
    Application.StatusBar = True

    wsheet = ActiveWorkbook.Name

    Set file = Application.FileDialog(msoFileDialogFolderPicker)
    file.Title = "Folder Selection:"

    If file.Show = -1 Then
        filePath = file.SelectedItems(1)
        Else
        Exit Sub
    End If

    If Right(filePath, 1) <> "\" Then filePath = filePath + "\"
        text = Dir(filePath & "*.asc")

    Do While text <> ""
        Application.StatusBar = "Converting: " & text
        Workbooks.Open Filename:=filePath & text
        ActiveWorkbook.SaveAs Replace(filePath & text, ".asc", ".xlsx", vbTextCompare), xlWorkbookDefault
        ActiveWorkbook.Close
        Windows(wsheet).Activate
        text = Dir
    Loop

    Application.StatusBar = False
    Application.DisplayAlerts = True
End Sub


text:
Q: Can I play Bad Company 2 with Intel dual-core 2.8 GHz Can I play Bad Company 2 with the following hardware?

*

*Intel dual-core 2.8 GHz CPU

*2GB RAM

*512MB external graphics card

*Windows XP, service pack 2

A: Your system is capable of running the game. Check out the minimum and recommended system requirements for Battlefield: Bad Company 2.
Minimum System Requirements:
OS: Windows XP
Processor: Core 2 DUO @ 2 GHz
Memory: 2 GB
Hard Drive: 15 GB for Digital Version, 10 GB for Disc Version
Video Memory: 256 MB (NVIDIA GeForce 7800GT/ATI X1900)
Sound Card: DirectX Compatible
DirectX: 9.0c
Recommended System Requirements:
OS: Windows Vista/7
Processor: Any Quadcore Processor
Memory: 2 GB
Hard Drive: 15 GB for Digital Version, 10 GB for Disc Version
Video Memory: 512 MB (NVIDIA GeForce GTX 260)
Sound Card: DirectX Compatible
DirectX: 10

A: Yeah, but it'll be slow.
You can get a  good increase in frames by OCing your processor into the 3+Ghz range.
Unless of course your GPU isn't powerful enough and bottlenecks your CPU. More information about your graphics would be helpful. A model number would tell us a lot more about it's capabilities.


text:
Q: NPN: Not fully sinking to GND I'm using an NPN to pull a 12v (5mA) signal low from an MCU (logic level). My problem is that when I pull the 12v line low, 7.4v are still present at the 12v side of the line using the circuit below:

When I remove R2 and connect the signal directly to the collector pin on the NPN, about 110mV are still left on the line. See below:

Why isn't the NPN fully pulling the line low, and what can I do to fix it?

A: Most of the commenters so far seem to think that the line you labeled "12V" is a power supply. However, I take it that you mean that it is a control signal that is pulled up to 12V — presumably through a pullup resistor of 2400 Ω, since you also specify a current of 5 mA.
Your second circuit is correct, and 110 mV is perfectly reasonable for a saturated NPN transistor @ 5 mA. If your equipment really requires a lower voltage drop than that, then you'll have to try either a logic-level MOSFET or a mechanical relay. Are you saying that the radio is failing to mute using the transistor?

A: The NPN should pull the signal line down when enabled to the 10mV's range. In the second schematic you show an NPN connected directly to the 12V line. This would dissipate approximately 1 watt which is exceeding the absolute maximum rating of the part and probably causing it to fail.
Check the 2n3094 with a multimeter, if it's bad replace it (or just replace it with a new one). IF it looks good then check the resistor or the wiring. Do a conductivity test on the circuit with the meter to make sure it matches the schematic.


text:
Q: Storing Value instead of array in Codeigniter Storing radio button value in array (temporary storage). Created 10 set of question those 10 sets having 4  options for each. Now i am storing it in array to check how many radio buttons are checked and how many are correct.
Now the problem is currently having 10 question. As Database will be increase more question will be loaded.
So what to use another method or any other technologies for storing and checking them.
New to Codeigniter
Here is the code where I am storing (in controller) and redirecting it to model and then result view page
public function resultdisplay()
{
    $this->data['checks'] = array(
         'ques1' => $this->input->post('quizid1'),
         'ques2' => $this->input->post('quizid2'),
         'ques3' => $this->input->post('quizid3'),
         'ques4' => $this->input->post('quizid4'),
         'ques5' => $this->input->post('quizid5'),
         'ques6' => $this->input->post('quizid6'),
         'ques7' => $this->input->post('quizid7'),
         'ques8' => $this->input->post('quizid8'),
         'ques9' => $this->input->post('quizid9'),
         'ques10' => $this->input->post('quizid10'),
         'ques11' => $this->input->post('quizid11'),
);
    $this->load->model('quizmodel');
    $this->data['results'] = $this->quizmodel->getQueanswer();
    $this->load->view('result_display', $this->data);
}

Any other method, because it's not possible for writing code creating array every time for every new question and their radio button
Thank You

A: I would use a loop. Your radio buttons would look like this:
<input type="radio" name="question[1]['a']" value="a"> Question 1, option a

<input type="radio" name="question[1]['b']" value="b"> Question 2, option b

...
<input type="radio" name="question[2]['a']" value="a"> Question 2, option a

<input type="radio" name="question[2]['b']" value="b"> Question 2, option b

...

Since you mentioned pulling from a database, I assume you have a loop to print out the radio inputs.
Your FOR loop, to print out the HTML, would look something like this:
for($x = 1; $x <= 10; $x++) { // number of questions
    for($y = "a"; $y <= "e"; $y++) { // number of options for that question
        echo '<input type="radio" name="question['.$x.'][\''.$y.'\']" value="'.$y.'"> Question '.$x.'
';
    }
}

In PHP, the loop is this:
foreach($this->input->post('question') as $index=>$resultArr) {
// if radio is selected, then $resultArr[0] is the letter option selected and will match the
// $index value
}

A: For Dynamic one use this I have taken for 10 as an example, you can increase dynamically.
<form action="/index.php/welcome/getResponse" method="POST">
    <?php for($i = 0; $i < 10; $i++){ ?>

        <?php echo ($i+1)."."; ?>
        <?php for($j = 0; $j < 4; $j++){ ?>
            <?php echo chr(65+$j); ?><input type="radio" name="<?php echo 'n_'.$i; ?>" value="<?php echo chr(65+$j); ?>">
        <?php } ?>

    <?php } ?>
    <input type="submit" name="Submit">
</form>

and in controller
public function getResponse(){
    $resp = array();
    for($i = 0; $i<10; $i++)
    {
        array_push($resp,$this->input->post('n_'.$i));
    }
    print_r($resp);
}

Output (sample)
Array ( [0] => A [1] => B [2] => A [3] => B [4] => C [5] => A [6] => B [7] => C [8] => D [9] => B )


text:
Q: Install VMware workstation 7 on Windows 7 when I run the installer on my Windows 7 machine, I get the error:
bootstrap.lua was not found.

It works on Windows Vista.
Any ideas what causes this?

A: You may have a corrupt copy, I would recommend re downloading it direct from VMware.
I am using VMWare Workstation on Windows 7 without problems and have installed it a few times and never seen the error you are describing.

A: Regards "bootstrap.lua" not found
I had same Problem, but it worked after i download again the same
software (same date same version) via Downloadmanager directly from the VMWare Webpage.
So maybe first time i just got an invalid copy

A: Try running it in Vista compatibility mode if it worked on Vista. Make sure you're also running the installer as administrator as it needs a higher level of access to install the components.

A: Maybe you should, from an administrator account :

*

*uninstall VMWare Workstation and reboot

*download it again

*turn UAC off, as well as all antivirus and firewall products

*reinstall and reboot

*turn back on everything from step 3

*reboot


text:
Q: Increment value in DB when script is called I am trying to get all update an int value in my database whenever the script is called. Just to put this issue into perspective, I have a table called monthly_flagged, which gets all the flagged posts on my site, and sorts them into the month they were flagged. The script is called flagged_posts. When the script is called, the idea is that the column total_flagged in table monthly_flagged will go up by one (+1).
However, with my current approach, the number doesn't change. The value currently is 0, and I have flagged 3 posts, meaning total_flagged should equal 3, but it remains at 0 (no change).
Here is my approach:
$currentMonth = date('F'); // get month realtime
$currentYear = date ('Y'); // get year realtime

$check_month = mysqli_query ($connect, "SELECT * FROM monthly_flagged");
$get_month = mysqli_fetch_array ($check_month);
    $month = $get_month['month'];
    $year = $get_month['year'];
    $total_flagged = $get_month['total_flagged'];

// check if row exists in db for current month/year, else make it.
$checking_row = mysqli_query($connect, "SELECT * FROM monthly_flagged WHERE month = '$currentMonth' AND year = '$currentYear' LIMIT 1");
$check_return = mysqli_num_rows ($checking_row);

if ($check_return == 0){
    $make_row = mysqli_query ($connect, "INSERT INTO monthly_flagged VALUES ('', '$currentMonth', '$currentYear', '')");
}
if ($check_return == 1){
    $plusOne = $total_flagged +1;
    $update_total_flagged = mysqli_query ($connect, "UPDATE monthly_flagged WHERE month = '$currentMonth' AND year = '$currentYear'
                                                    SET total_flagged = '$plusOne'");
}

A: In your update statement you have the WHERE placed in front of the SET it should be:
UPDATE monthly_flagged
SET total_flagged = '$plusOne'
WHERE month = '$currentMonth' AND year = '$currentYear'

Or without the plus one variable:
UPDATE monthly_flagged
SET total_flagged = (total_flagged+1)
WHERE month = '$currentMonth' AND year = '$currentYear'

These kind of mistakes can be easily spotted if you implement something to catch MySQL errors (they're not magically displayed): More info on error reporting
P.S. Your code is vulnerable to SQL injections meaning other people can pretty much execute any SQL code on your database including deleting all. you should read up on prepared statements and how to use them! More info on prepared statements


text:
Q: Analyze network usage by Individual Applications/Process? Is there any tool on Win8 to analyze network usage by Applications/Process?
The total network usage seems to be running high, but there are no heavy downloads occuring.

A: *

*Ctrl + Alt + Del or right click superbar for task manager.

*Click on more details.

*Click on App History

There it will display the bandwidth used per app.


text:
Q: Getting Error on Readprocessememory on c# private static int FindPattern(byte[] Pattern)
        {
            Process[] P = Process.GetProcessesByName("example");
            if (P.Length == 0)
            {
                return -1;
            }
            if (modules == exmaple())
            {
                modules = P[0].MainModule.BaseAddress;
            }
            byte[] _Buffer = new byte[268435457];
            var tempVar = 0;
            ReadProcessMemory(P[0].Handle, modules, out _Buffer, _Buffer.Length, ref tempVar);

            int[] sBytes = new int[256];
            int Len = Pattern.Length - 1;
            var Dex = 0;

            for (int i = 255; i >= 0; i--)
            {
                sBytes[i] = Pattern.Length;
            }

            for (int i = Len; i >= 0; i--)
            {
                sBytes[Pattern[i]] = Len;
            }

            while (Dex <= _Buffer.Length - Pattern.Length)
            {
                int i = Len;
                while (_Buffer[Dex + i] == Pattern[i])
                {
                    if (i == 0)
                    {
                        return Dex;
                    }
                    i -= 1;
                }
                Dex += sBytes[_Buffer[Dex + Len]];
            }

            return -1;
        }

i tried a lot but i can't fix it.What did i did wrong?.
i am getting errors on this.Can anyone fix it for me please :
ReadProcessMemory(P[0].Handle, modules, out _Buffer, _Buffer.Length, ref tempVar);

A: Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication81
{
    class Program
    {
        [DllImport("kernel32.dll", SetLastError=true)]
        static extern Int32 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress,[Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead);
        const int SIZE = 268435457;
        static void Main(string[] args)
        {
            Process[] P = Process.GetProcessesByName("example");
            if (P.Length == 0)
            {
                return -1;
            }
            if (modules == exmaple())
            {
                modules = P[0].MainModule.BaseAddress;
            }
            IntPtr buffer = Marshal.AllocHGlobal(SIZE);

            var tempVar = 0;
            ReadProcessMemory(P[0].Handle, modules, out buffer, SIZE, ref tempVar);

            byte[] _Buffer = new byte[SIZE];

            Marshal.PtrToStructure(buffer, _Buffer);

            int[] sBytes = new int[256];
            int Len = Pattern.Length - 1;
            var Dex = 0;

            for (int i = 255; i >= 0; i--)
            {
                sBytes[i] = Pattern.Length;
            }

            for (int i = Len; i >= 0; i--)
            {
                sBytes[Pattern[i]] = Len;
            }

            while (Dex <= _Buffer.Length - Pattern.Length)
            {
                int i = Len;
                while (_Buffer[Dex + i] == Pattern[i])
                {
                    if (i == 0)
                    {
                        return Dex;
                    }
                    i -= 1;
                }
                Dex += sBytes[_Buffer[Dex + Len]];
            }

            return -1;

        }
    }
}


text:
Q: document.getElementByTag I already used document.getElementById, but it does not work any more. I want to get the value of 0,01€ but I can not. I want to save it in my NSString *price but how.
The HTML code is

0,01
EUR

My idea was
NSString *price = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('price.td').innerText;"];

A: The tagName in this case is 'td' not 'price.td', but if you run document.getElementsByTagName('id') you will get all the table cells in the page which is probably not what you want.
If the page has jQuery loaded in it you can use jQuery('.price td:first').text() to get the price.
If it doesn't have jQuery but you have control of the page you can add a class to it (12.44	) and get it with document.getElementsByClassName('my-price')[0].innerHTML.
If you don't have control of the page and it doesn't have jQuery you will have to find the  'price' row and then get its 1-st cell by using document.getElementsByClassName('my-price')[0].childNodes[0].innerHTML.

A: Also, a cleaner and more flexible approach is to use the Selectors API:
http://www.w3.org/TR/selectors-api/
document.querySelector('.price td:first').innerText


text:
Q: PCA for KNN: preprocess parameter in caret I am conducting knn regression on my data, and would like to:
a) cross-validate through repeatedcv to find an optimal k;
b) when building knn model, using PCA at 90% level threshold to reduce dimensionality.
library(caret)
library(dplyr)
set.seed(0)
data = cbind(rnorm(15, 100, 10), matrix(rnorm(300, 10, 5), ncol = 20)) %>%
  data.frame()

colnames(data) = c('True', paste0('Day',1:20))
tr = data[1:10, ] #training set
tt = data[11:15,] #test set

train.control = trainControl(method = "repeatedcv", number = 5, repeats=3)
k = train(True ~ .,
          method     = "knn",
          tuneGrid   = expand.grid(k = 1:10),
          trControl  = train.control,
          preProcess = c('scale','pca'),
          metric     = "RMSE",
          data       = tr)

My question is: currently the PCA threshold is by default 95% (not sure), how can I change it to 80%?

A: You can try to add preProcOptions argument in trainControl
train.control = trainControl(method = "repeatedcv", number = 5, repeats=3, preProcOptions = list(thresh = 0.80))


text:
Q: Starting the ValueAnimator outside the UI Thread I am trying to run android.animation.ValueAnimator from a separate thread from the UI thread. As I understand it, ValueAnimator can only be ran from the UI thread. Is there a proper way to start it from another thread to run on the UIThread?
I wrapped the ValueAnimator in an other class which holds a switch for the UI thread to periodically check.
private ArrayList<Animation> animators;
public void onResume(){
while(true)
        {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            checkAnimations();

        }
}
public void checkAnimations()
    {
        for(Animation va: animators)
        {
            if(va.animationHasStarted())
                va.actuallyStartTheAnimation();
        }
    }
public void RegisterAnimation(Animation valueAnimator)
    {
        animators.add(valueAnimator);
    }

The infinite loop causes the UI to stall. Do you know of a better implementation/design pattern.


text:
Q: Persist data for 24 hours I need to build a microservice that scrapes a message once a day and persists it somewhere. It does not need to be accessible after 24 hours (it can be deleted). It doesn't really matter where or how, but I need to access it from an Express.js endpoint and return the message. Currently we use Redis and MongoDB for data persistence. It feels wrong to create a whole collection for one tiny service, and I'm not sure of an application of Redis that would fulfill this task. What's my best option? Open to any suggestions, thank you!

A: You can use YUGABYTE DB,  and you can set TABLE LIVE= 24 Hours, then data will be deleted.

A: Redis provide an expiration mechanism out of the box. You can associate a timeout to a key, and it will be automatically deleted after the timeout has expired. Some official documentation here
Redis also provides logical databases, if you want to keep this expiring keys separated from the rest of your application. So you do not need to spin up another machine. Some official documentation here


text:
Q: Finding the main activity for an Android application I have a custom launcher and at times want to add a button to launch third party applications. To do this I need the apps package name, which is easy to find, but also the apps main or starting activity. I use this to create Intents that I pass to my app.
For example, to create an intent that launches Skype I use:
`new Intent().setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"))

I was able to find the name of the main activity by Googling around and as Skype is a popular app it showed up eventually.
I know that if I have the APK I can just open it and look at the androidmainifest , however I'm not sure how to get the APK's of some apps at all. For instance, I want to start this app from Google Play . I can see the package name, com.dbapp.android.mediahouse, however I'm not sure how to get the name of the main activity(I tried .MAIN).
I've looked at the Chrome extension apk downloader that supposendly allowed you to get APK's from Google Play but it appears to no longer work.
I know starting third party apps from a custom launcher is something that must be fairly common, but I'm not finding the answer when I search.
How do people typically handle this issue? Do you get the APK from the Google Play Store and if so how does one do that? Again, I know that I can get the activity from reading the manifest but I don't know how to get the APK itself in many cases. Any advice would be very much appreciated, thanks!

A: A launcher should be finding the MAIN/LAUNCHER activities advertised by apps on the device, by using PackageManager and queryIntentActivities(). Here is a sample app that implements such a launcher.
PackageManager pm=getPackageManager();
Intent main=new Intent(Intent.ACTION_MAIN, null);

main.addCategory(Intent.CATEGORY_LAUNCHER);

List<ResolveInfo> launchables=pm.queryIntentActivities(main, 0);

You then use that List<ResolveInfo> to display the available activities in a ListView, GridView, etc.

A: The PackageManager offers a method to get exactly what you want:
PackageManager.getLaunchIntentForPackage(String packageName)

A: You can use Intent intent = new Intent(android.content.Intent.MAIN);
or like the example behind to launch Maps and parse a URI:
String uri = "http://maps.google.com/maps?saddr=" + Utils.getLatitude(ShowDetails.this)+","+Utils.getLongitude(ShowDetails.this)+"&daddr="+userLatitude+","+userLongitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);


text:
Q: how to attach files that are stored in the database to the action mailer? you have mention about how to store files in database.
How to attach those files with mail using action mailer?
I have search many sites but not able to find the way to attach database files.
Everywhere the help of attaching files stored in file system is given.

A: It's not very different from sending attachments stored on disk.
Say you have a model Binary that corresponds to files in the file system. If it responds to content_type and data, then something like this should work:
class AttachmentMailer < ActionMailer::Base
  def attachment(recipient, binary)
    recipients recipient
    subject "Your requested file"
    from "example@example.com"

    attachment :content_type => binary.content_type, :body => binary.data
  end
end

# Wherever you want to e-mail something:
binary = Binary.find(:first)
Notifier.deliver_attachment("user@example.com", binary)

Of course, if you store your data differently or if the database columns are named differently, you should adjust the methods of the Binary class (or whichever class you use) in the above example.
I hope this helps.


text:
Q: Call Block's method in Helper I have Block class
class Abc_AddressManager_Block_Address_Book extends

Mage_Customer_Block_Address_Book {
       public function getAdditionalAddresses() {
          $addresses = $this->getCustomer()->getAddresses();
          return $addresses;
      }
}

And Helper class
class Abc_AddressManager_Helper_Data extends Mage_Core_Helper_Abstract {...}

want to call getAdditionalAddresses() in Helper
Have tried
$addressBookBlock = $this->getLayout()->getBlockSingleton('Abc_AddressManager_Block_Address_Book');
$_pAddsses = $addressBookBlock->getAdditionalAddresses();

A: you should not call block methods in helpers.
Try it the other way around.
Declare your method in the helper and call it in your block using
Mage::helper('helper/alias_here')->abc();


text:
Q: Cakephp 2.X Website Looks Cached I am trying to spin up a web application but Im having a really small problem and Im not sure how to handle it. I have did it before a long time ago but forgot (CLUTZ). When I try to access my application I see the login screen but it looks cached. I see a white page and I can see the links. The layout doesn't load for some reason. Like I said, this is a very small issue that I know someone can assist me with. If you give an answer please explain so that I can learn from it. Thanks a mil!

A: It sounds like what you're describing is CSS not loading. Doublecheck your <link href="…" rel="stylesheet"/> tags to ensure that they're pointing to the correct files.


text:
Q: How to await promise inside stream pipe I am using createReadStream of file module. I have a async operation which is reading from redis/db and based on saved value, I have to increment different counters. This is done inside the stream. The problem is end event is called on stream before the reading and increment operation have been completed.  I have to update the counter based on status store in redis/db.  I have tried using async/await  but nothing work.
    let fileStream = fs.createReadStream(process.env.FILE_PATH + file_name, { highWaterMark: 1024 * 1024 });
    fileStream.pipe(es.split()).pipe(
        es.mapSync(async function (line) {
            totalCount++;
            let extractData = line.split(",");
            let number = extractData[0];

            if (number) {
                number = number.replace(/['"]+/g, "");

              // HERE IT Check in redis or db
                const status = await checkNumberStatus(number, shortCode);

                tempStatus = status;

                if (status === "unsub") {
                    unprocessCount++;
                } else {
                       // add in redis
                    addToCronJob(number, campaign).then(() => {
                        processCount++;
                    });
                }
            }
        })
    );

    fileStream.on('end',async function (){

        campaign.cron_end_time= new Date();
        campaign.process_count= tempStatus === 'unsub'? processCount: ++processCount;
        campaign.total_count= totalCount;
        campaign.unprocess_count = tempStatus === 'unsub'? ++unprocessCount: unprocessCount;
        await campaign.save();
    })


text:
Q: Custom Name Entity Regognition I have the following sentence:
text="The weather is extremely severe in England"

I want to perform a custom Name Entity Recognition (NER) procedure
First a normal NER procedure will output England with a GPE label
pip install spacy

!python -m spacy download en_core_web_lg

import spacy
nlp = spacy.load('en_core_web_lg')

doc = nlp(text)

for ent in doc.ents:
    print(ent.text+' - '+ent.label_+' - '+str(spacy.explain(ent.label_)))

Result: England - GPE - Countries, cities, states

However, I want the whole sentence to take the tag High-Severity.
So I am doing the following procedure:
from spacy.strings import StringStore

new_hash = StringStore([u'High_Severity']) # <-- match id
nlp.vocab.strings.add('High_Severity')

from spacy.tokens import Span

# Get the hash value of the ORG entity label
High_Severity = doc.vocab.strings[u'High_Severity']

# Create a Span for the new entity
new_ent = Span(doc, 0, 7, label=High_Severity)

# Add the entity to the existing Doc object
doc.ents = list(doc.ents) + [new_ent]

I am taking the following error:
ValueError: [E1010] Unable to set entity information for token 6 which is included in more than one span in entities, blocked, missing or outside.

From my understanding, this is happening because NER has already recognised England as GRE and cannot add a label over the existing label.
I tried to execute the custom NER code (i.e, without first running the normal NER code) but this did not solve my problem.
Any ideas on how to Solve this problem?

A: Indeed it looks like NER do not allow overlapping, and that is your problem, your second part of the code tries to create a ner containing another ner, hence, it fails.
see in:
https://github.com/explosion/spaCy/discussions/10885
and therefore spacy has spans categorization.
I did not find yet the way to characterized a predefined span (not coming from a trained model)

A: Why do you need the new hash in the string store? Due to the underscore? Thx


text:
Q: Why numberOfSectionsInTableView is called twice in UITableViewController? Is there any other reason (than calling "reloadData") why numberOfSectionsInTableView is called twice? I did debugging and found, that it's get called twice during initial startup when no custom reloadData statements are called.
I have created the table with IB but does that might cause a problem?

A: Have a look at the call stack. you can see that this method is being called from two different scenarios.

A: Probably your tableView object may instantiate twice. Once i have encountered the same problem due to this.


text:
Q: Distribute matlab functions without source I have written a set of Matlab functions and I want to distribute it to few people for testing. But I do not want to reveal the source to them. All these people have matalb installed on their systems. So I don't want to make standalone executable from my functions. Ideally I want something like complied library files which the users can put in the matlab path & call the functions from their matlab prompt / matlab functions. Is it even possible ?
Edit: I have  matlab compiler toolbox. But the users won't be having access to matlab compiler toolbox on their matlab.

A: The standard way is using pcode. Look in the docs and remember to keep a copy of the source code elsewhere!


text:
Q: Manipulate DOM on success event of jquery plugin In success event of  a jquery plug in I need to manipulate the DOM and create/make visible some new html controls...
HTML..
<input type="file" name="fileupload" id="fileupload" />

<%=Html.ActionLink("TestA", "TestA", "ControllerA", new { Id = Id})%>

<%=Ajax.ActionLink("TestB","TestB","ControllerB", new { Id= Id})%>

JS:
<script type="text/javascript">
$(function () {

    $('#fileupload').uploadify({
        'buttonText': 'Upload',
        'auto': true,
        'multi': false,
        'swf': '/Uploadify/uploadify.swf',
        'uploader': '/ControllerA/LinkMethod',
        'formData': { 'Id': Id},
        'debug': false,
        'onUploadSuccess': function (file, data, response) {

         //Here I want to show two action links and disable/invisible the plugin.

        }
    });
});

A: Just call show() and hide() for the respective elements with the corresponding id value.
 'onUploadSuccess': function (file, data, response) {

        $('#MyIdForLink1').show();
        $('#MyIdForLink2').show();
        $('#pluginId').hide();

 }


text:
Q: React-Hook-Form Unregister not clearing values I have a form with a mapped array of subcomponents within it. I have toggles on each of the mapped sub-components and I'm attempting to unregister the subcomponent fields if the toggle = false. Following the docs and the example in the associated video (https://react-hook-form.com/api/useform/unregister/) I'm pretty sure I have everything set up as I should, and I even added shouldUnregister: true in the useForm call. Yet I'm still getting values stored for each field.
My only guess is that the subcomponent needs to unmount through the useEffect hook or else the component rerenders and then registers the field, however I have not found any clear way to do that, so I've tried passing an empty return statement, but that did not work either.
If anyone as any ideas or guidance, it would be greatly appreciated
parent form component
const EditVisit = ({ visitId, event, goals }) => {

/.../

const { register, unregister, handleSubmit, watch, control, setValue, formState: { errors } } = useForm({
    defaultValues: {
    visitStart: event?.visitStart,
    visitEnd: event?.visitEnd,
    location: event?.location,
    goals: [{
      title: '',
      marked: false,
      note: ''
    }]
    },
    shouldUnregister: true
  });

/.../

{goals && goals.map((goal, index) => (
          <GoalInput
            key={goal._id}
            goal={goal}
            index={index}
            register={register}
            control={control}
            errors={errors}
            visitGoals={event?.goals}
            setValue={setValue}
            unregister={unregister}
          />

      ))}

/.../
}

Child mapped component with the unregister:
function GoalInput({ goal, index, register, unregister, setValue, control, errors, visitGoals }) {
    const [toggle, setToggle] = useState(false)

/.../

useEffect(() => {
        if(toggle === false) {
            unregister(`goals.${index}.title`)
            unregister(`goals.${index}.marked`)
            unregister(`goals.${index}.note`)
        }

        return(() => {})
    }, [unregister, toggle])

    return (
        <>
        <FormControlLabel
          {...register(`goals.${index}.title`, goal.title)}
          value={goal.title}
          name={`goals.${index}.title`}
          control={
            <Switch
              key={index}
              {...register(`goals.${index}.marked`)}
              checked={goalData.marked || toggle}
              name={`goals.${index}.marked`}
              value={goalData.marked || toggle}
              onClick={console.log("marked? ", goalData.marked, "toggle ", toggle)}
              onChange={
                () => {
                    setToggle(!toggle);
                    setValue(`goals.${index}.title`, goal.title)
                }}

            />
          }
          label={goal.title}
        />

          {toggle ? (
            <>
            <Controller
              control={control}
              name={`goals.${index}.note`}
              id={`goals.${index}.note`}
              render={({field}) => (
                <TextField

                    index={index}
                    error={!!errors.note}
                    value={goalData.note || field.value}
                    onChange={(e)=>field.onChange(e)}
                    label="Progress Note"
                />
              )}
            />

            </>

          ) : <></>}
        </>
    )
}

CSB: https://codesandbox.io/s/trusting-williamson-qslkxf?file=/src/GoalInput.js


text:
Q: How to query a 2 table database in Codeigniter I have 2 tables in a single database.
For example:
Table 1 Columns:
id | code | name

Table 2 Columns:
id | code | family | etc.

How can I query both tables based on the overlapping code column to retrieve family column?
This is what I currently have:
$query = $this->db
    ->select('*')
    ->from('table 1')
    ->where('code', '123');

$query->get()->result();

The above query will retrieve the row(s) with code 123 but I'd like to get the corresponding family data from table 2. How can I do this?

A: Use join(). Something like:
$query = $this->db
    ->select('*')
    ->from('table1')
    ->join('table2', 'table1.code = table2.code')
    ->where('code', '123');

Docs on the function are here: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select

A: well you must add a sentence Join, it will let you query two tables.
$dataquery = array('table1.code' => '123'); //var in order to where
$this->db->select('table1.id As id1, table2.id As id2') //separate the ids with names
$this->db->join('table2.code','tabla1.code'); //code is overlapping
$query = $this->db->get_where('table1',$dataquery);

return $query->get()->result_array();//Return array if you want

Cheers!


text:
Q: Broadcasting a numpy.arange into a multi-dimensional array Suppose I have a 3 dimensional array of zeros
Y = np.zeros((2,3,4))

and I wished to broadcast a 1 dimensional array to it via the second dimension
X = np.arange(3)

such that the resulting multidimensional array was
Y = [[[ 0. 0. 0. 0.]
      [ 1. 1. 1. 1.]
      [ 2. 2. 2. 2.]]

     [[ 0. 0. 0. 0.]
      [ 1. 1. 1. 1.]
      [ 2. 2. 2. 2.]]]

What would be the most pythonic and efficient way of achieving this without loops (or even list comprehensions)? I wish to be able to scale this up with larger dimension sizes and run the code with the numba module, which does not compile with np.tile or np.repeat

A: You can reshape X firstly so that it can be broadcasted to Y.shape and then use np.broadcast_to method:
Y = np.zeros((2,3,4))
np.broadcast_to(X[:,None], Y.shape)

#array([[[0, 0, 0, 0],
#        [1, 1, 1, 1],
#        [2, 2, 2, 2]],

#       [[0, 0, 0, 0],
#        [1, 1, 1, 1],
#        [2, 2, 2, 2]]])

Another option is, create a new empty array with the same shape as Y and then assign X values to it:
new_X = np.empty_like(Y)
new_X[:] = X[:,None]

new_X
#array([[[ 0.,  0.,  0.,  0.],
#        [ 1.,  1.,  1.,  1.],
#        [ 2.,  2.,  2.,  2.]],

#       [[ 0.,  0.,  0.,  0.],
#        [ 1.,  1.,  1.,  1.],
#        [ 2.,  2.,  2.,  2.]]])

A: If you are always starting with a zeros array, just add x so that it will broadcast
>>> y + x[None, :, None]
array([[[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]],

       [[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]]])

General Broadcasting Rules
Or
>>> np.add(y, x[None, :, None], out = y)
array([[[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]],

       [[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]]])
>>> y
array([[[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]],

       [[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]]])
>>>

I wasn't sure you could broadcast using assignment but it sems you can:
>>> y[:] = x[None, :, None]
>>> y
array([[[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]],

       [[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]]])
>>> y[...] = x[None, :, None]
>>> y
array([[[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]],

       [[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 2.,  2.,  2.,  2.]]])
>>>


text:
Q: c++ assgin member variable via constructor with no "new" specifier cost calling copy method? int main()
{
    GameObject* go = new GameObject();
    go->transform->localScale = Vector3(1, 1, 1);
}

i wonder if im doing this in a neat way, that is, will the second row first create a Vector3 on stack memory and then copy the object to localScale(which means two object created)?
also, is it meaning that localScale is indicate to a reference in a stack memory if i do it in a local function?