text:
Q: Zend\Stdlib\Exception\BadMethodCallException Here the part of the stacktrace where I have a problem:
Zend\Stdlib\Exception\BadMethodCallException
File:
/var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Stdlib/Hydrator/ArraySerializable.php:28
Message:
Zend\Stdlib\Hydrator\ArraySerializable::extract expects the provided object to implement getArrayCopy()
Stack trace:
0 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Fieldset.php(631): Zend\Stdlib\Hydrator\ArraySerializable->extract(Object(BookList\Model\Book))
1 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(942): Zend\Form\Fieldset->extract()
2 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(303): Zend\Form\Form->extract()
3 /var/www/html/zf2/module/BookList/src/BookList/Controller/BookController.php(59): Zend\Form\Form->bind(Object(BookList\Model\Book))
The action method in my Controller that call bind:
public function editAction()
 {
   $id = (int) $this->params()->fromRoute('id', 0);
     if (!$id) {
         return $this->redirect()->toRoute('book');
     }

     try {
          $book = $this->getBookTable()->getBook($id);
      }
      catch (\Exception $ex) {
          return $this->redirect()->toRoute('book', array(
              'action' => 'index'
          ));
      }

    $form  = new BookForm();
    $form->bind($book); // this is the line 59 of BookController
    $form->get('submit')->setAttribute('value', 'Edit');

    $request = $this->getRequest();
    if ($request->isPost()) {
         $form->setInputFilter($book->getInputFilter());
         $form->setData($request->getPost());

         if ($form->isValid()) {
             $this->getBookTable()->saveBook($book);

             // Redirect to list of books
             return $this->redirect()->toRoute('book');
         }
    }

    return array(
        'id' => $id,
        'form' => $form,
    );
 }

I checked also the BookTable class to see the object returned from the resulset and it's an istance of Book.
Than I opened the ArratSerializable.php and check the object passed and tre response is:
BookList\Model\Book Object ( [id] => 5 [author] => Gotye [title] => Making Mirrors [inputFilter:protected] => )
So it's a correct object, why doesn't it work?

A: How the result is returned you generally tell that to the ResultSet object while building your model. You actually set a prototype there for returning your result set saying, hey! "Use this prototype" which is, in your case, Book model. It does have a method called getArrayCopy() which is missing. That actually rises error in this case. So please add this to the Book model thus
class Book
{
    // other properties and methods should be here

    // add this method here
    public function getArrayCopy()
    {
        return get_object_vars($this);
    }
}


text:
Q: Understand how caching helps in auto-refreshing Superset dashboards I have created a couple of Superset dashboards in a production environment, and I have read that it's recommended to use the Redis cache in production environments. A similar StackOverflow question here.
Firstly, I would like to understand what am I going to achieve by adding the following code in the superset_config.py
FILTER_STATE_CACHE_CONFIG = {
    'CACHE_TYPE': 'RedisCache',
    'CACHE_DEFAULT_TIMEOUT': 86400,
    'CACHE_KEY_PREFIX': 'superset_filter_',
    'CACHE_REDIS_URL': 'redis://localhost:6379/2'
}

Secondly, I would like to know how can I auto-refresh a superset dashboard permanently and not only for the current session option which is available. Is there any way? (similar question in this thread).
Thanks in advance for your help.
-- UPDATE 26.07.2022 (after more research)
Reference links: official doc, issue 390
I have added the following dictionaries in my superset_config.py file:
CACHE_CONFIG: CacheConfig = {
    'CACHE_TYPE': 'RedisCache',
    'CACHE_DEFAULT_TIMEOUT': int(timedelta(days=1).total_seconds()),
    'CACHE_KEY_PREFIX': 'superset_cache_',
    'CACHE_REDIS_URL': 'redis://redis:6379/2'
}

# Cache for datasource metadata and query results
DATA_CACHE_CONFIG: CacheConfig = {
    'CACHE_TYPE': 'RedisCache',
    'CACHE_DEFAULT_TIMEOUT': int(timedelta(days=1).total_seconds()),
    'CACHE_KEY_PREFIX': 'superset_data_',
    'CACHE_REDIS_URL': 'redis://redis:6379/3'
}

FILTER_STATE_CACHE_CONFIG: CacheConfig = {
    'CACHE_TYPE': 'RedisCache',
    'CACHE_DEFAULT_TIMEOUT': int(timedelta(days=1).total_seconds()),
    'CACHE_KEY_PREFIX': 'superset_filter_',
    'CACHE_REDIS_URL': 'redis://redis:6379/4'
}

EXPLORE_FORM_DATA_CACHE_CONFIG: CacheConfig = {
    'CACHE_TYPE': 'RedisCache',
    'CACHE_DEFAULT_TIMEOUT': int(timedelta(days=1).total_seconds()),
    'CACHE_KEY_PREFIX': 'superset_explore_',
    'CACHE_REDIS_URL': 'redis://redis:6379/5'
}

The superset app started successfully and when I do a dashboard refresh I can see the query running in redis-cli. My concern is that every time I apply filters on the dashboards the data is re-cached. Shouldn't the caching be applied once for every filter in the datasource, so when I apply filters superset won't have to hit the DB to fetch new records.

A: I'm new to Superset and caching, but here's my understanding.
If a reader opens a report that has recently been cached, instead of the report being run again, a cached version is fetched from Redis.  Redis can store and transmit data faster than a relational database - that's one advantage.  This reduces traffic on the database as well.
The other advantage is that the cached report doesn't need to be re-computed, saving the need to run a potentially long-running and expensive query on your source database.
You can watch this happen by entering your Redis instance (for Docker, that means entering the container with docker exec -it superset_worker /bin/bash) and then running redis-cli.  You can then run MONITOR to see all the transactions that are happening.  And in the main Superset app, you can see when a report is fetched from the cache.  Open those and then reload reports in your browser to generate the activity.
Your block of code would set up caching only of filters.  You need similar blocks of code to set up filters for data, etc.  Check the config.py file to see all the cache values that can be overwritten, then supply blocks of code similar to the one you have in your post for the other caches.
Here's a related post from Chartio, a Business Intelligence company that closed after being acquired, about the role of caching in serving their reports more efficiently.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to connect to WiFi Ubuntu 15.10 I am new here and new with Ubuntu. I have version 15.10, connected to my macbook pro retina. I am trying to get wifi to work, but no networks are detected on my computer, so I am using an ethernet cable. I'm sure there are some drivers I am supposed to download, but I can not find them. Can someone help me find the drivers I need or help me otherwise?
I can not use a different version of Ubuntu, because the program I need to run is specifically for 15.10. My computer has a BCM4360 802.11ac Wireless Network Ada. pter


text:
Q: I cant get the birth year of user and friends(javascript sdk, fb api) I am trying to get birthday year to calculate age but birthday.year give me undefined.
Is there any other way to get age(not age_range) of user and friends or get birthday year?
Here is my code.
    function testAPI(){
        FB.api('/me?fields=name,email,birthday,location,age_range',function(response){
            if(response && !response.error){
                console.log(response);
                buildProfile(response);
            }

        FB.api('me/friends?fields=id,name,gender,first_name,birthday,location',function(response){
                if(response && !response.error){
                    console.log(response);
                    buildfriends(response);
            }
              }
            );

    }
    //user info
    function buildProfile(user){
        let profile=`

${user.name}

User Id: ${user.id}

Email: ${user.email}

Birthday: ${user.birthday.year}

User Location: ${user.location.name}

        `;
            document.getElementById('profile').innerHTML = profile;
    }

    //friends info
    function buildfriends(friends){
        let friendlist='
Friend List
';
        for(let i in friends.data){
                friendlist +=`

                        ${friends.data[i].name}

                        ${friends.data[i].id}

                        ${friends.data[i].first_name}

                        ${friends.data[i].gender}

                        ${friends.data[i].birthday}

                `;
        }
        document.getElementById('friends').innerHTML=friendlist;
    }
    }


text:
Q: jQuery.validate killing character counter after it fires After extensive searching on this matter, I have been unable to find an answer on my own for an issue I'm experiencing where the jQuery validation plugin is cannibalizing a character count plugin I'm using for an SMS-via-PHP form.
If you get into the form, on the front-end, and start typing in the text area, the counter works just fine, and of course the validation won't fire since there's text in the element... but, in the interest of testing, if you try to submit the form without a message, the validation fires, and the error message is displayed relative to the textarea, and when you input copy, the validation message goes away, but the character counter no longer works.
Here's the character counter I'm using: http://cssglobe.com/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas/
Here's the way I have my script laid out:
$(function(){
    //irrelevant functions have been omitted

    $("#smsMessage").charCount({
        allowed:110,
        warning:10,
    });
    $('form').validate();
});

I even tried re-firing the counter function, as a callback to the validation, but that just resulted in a duplicate, non-functional counter being placed next to the textarea.
$(function(){
    //irrelevant functions have been omitted

    $("#smsMessage").charCount({
        allowed:110,
        warning:10,
    });
    $('form').validate({
        invalidHandler: function(form, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                $("#smsMessage").charCount({
                    allowed:110,
                    warning:10,
                });
            }
        }
    });
});

Admittedly, this is my first solo webDev project in a while -- it's for my fiancee and my wedding site, so I'm trying to class it up a bit. If there's any way to have the counter and validation play nicely together, that would be great. If not, it's not exactly the end of the world, but it's still less than ideal.

A: The problem is that your counter plugin is not very smart about keeping track of where the counter is.  It creates the counter by putting it after the text area.  The validate plugin does the same thing with it's error messages.  The easiest fix will be to tell the validate plugin to put it's errors somewhere else.  Try this:
$('form').validate({
    errorPlacement: function(error,element){
        if (element.attr('id') == 'smsMessage'){
            error.insertAfter(element.next());
        } else {
            error.insertAfter(element);
        }
    }
});

I made a working example so you can try it out:  http://jsfiddle.net/ryleyb/6HKuq/


text:
Q: PHP: Filtering and posting a text file I have a text file that contains a persons surname, address, time of accident and reason of accident separated by a white space in a line. I need to filter this file by only the people that have called in at least two times for the same reason and echo it.
I'm fairly new to PHP so I would like a simple way. :)
Thank you.
EDIT:
I haven't tried anything since I have no clue how to even filter file contents.
$data = array($_POST['surname'], $_POST['address'], $_POST['time'], $_POST['reason']);
$info = implode("   ", $data)
$info .= "\r\n";
serialize($info);
file_put_contents("data.txt", $info, FILE_APPEND);
serialize($info);

This is how I wrote it into a file.
I imploded the file because I needed to make them separated by 3 white spaces, but it no longer matters so I can just keep the array.
The expected output should be something like this:
Surname   Address   Time   Reason
Adams   Railroad 5   13:20   Heart Attack
Adams   Railroad 5   23:35   Heart Attack

It would only need to repeat the same people that have matching Surnames and Reasons.

A: Update
your text file contains string, entries seprated by line brakes and values by three spaces (actually html coded spaces).
Here we read whole txt file in,(some could do this line by line):
$whole_string = file_get_contents('data.txt');

So firstly we get each line:
$entries = explode('\n',$whole_string);

Then value arrays are pushed:
$whole_ar = array();
foreach($entries as $e){
   $whole_ar[] = explode('   ',$e);
}//if 3 spaces in file are in html

We get:
array(
    array(
    'name','date','etc..'
    ),
    array(
    'name2','date','etc..'
    ),
    array(
    'name2','date','etc..'
    )
)

You could store array in php file, for later to include('data.php'); like so:
$file = '<?php $whole_ar='.var_export($whole_ar, TRUE)."; ?>";
file_put_contents('data.php', $file);

Main answer on how to parse this array to target copies is iteritating or:
$answer = array_unique(array_diff_assoc($whole_ar, array_unique( $whole_ar)));

As I understand, you get information like this string when user calls in:
$newest = "Huchinson Estonia Tallin Geo street 13 2015.12.02 13:44 Gas leak"

You have this string in variable, like stated above.
Then you could explode string by space characters: $data = explode(" ",$newest); which gives you an array with number of values. First value will be a surname and last will be reason of accident.
Parse them out of array like this: echo $data[0];//this will be surname and echo end($data);//this will be accident type
Instead of echo you can assign these values to variables and look up if this surname AND accident is present in your database:
if($saved_before == $data[0].end($data)){
   echo "we are working on ".end($data).", be patient, dear ".$data[0];
}

p.s. dot (.) is for concatenating strings

A: If i understand well the txt file is a csv file that uses a space as the delimenter of the columns. So use use fgetcsv function to load columns of each row. Specify the blank space as the delimiter.

A: That should get you started:
function parseIt($line) { return str_getcsv($line, "   "); }
$all = array_map('parseIt', file('yourfile.txt'));
$names = array();
foreach ($all as $row) {
    $uniqkey = $row[0].$row[3];
    if (isset($names[$uniqkey])) {
        echo implode(" ",$row);
        $names[$uniqkey]++;
    } else {
        $names[$uniqkey] = 1;
    }
}

I noticed in your file writing code you use a delimiter of 3 white spaces so I used it in the example - you can set it to whatever you want in the str_getcsv(line, delimiter)
Explanation:

*

*Lines 1,2 - file() will read the file into an array that are passed through the function parseIt() this function will parse the line and return an array of the line value.

*Line 3 - The array $names will act our memory, at the end it will hold all names + reason as keys and the value will be the counter of occurrences.

*Line 4... - Loops through $all checks if the key exists in $names if it does it prints the row and moves the counter otherwise sets a new key in $names and set its value to 1 (counter).


text:
Q: Overriding Method with MouseListener I'm creating a Java program that uses Swing to draw a face, and then I am using MouseListener to respond to mouse clicks to make one of the eyes blink. How would I make one of the eyes blink using MouseListener? The method paint(Graphics g) can only be created once with that name, so if I want to repeat it and edit it under the MouseListener code with one of the eyes turned into a line for blinking, how would I do that?
Here is my code so far:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Sans extends JPanel {

public void paint(Graphics g) {

    super.paintComponent(g);
    setSize(650, 650);
    g.drawOval(110, 250, 500, 275);
    g.setColor(new Color(226, 222, 217));
    g.fillOval(110, 250, 500, 275);

    g.drawOval(475, 300, 75, 75);
    g.setColor(new Color(74, 199, 226));
    g.fillOval(475, 300, 75, 75);

    g.drawOval(505, 330, 15, 15);
    g.setColor(new Color(0, 0, 0));
    g.fillOval(505, 330, 15, 15);

    g.drawOval(175, 300, 75, 75);
    g.setColor(new Color(0, 0, 0));
    g.fillOval(175, 300, 75, 75);

    g.drawOval(205, 330, 15, 15);
    g.setColor(new Color(232, 255, 243));
    g.fillOval(205, 330, 15, 15);

    g.drawOval(350, 375, 20, 50);
    g.setColor(new Color(0, 0, 0));
    g.fillOval(350, 375, 20, 50);

    g.drawArc(290, 360, 150, 150, 180, 180);
    g.setColor(new Color(255, 255, 255));
    g.fillArc(290, 360, 150, 150, 180, 180);
}

public static void main(String[] args) {

    Font font = new Font("TimesRoman", Font.PLAIN, 15);

    JFrame frame = new JFrame();
    Sans spook = new Sans();
    frame.add(spook);
    frame.setSize(750, 750);

    frame.setTitle("I'VE GOTTEN A TON OF WORK DONE TODAY. A SKELE-TON.");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);
}

public class BlinkHandler implements MouseListener {

    public void mouseClicked(MouseEvent e) {

    }

    public void mousePressed(MouseEvent e) {

    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }
}

}


text:
Q: How to deploy a Vue app after using vue cli webpack I recently finished creating a Vue app that I wish to deploy on the internet. However, I can only open the project using node and running npm run dev. If I double click on the index.html file, I just see a blank page. How may I deploy my website so that the browser can render my Vue app?

A: If you used the vue-cli to generate the project, you should be able to run npm run build and get a minified, single .js file.
See here: http://vuejs-templates.github.io/webpack/commands.html
This will give you a dist folder with index.html and build.js. You should be able to open the html file and see your app.

A: Hoping it's usefull for someone, still:
Using @vue/cli 3, I had a simular result when copiing the dist to my localhost/test.
The build assumed all js and css file relative to the root while I was putting them relative to a subfolder 'test'.
adding the publicPath : "" did the trick to get rid of the preceeding '/'
in vue.config.js I added : ( using proxy for dev with apache/php )
module.exports = {

    devServer: {
        proxy: 'http://localhost:80/proxy'
    },

    configureWebpack: config => {
        if (process.env.NODE_ENV === 'production') {
            output: {
                 publicPath : "" // only for prod
            }
        } else { // dev
            // org, no changes
        }
    }
}

See also
https://alligator.io/vuejs/using-new-vue-cli-3/
https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md#inspecting-the-projects-webpack-config


text:
Q: Token based authentication and authoriozation for Apache Tomcat servlets Background: Our current technology architecture includes Tomcat Servlets that do backend activities and Codeigniter PHP which handles the presentation layer. So when a particular page is loaded, the Codeigniter View invokes the Controller which constructs the servlet URL with necessary input parameters and invokes the URL and gets the response and passes it back to the View so that the page is rendered.
Issue: User information and login credentials are stored in database and is validated by PHP front end. There is no authentication for the Tomcat servlets and in cases where we need user information in the backend, the user id is passed as a parameter to the backend.
Currently Tomcat and PHP resides on the same server and we have used firewall port based restrictions to ensure that servlets can be invoked only from within the server to secure the servlets.
Help required : We are looking to implement token based authentication and authorization mechanism for the servlets. If we can get some sort of existing library that we can easily plug-in to our servlets, that would be ideal. Otherwise please guide what would be the best solution to implement without too much code changes but would effectively secure the backend servlets.

A: Cássio Mazzochi Molin have a nice articel about the topic : Token-based authentication with JAX-RS 2.0


text:
Q: How does the concept of a random variable come into play when sampling? I have an (intuitive) understanding of what a random variable and a sample are. However, I am not sure how a random variable is related to a sample.
Suppose we have a population of people. Sampling from that population means to take a subset (which we call "sample") of those people.
What can be considered a random variable while sampling, once we have a sample and when we take an element from this sample? How many random variables are involved in the process of sampling or once we have the sample?
I would appreciate seeing many real-world examples of the sampling process where you explain which and how many random variables are involved.

Notes

1. This question is different from What is the difference between random variable and random sample?.

2. Please, avoid defining what a random variable and sample are. I already know what they are and, if I forget the definitions, I can look them up again!

A: There are two major ways of approaching random sampling. One is parametric, assuming that each unit responds based on a function of their characteristics plus an error. This error is the random variable that @Robien1 describes.
The other method treats the responses received from units in the population as fixed constants. The random variable in this case is a 0/1 indicator variable for each unit in the population, indicating whether the unit is selected in the sample or not.
In survey analysis the first method is called the model-based, the second is called the design-based or model-assisted. The design-based method is useful if you have access to (or can build) a population frame.

A: Let us take a  human population of $N$ persons.
Among that population $N_0$ persons have blue eyes and let's call $p=\dfrac{N_0}{N}$ the proportion of blue-eyes persons.
If you pick « randomly » somebody in that population and associate the value 1 if that person has blue eyes and 0 otherwise, you are constructing a real random variable $X$ because il has uncertain issue.
To make it simple $X$ takes two values and $P(X=1)=p$, $P(X=0)=1-p$ ($P$ being  a measure of probability, the existence/construction of such  a probability is a big step, not necessary here, where the intuition makes it understable/acceptable).
For your sample, the $i$-th person picked is associated with a random variable $X_i$. All the $X_i$ follow the same law (of probability) called $B(p)$ (Bernoulli) : 1 with probability $p$, 0 with probability $1-p$).
So if you have a $n$-sample, you have a $n$ random variables associated
and what you handle in your real sample are issues of that variables: $X_1(\omega)=0$,
$X_2(\omega)=1$,
$\dots$,
$X_n(\omega)=0$ (for example)
Then the theory of probabilities give you some information
like $\dfrac{\sum\limits_{i=1}^nX_i}{n}\to p$ in a sense
if the variables are independant which in that case would be picking
each time a new personn in the whole population, otherwise they are dependant
but if the $n$-sample  picked is small in comparison with $N$ then you can approximate with independance.
To finish you get :
$x_1,\dots x_n$ in your sample
and the probability model consider it as
$X_1(\omega),X_2(\omega),\dots,X_n(\omega)$
where the $X_i$ follow the same law of probability and are most of the time mutually independants (or so-approximated)
I hope it answers your question.


text:
Q: Python ElementTree - Taking Element.Text from HTML form_input So I have a basic script which creates xml and adds it to a file:
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as etree

root = Element('ipaddress')
tree = ElementTree(root)
ipaddress = Element('ipaddress')
root.append(ipaddress)
ipaddress.text= **INSERT FROM FORM**
ipaddress.set('version', 'v4')

print etree.tostring(root)
tree.write("/root/Desktop/" + "xmlfile.xml")

It out puts like this on xmlfile.xml
<ipaddress><ipaddress version="v4">123.123.123.123</ipaddress></ipaddress>

I have a simple HTML Form element to handle it:
<form action="create_ticket" method="post">

                <input type="text" size="35" placeholder="Host IP"
                name="host_ip" class="form-control" required>

    <input type="submit" value="Submit">
</form>

The form is much larger with more inputs but this is the basic idea. It also serves a ticket through API by using another script.
How do I dynamically change the ipaddress.text value based on what the user inputs to host_ip on the form?
Thanks for your help!


text:
Q: How to check if current PC user is current logged on user? For security reasons we want to check if the current PC user is the actual logged on user. To do this we want the user to re-enter their password and check his credentials with the domain. How could we accomplish this?
Sofar we tried this:
public static Boolean Authenticate(String password)
{
    String user = WindowsIdentity.GetCurrent().Name;

    using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
    {
        return PrincipalContext.ValidateCredentials(user, password);
    }
}

But get a System.DirectoryServices.Protocols.LdapException, leaving the Environment.UserDomainName off also triggers this exception.
We also tried:
public static Boolean Authenticate(String password)
{
    String user = WindowsIdentity.GetCurrent().Name;

    using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Machine))
    {
        return PrincipalContext.ValidateCredentials(user, password);
    }
}

But this returns true on any password.

A: After some searching I came across this answer. Turns out the Domain name is included in WindowsIdentity.GetCurrent().Name. As found under the remarks in the documentation.
Giving this as a working solution:
public static Boolean Authenticate(String password)
{
    String user = WindowsIdentity.GetCurrent().Name; //Should be: DomainName\UserName
    String[] DomainAndUserName = user.Split(new Char[] { '\\' }, 2);

    if (DomainAndUserName.Length != 2) { return false; } // No DomainName ==> Wrong network;

    using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Domain, DomainAndUserName[0]))
    {
            return PrincipalContext.ValidateCredentials(DomainAndUserName[1], password);
    }
}


text:
Q: Which uses less memory in javascript, null or undefined? I have an array which contains a few million elements; nearly half of the indexes will be empty. What is the most memory efficient way of filling these empty indexes?
My limited understanding is that both are stored as strings of their name; and each char in a string requires 2 bytes. So null being 4 chars is 8 bytes; while undefined is 8 chars or 16 bytes. If this is the case would it be better to store these index as an empty string?


text:
Q: copy and paste data in VBA without range I have data like below

I want to fill last row with 0's. but the problem is every month number of rows will be changed.
I want to write a code that automatically adds 0's in the last column based on column A or B or C or D number of rows.

A: You should try something on your own... We usually help people improve their code, or correct things as does not work as expected.
Please, try the next code and confirm that it does what you need:
Sub FillZeroLastCol_Row()
  Dim sh As Worksheet, lastCol As Long, lastRow As Long
  Set sh = ActiveSheet 'use here the worksheet you need
  lastCol = sh.Cells(1, Columns.Count).End(xlToLeft).Column + 1
  lastRow = sh.Range("A" & Rows.Count).End(xlUp).row
  sh.Range(sh.Cells(1, lastCol), sh.Cells(lastRow, lastCol)).Value = 0
  'if you also need zero on the last row, this can be done in this way:
  sh.Range(sh.Cells(lastRow + 1, 1), sh.Cells(lastRow + 1, lastCol)).Value = 0
End Sub

It can be made to check if you already did it, by checking the last column/row content...


text:
Q: How to add a span tag to wrap the other string not in regex? How to  add a span tag to wrap the other string not in regex?
// This is english & some 中文 character 字元.

var str = 'This is english & some 中文 character 字元.'

var pattern = new RegExp(/[a-zA-Z0-9 _^!-~-]/);
console.log( pattern.test(str));

A: var str = "This is english & some 中文 character 字元.";
var regex = /([^a-zA-Z0-9 _^!-~-]+)/g;
console.log(str.replace(regex, '$1'));
// This is english & some 中文 character 字元.

I have used your regex with the following changes:

*

*Added capturing group by adding () so that matches can be captured

*Then use the captured group in replacement using $1

*Added a g flag for global which means all matches must be replaced instead of just the first one.

You might be interested in the regular expressions discussed here.


text:
Q: can I partly execute the code in Visual Studio? Can I partly execute the code in Visual Studio? I have a code and instead of doing the whole execution can I do it partly? For example a function

A: I don't think this is possible.
What you can do is feed the specific function you want to try with some parameters like:
private int Sum(int x, int y)
{
    return x+y;
}

You can write a code like:
int test = Sum(10, 12);

and use the debug to watch what happens.


text:
Q: I disabled my touchpad, and now there's no option to reenable it on Ubuntu 14.04 I installed Ubuntu 14.04 on my laptop(Lenovo Z400).  Last night I disabled the touchpad, because I was using external mouse. Today I tried reenabling the touchpad, but there isn't that option any more in the mouse settings.  I am just seeing the setting for Primary Button and Double Click speeds. Where did my touchpad go?

A: Try touchpad extension to re-enable and control your touchpad.


text:
Q: Linq with Logic I have  simple Linq statement (using EF4)
var efCars = (from d in myentity.Cars
         where d.CarName == inputCar.CarName
         && d.CarIdNumber == inputCar.IdNumber
         && d.Make == inputCar.Make
         select d.Car);

I want it to be smarter so that it will only query across one or more of the 3 fields IF they have values.
I can do a test before, and then have a separate linq statement for each permutation of valyes for inputcar
(i.e. one for all 3, one for if only carname has a value, one for if carname AND CarIdNumber has a value etc etc)
but there must be a smarter way
Thanks!

A: If "has no value" means null then you can use the null coalescing operator ?? to say take the first value if populated, otherwise take the second:
var efCars = (from d in myentity.Cars
where d.CarName == (inputCar.CarName ?? d.CarName
&& d.CarIdNumber == (inputCar.IdNumber && d.CarIdNumber)
&& d.Make == (inputCar.Make && d.Make)
select d.Car);

This basically says if a value exists it must match, otherwise treat it as matching
However if instead you're saying "when a special value (empty string) ignore it, otherwise match" then you can do one of two approaches (or possibly more!):
where (inputCar.CarName == "" || d.CarName == inputCar.CarName)

where (string.IsNullOrEmpty(inputCar.CarName) || d.CarName == inputCar.CarName)

A: For performance (when dealing with database queries) it can sometimes be beneficial to let EF generate queries based on the filters, instead of using one generic query. Of course you will need to profile whether it helps you in this case (never optimize prematurely), but this is how it would look if you dynamically build your query:
var efCars =
    from car in myentity.Cars
    select car;

if (inputCar.CarName != null)
{
    efCars =
        from car in efCars
        where care.CarName == inputCar.CarName
        select car;
}

if (inputCar.IdNumber != null)
{
    efCars =
        from car in efCars
        where care.CarIdNumber == inputCar.IdNumber
        select car;
}

if (inputCar.Make != null)
{
    efCars =
        from car in efCars
        where care.Make == inputCar.Make
        select car;
}

A: where (inputCar.CarName != null || d.CarName == inputCar.CarName) &&...


text:
Q: Performance: Store likes in PostgreSQL ArrayField (Django example) I have 2 models: Post and Comment, each can be liked by User.

*

*For sure, total likes should be rendered somewhere near each Post or Comment

*But also each User should have a page with all liked content.
So, the most obvious way is just do it with m2m field, which seems will lead to lots of problems in some future.
And what about this?

*

*Post and Comment models should have some
users_liked_ids = ArrayField(models.IntegerField())

*User model should also have such fields:
posts_liked_ids = ArrayField(models.IntegerField())
comments_liked_ids = ArrayField(models.IntegerField())
And each time User likes something, two actions are performed:

*

*User's id adds to Post's/Comment's users_liked_ids field

*Post's/Comment's id adds to User's posts_liked_ids/comments_liked_ids field
The questions are:

*

*Is it a good plan?

*Will it be efficient to make lookups in such approach to get "Is that Post/Comment` was liked but current user

*Will it be better to store likes in some separate table, rather then in liked model, but also in ArrayField

*Probably better stay with obvious m2m?

A: 1) No.
2) Definitely not.
3) Absolutely, incredibly not. Don't split your data up even further.
4) Yes.
Here are some of the problems:

*

*no referential integrity, since you can't create foreign keys on array elements, meaning you could easily have garbage values in an ID array

*data duplication with posts having user ids and users having post ids means it's possible for information to get out of sync (what happens when a user or post is deleted?)

*inefficient lookups in match arrays (your #2)

Don't, under any circumstances, do this. You may want to combine your "post" and "comment" models to simplify the relationship, but this is what junction tables are for. Arrays are good for use cases that don't involve foreign keys or the potential for extreme length.


text:
Q: How can I add a column to the primary key of a MySQL InnoDB table? I have tables foo and bar:
create table foo(a int, b varchar(10),
                 primary key (a));
create table bar(a int, c int, d int,
                 primary key (a,c),
                 foreign key(a) references foo(a));

Now I have a new column e that needs to participate in the primary key of bar. How can I do this? It seems I should be able to drop the primary key, add the column, and create a new primary key, but attempting to drop the primary key gives me:
mysql> alter table bar drop primary key;
ERROR 1025 (HY000): Error on rename of './mydb/#sql-1e08_16a273' to './mydb/bar' (errno: 150)

This only appears to be the case with primary keys that include a foreign key column.

A: This other stackoverflow question might help you out.
My guess would be you need to first drop the foreign key, then drop the primary.

A: Add the e column to the bar table and then update the primary key by issuing the following MySQL specific command :
ALTER TABLE bar DROP PRIMARY KEY, ADD PRIMARY KEY (a, c, e);


text:
Q: How can I wait until data comes in when reading data over Serial Port? QT C++ I need to read ID data through Serial Port. When I send the ID read command with the leather port, the ID data comes to me a little late. Therefore, when I try to split the data and display it on the screen, it comes up blank and the application closes itself. How can I wait until the data comes in?
void productDetail::on_pushButton_clicked()
{
    QSerialPortInfo info;
        QList<QSerialPortInfo> infoList = QSerialPortInfo::availablePorts();

           foreach(info, infoList) QTextStream(stdout) << info.portName();
        QString curport = info.portName();

   serial.begin(curport, 9600, 8, 0, 1, 0, false);

   if(serial.isOpen()){
       qDebug()<<"serial open";
       QString sendWC= "WR+1121"; //Read ID command
       serial.send(sendWC);
       QString serialID = serial.getString();

        serialID = serialID.trimmed();
         QStringList buffer_split = serialID.split(",");

             ui->IDlabel->setText(buffer_split[2]; //when I write this program closes

             }
   }

}

error: ASSERT failure in QList::operator[]: "index out of range",

A: Qt's QIODevice provides a signal readyRead (https://doc.qt.io/qt-5/qiodevice.html#readyRead)  which is emitted once every time new data is available for reading from the device.
In the productDetail class constructor, connect serial port readyRead signal to a slot.
connect(serial, &QSerialPort::readyRead, this, &productDetail::readData);

Define readData method as follows:
void productDetail::readData()
{
    const QByteArray data = m_serial->readAll();
}

For serial communication there is no guarantee that you will receive entire message data in a single read. I prefer to store the received data in a circular buffer and process the circular buffer in a separate slot.


text:
Q: Flume + HDFS-200 append The page https://cwiki.apache.org/confluence/display/FLUME/Getting+Started says that HDFS sink  supports appending but I havent been able to find any information on how to enable it, every examples are on rolling files. So, I would appreciate any information on how to make flume append to an existing file, if it's at all possible)
Update
One can set all rolling properties to 0, that will make flume to write into single file, but it doesnt close the file and new records are not visible to other processes.
There is a topic similar to mine: Flume NG and HDFS, Dmitry says that Flume doesnt support appending, but the answer is one year old and documentation says the opposite, so I thought maybe flume was improved or I'm misunderstanding something, any clues will be appreciated.
Update
I realized that the question is unclear so let me just describe what I'm trying to achieve:
I want logs to be written in one file and I want to be able to read them as soon as they're ingested into hdfs. At the moment I'm using Cloudera Impala to perform search queries and it doesnt see new events even though Flume is configured to flush them on disk immediately, at least that's how I believe. My investigations show that usually people use HBase for these purposes but as far as I understand, it's not effective for ad hoc search queries unless one uses external indexing like Solr. The problem is that I need a solution ASAP so I was hoping that maybe it can be done easier, for example Fluentd can append to existing file, but it works only with plain text files and I would prefer some binary format.

A: I havent been able to find a way to make Flume do what I wanted, so eventually I've decided to use Cloudera Search for logs streaming, specifically Solr for both ingestion and retrieval.
It seems that Flume doesnt have a capablity for real time ingestion in hdfs without creation of lots of relatively small files, hope they fix it in future.


text:
Q: CUDA ptxas warnings (Stack size for entry) I am getting the following warning which I dont understand when compiling CUDA code:
CUDACOMPILE : ptxas warning : Stack size for entry function
'_Z24gpu_kernel_get_3d_pointsiPK8RtmPointS1_PKfS3_P10RtmPoint3DPif' cannot be statically
determined.

The kernel prototype is:
__global__ void gpu_kernel_get_3d_points(int count1, const RtmPoint *pPoints1,
const RtmPoint *pPoints2, const float *PL, const float *PR, RtmPoint3D *pPoints3D,
int *pGlobalCount, float bbox)

All the pointers are pointers to device memory. I dont see why the compiler should have a problem determing the stack size. There are a few local variables in the kernel but not many. Any ideas? Does this warning matter?

A: This warning happens when a function is recursive. Cuda tries to allocate the stack space before the execution which is not a big deal, unless you are using recursion. The problem with it is that the stack size isn't predictible. The depth of the recursion isn't a known value so the memory that the stack will use isn't known. This warning isn't really relevant but if you exceed the GPU stack with your data, you must manually increase the stack size.

A: It seems like your kernel is dynamically allocating memory on the GPU heap using malloc() or the new operator. It may have an adverse effect on your kernel's performance.


text:
Q: Binding custom node addon to lua with extentions I have a large collection of asynchronous functions that I have in nodejs code that I would like to expose to lua.  The basic idea is that I would like to execute lua scripts and allow those scripts to call back into some of my  nodejs code, as well as asynchronously return a value from an executed lua script,
In this example myCustomNodejsAddon would be a custom addon that I write that knows how to bind lua and run lua scripts.  One outstanding question is how do I asynchronously return a value from a lua script?
Has anyone done something like this before?  I would be very interested in any pointers, thoughts, examples.
EDIT with better example:

-- user written lua script
getUser(1, function(err, user)
   if err then
      print('Error', err)
   else
      print('Found user with id', user.id)
      return ''
   end
end)

/*Create object with mapping of async functions*/
var callbacks = {
   "getUser": function(userId, cb) {
      db.Users.fetchById(userId).then(function(user) {
         cb(null, user);
      }, function(err) {
         cb(err, null);
      }
   }
};
myCustomNodejsAddon.provideCallbacks(callbacks);

/* user written lua script has been stored into `scriptSrc` variable */
myCustomNodejsAddon.execute(scriptSrc, function(returnValueOfScript) {
   console.log('done running user script: ', retrunValueOfScript);
});

A: More than one approaches to this problem comes to my mind.
The first would be to create a nodejs script that once executed read the program command line arguments or input stream and execute the code indicated by this channel and stream the response back in JSON format for example. This is the less invasive way of doing this. The script would be something like:
if(require.main === module){
   // asume first argument to be the source module for the function of iterest
   var mod = require(process.argv[2]);
   var fnc = mod[process.argv[3]];

   args = process.argv.slice(4);

   // by convention the last argument is a callback function
   args.push(function(){
       console.log(JSON.stringify(arguments));
       process.exit();
   })

   fnc.apply(null, args);
}

An example usage will be:
$ node my-script.js fs readdir /some/path

This will respond with something like [null, ['file1', 'file2']] acording with the files on /some/path. Then you can create a lua module that invoque node with this script and pass the parameters according with the functions you want to call.


text:
Q: How to use inner join in CakePHP models I have two tables that I want to INNER JOIN, I spent hours but I had no luck. I will be very please if some could help.
My first table: properties
id | room | price | location_id
My second table is: locations
id | country | province | district
Note: location_id in Properties is 'id' in Location
I want to use basic model associations like hasOne, belongsTo and so on.
What should I put in my models so that I can basically get the following result?
SELECT
    Property.room,
    Property.price,
    Location.province
FROM
    properties AS Property
INNER JOIN locations AS Location ON Property.location_id = Location.id

Thanks in advance!

A: The following model relation will generate the query you need.
class Property extends AppModel {

    public $belongsTo = array(
        'Location' => array(
            'type' => 'INNER'
        )
    );

}

Read more about model associations

A: Use the following code:
$this->Property->find('all', array('joins' => array(array('table' => 'locations',
                                   'alias' => 'Location',
                                   'type' => 'INNER',
                                   'conditions' => array('Property.LOCATION_ID = Location.ID')))));

A: Try this
class Location extends AppModel {

    public $belongsTo = array('Property'));

}

class Property extends AppModel {

    public $hasOne = array( 'Location'));

}

A: Try this :
class Variant extends AppModel {

    $this->bindModel(array('belongsTo' => array('Brand' => array('type' => 'INNER'))));

}

A: CakePHP does support a syntax for defining your own joins. It would be done like this, from the PropertiesController
$properties = $this->Property->find('all', array(
            'fields' => array('Property.*'),
            'joins' => array(
                array(
                        'table' => 'locations',
                        'alias' => 'Location',
                        'type' => 'INNER',
                        'conditions' => array(
                        'Property.location_id' =>'Location.id'
                        )
                    ),
                ),
            )
        );

Another Way You Can DO This
You would create a relationship with your Model, and use the containable behavior like below:
class Property extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array('Property');
}

class Location extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array('Property');
}

Then you can do this from the PropertiesController:
$properties = $this->Property->find('all', array(
    'contain' => array('Location')
));


text:
Q: Form validation problems I have a very strange problem. Inside form I have hidden input with value -1 and input field for username.
<form action="" method="POST" name="login" onSubmit="return Validate()">
  <input type="text" id="username"/>
  <input type="hidden" id="available" value="-1"/>
<  input type="submit" value="Send"/>
</form>

On submit function Validate() checks value of username input which mustn't be empty, and Validate() also checks value of available input which mustn't be valued -1.
function Validate(){

var a=document.getElementById("username").value;
var b=document.getElementById("available").value;

if(a=="" || a==null)
{
    alert("Username cannot be empty");
    return false;
}
else if(b<0)
{
    alert("Form isn't finished");
    return false;
}
else
{
    return true;
}
}

Problem is that Validate() works only if one condition is evalueted. If function Validate() contains only 1 var(a or b) and 1 if order(without else if) it works correctly. But when I put it like this, when Validate uses a and b variables and if, else if conditional order it won't work. Really od.. Thanks in advance...
In this case it works:
function Validate(){

var a=document.getElementById("username").value;

if(a=="" || a==null)
{
    alert("Username cannot be empty");
    return false;
}
else
{
    return true;
}
}

A: <input type="hidden" id="available" value="-1"/>

Here the value is of string dataType.  Whereas
else if(b<0)  //b is string dataType

Hence it failed.  so change it as
var b= Number(document.getElementById("available").value);

Try like this
HTML:
<form action="" method="POST" name="login">
    <input type="text" id="username" />
    <input type="hidden" id="available" value="1" />
    <input type="button" value="Send" onClick="return Validate()" />
</form>

JS:
function Validate() {
    var a = document.getElementById("username").value;
    var b = Number(document.getElementById("available").value);
    if (a == "" || a == null) {
        alert("Username cannot be empty");
        return false;
    } else if (b < 0) {
        alert("Form isn't finished");
        return false;
    } else {
        document.login.submit();  //dynamically submit the form
    }
}

A: If you are wanting to get error notifications for each input don't use if/else here, use multiple if's and set your errors
function validate(){
   var a=document.getElementById("username").value;
   var b=document.getElementById("available").value;
   var errors = [];

   if(a=="" || a==null){
      errors.push("Invalid username");
   }
   if(b<0 || isNaN(b)){
      errors.push("Invalid available value");
   }
   if(errors.length>0) {
      //do something with errors (like display them
      return false;
   }
}

Using the else if one of them evaluates to true it will skip the others. For instance if the first one is empty or null then it will do that block and skip the others.

A: I was testing your code for IE and Firefox and it work. Just add parseInt when you get the value of var b.
var b= parseInt(document.getElementById("available").value);


text:
Q: How to use jQuery each to successfully console.log a JSON array value With my below Javascript I'm defining a JSON array as a variable:
var json =     [
  {
        "pk": 981,
        "name": "Uruguay",
        "distributor": {
            "id": 28,
            "name": "Store 1",
            "email": "CustomService@example.com",
            "phone": "",
            "site": "",
            "ownership": 1,
            "shipping_cost": 1600,
            "fulfilled": false,
            "items": [
                213,
                215,
                217
            ]
        }
    },
    {
        "pk": 982,
        "name": "US Minor Outlying Islands",
        "distributor": {
            "id": 31,
            "name": "International",
            "email": "CustomerService@example.com",
            "phone": "1231231234",
            "site": "http://www.example.com",
            "ownership": 1,
            "shipping_cost": 1600,
            "fulfilled": false,
            "items": [
                213,
                215,
                217
            ]
        }
    },
    {
        "pk": 983,
        "name": "Uzbekistan",
        "distributor": {
            "id": 31,
            "name": "International",
            "email": "CustomerService@example.com",
            "phone": "1231231234",
            "site": "http://www.example.com",
            "ownership": 1,
            "shipping_cost": 1600,
            "fulfilled": false,
            "items": [
                213,
                215,
                217
            ]
        }
    }
  ];

Then I'm attempting to use jQuery's each function and a value reference on the pk field to log the name field value to console.
$.each(json.pk, function(i, v) {
    if (v.pk == 981) {
        console.log(v.name);
        return;
    }
});

I've tried numerous variations of this but I can't seem to ever trigger the conditional which would allow me to console log values. What am I doing wrong?

A: Have you tried this way
$.each(json, function(i, v) {
    if (v.pk == 980) {
        console.log(v.name);
        return;
    }
});

A: You need to pass json in $each instead of json.pk

var json =     [
  {
        "pk": 981,
        "name": "Uruguay",
        "distributor": {
            "id": 28,
            "name": "Store 1",
            "email": "CustomService@example.com",
            "phone": "",
            "site": "",
            "ownership": 1,
            "shipping_cost": 1600,
            "fulfilled": false,
            "items": [
                213,
                215,
                217
            ]
        }
    },
    {
        "pk": 982,
        "name": "US Minor Outlying Islands",
        "distributor": {
            "id": 31,
            "name": "International",
            "email": "CustomerService@example.com",
            "phone": "1231231234",
            "site": "http://www.example.com",
            "ownership": 1,
            "shipping_cost": 1600,
            "fulfilled": false,
            "items": [
                213,
                215,
                217
            ]
        }
    },
    {
        "pk": 983,
        "name": "Uzbekistan",
        "distributor": {
            "id": 31,
            "name": "International",
            "email": "CustomerService@example.com",
            "phone": "1231231234",
            "site": "http://www.example.com",
            "ownership": 1,
            "shipping_cost": 1600,
            "fulfilled": false,
            "items": [
                213,
                215,
                217
            ]
        }
    }
  ];

  $.each(json, function(i, v) {
    if (v.pk == 981) {
        console.log(v.name);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: One can easily navigate in JSON object provided that the json of is type Array.
$.each(json, function (key, value) {
    console.log((key + 1), value);
});

Demo


text:
Q: What is the correct syntax for a post url to Google Sheets which includes an API key? I am trying to post data to a Google Sheet (via a Gravity Forms form submission in WordPress).
My post url looks like this:
https://sheets.googleapis.com/v4/spreadsheets/1S45-------w3u1A/values:batchUpdate&key=AI-------KxIiBcD8
But I get this response:

404. That's an error.
  The requested URL /v4/spreadsheets/1S45-----3u1A/values:batchUpdate&key=AI----KxIiBcD8 was not found on this server.  That's all we know.


text:
Q: How to upgrade Castle.windsor from version 4 to version 5.0.1 While upgrading Castle.Windsor to version 5, I found out that the PerWebRequest is removed from LifestyleTypes enum.
In my application I am registering the components with different lifestyles like this
private static void RegisterComponents(LifeStypleType defaultLifestyleType) {
    container.Register(Component.For<IProjectService>()
             .ImplementedBy<ProjectService>()
             .LifeStyle.Is(defaultLifestyleType));
}

On another page I am creating the Container like
_windsorContainer = RegisterComponents(LifestyleType.PerWebRequest);

_windsorContainer2 = RegisterComponents(LifestyleType.Singleton);

Is there any way to use LifestyleType.PerWebRequest in Castle.Windsor version 5?


text:
Q: Typescript: Wrong overload selection based on function return type Why the following code is a compile error:
export interface Timer { }
declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): Timer;
declare function setInterval(handler: (...args: any[]) => void, timeout: number): number;

const timer: number = setInterval(() => console.log('hi'), 1000);

Also, when I change the order of declare function statements, it compiles the code without any errors. Looks like compiler just accepts the first type declaration.
EDIT: I couldn't provide a link to playground because the url was not correctly formatted in the question and I couldn't use any url shortener!

A: The problem is that Typescript does not (usually) take into account the expected call site return type when resolving function signatures. In your case just looking at setInterval(() => console.log('hi'), 1000); the compiler can say that this call could resolve to either signature, so it picks the first one in declaration order (as specified in the compiler specs). Once it has picked an overload the compiler will not reverse the decision if later, on assignment an error occurs.
The real problem to me seems to be that in deed, even I, lookin at  setInterval(() => console.log('hi'), 1000); can't tell if it will return a number or a Timer. There is nothing distinguishing between a call with two arguments returning a number, and a call to the version with two arguments and an empty rest parameter returning a Timer


text:
Q: NSFileWrapper, lazy loading and saving I have an NSDocument based application that uses filewrappers to save and load its data.
The document can have all kinds of resources, so I don't want to load everything into memory. I might be doing something fundamentally wrong, but as soon as I change one (inner) file and then save, I can't read any file that hasn't been loaded into memory.
I have separated the relevant code into a separate project to reproduce this behaviour, and I get the same results. The basic flow is this:

*

*I load an existing document from disk. The main fileWrapper is a directory filewrapper (I'll call that main) containing two other filewrappers (sub1 and sub2). The two inner filewrappers are not loaded at this point.

*When the user wants to edit sub1, it is loaded from disk.

*The user saves the document

*If the user wants to edit the other file (sub2), it cannot load. The error that appears:
-[NSFileWrapper regularFileContents] tried to read the file wrapper's contents lazily but an error occurred: The file couldn't be opened because it doesn't exist.

Here is the relevant code in my project:
This code might be easier to read in this gist:
https://gist.github.com/bob-codingdutchmen/6869871
#define FileName01 @"testfile1.txt"
#define FileName02 @"testfile2.txt"

/**
 *  Only called when initializing a NEW document
 */
-(id)initWithType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    self = [self init];
    if (self) {
        self.myWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];

        NSLog(@"Initializing new document...");

        NSString *testString1 = @"Lorem ipsum first sub file";
        NSString *testString2 = @"This is the second sub file with completely unrelated contents";

        NSFileWrapper *w1 = [[NSFileWrapper alloc] initRegularFileWithContents:[testString1 dataUsingEncoding:NSUTF8StringEncoding]];
        NSFileWrapper *w2 = [[NSFileWrapper alloc] initRegularFileWithContents:[testString2 dataUsingEncoding:NSUTF8StringEncoding]];

        w1.preferredFilename = FileName01;
        w2.preferredFilename = FileName02;

        [self.myWrapper addFileWrapper:w1];
        [self.myWrapper addFileWrapper:w2];

    }
    return self;
}

-(NSFileWrapper *)fileWrapperOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {

    // This obviously wouldn't happen here normally, but it illustrates
    // how the contents of the first file would be replaced
    NSFileWrapper *w1 = [self.myWrapper.fileWrappers objectForKey:FileName01];
    [self.myWrapper removeFileWrapper:w1];

    NSFileWrapper *new1 = [[NSFileWrapper alloc] initRegularFileWithContents:[@"New file contents" dataUsingEncoding:NSUTF8StringEncoding]];
    new1.preferredFilename = FileName01;

    [self.myWrapper addFileWrapper:new1];

    return self.myWrapper;
}

-(BOOL)readFromFileWrapper:(NSFileWrapper *)fileWrapper ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    self.myWrapper = fileWrapper;
    return YES;
}

- (IBAction)button1Pressed:(id)sender {
    // Read from file1 and show result in field1
    NSFileWrapper *w1 = [[self.myWrapper fileWrappers] objectForKey:FileName01];
    NSString *string1 = [[NSString alloc] initWithData:w1.regularFileContents encoding:NSUTF8StringEncoding];
    [self.field1 setStringValue:string1];
}

- (IBAction)button2Pressed:(id)sender {
    // Read from file2 and show result in field2
    NSFileWrapper *w2 = [[self.myWrapper fileWrappers] objectForKey:FileName02];
    NSString *string2 = [[NSString alloc] initWithData:w2.regularFileContents encoding:NSUTF8StringEncoding];
    [self.field2 setStringValue:string2];
}

The bottom two methods are only for updating the UI so I can see what happens.

*

*To change the contents of a file, I remove the existing fileWrapper and add a new one. This is the only way I've found to change the contents of a file, and the way I've seen it done in other SO answers.

*When a document is loaded from disk, I keep the fileWrapper around so I can use it (called myWrapper in the code above)
The Apple docs say that NSFileWrapper supports lazy loading and incremental saving, so I'm assuming that my code has some fundamental flaw that I can't see.

A: An NSFileWrapper is essentially a wrapper around a unix file node. If the file is moved the wrapper stays valid.
The problem yo seem to have is that creating a new file wrapper during saving is a new folder. And the system deletes your previous wrapper including sub2.
To achieve what you want you need to change to incremental saving, i.e. Only saving changed parts in place. See "save in place" in NSDocument.

A: In your -fileWrapperOfType:error: method, try building a new file wrapper that has new contents for the changed members and references the old file wrappers for the unchanged members.

A: Following the documentation to addFileWrapper: you add a child (subdirectory) to it, means
directory/

*

*addfileWrapper:fileName1
directory/fileName1/

*addfileWrapper:fileName2
directory/fileName1/fileName2.
That file doesn't exist.
You have to use
addRegularFileWithContents:preferredFilename:
instead.


text:
Q: Why can't I use the array's append() in Swift? I'm getting a: Cannot invoke 'append' with an argument list of type '([Book])' It works find if I use the += but I don't understand why append() won't work.
struct Book
{
    var title:String
    var pageCount:Int
}

class Library
{
    var onShelfBooks:[Book] = []
    var onLoanBooks:[Book] = []
    var books:[Book]
    {
        get
        {
            return onShelfBooks + onLoanBooks
        }

        set(newBook)
        {
            onShelfBooks.append(newBook)
        }
    }
}

A: struct Book
{
    var title:String
    var pageCount:Int
}

class Library
{
    var onShelfBooks:[Book] = []
    var onLoanBooks:[Book] = []
    var books:[Book]
    {
        get
        {
            return onShelfBooks + onLoanBooks
        }

        set(newBook)
        {
            onShelfBooks.append(newBook[0])
        }
    }
}

var myLibrary = Library()

var newBook = Book(title: "Swift Development with Cocoa", pageCount: 453)

myLibrary.books = [newBook]

myLibrary.books

A: Append only allows you to add one object at a time while += allows you to combine an array of objects with another object. When you call append on the setter you are trying to add an array of book objects, or [Book] instead of just a single book object.

A: If you would like to add [newBook] with append, you can use : of
1- onShelfBooks.append(contentsOf: newBook)
"contentOf" is type of Sequence.
otherwise use of:
2- onShelfBooks += newBook


text:
Q: Creating a list of CheckBoxed items across multiple google sheets I'm struggling to find the right formula to do a relatively simple task. I have a google sheet document with multiple sheets that have items listed each with a checkbox. I'd like to have each item that is checked be returned in a separate sheet in order to create a list. I've tried a few VLOOKUP formulas as well as combinations of IF/MATCH logic to get there but nothing seems to be working. Here's what I'm looking at:

Id like the list to return the "Item Location" for each column with a checked checkbox.

A: try:
=TRANSPOSE(FILTER({Sheet1!6:6, Sheet2!6:6}; {Sheet1!2:2, Sheet2!2:2}=TRUE))


text:
Q: Condition gets false even if matching seems true in beanshell jmeter I am getting URL based on previous POST request and checking for specific string in URL.
URL is : https://www.example.com/index/checkout
Code to check specific text in URL
String URL = prev.getURL().toString();
vars.put("URL", URL);

      if("${URL}".contains("index"))
      {
           log.info("PASS");
      }
     else
      {
        log.info("FAIL");

      }

My URL already contains "index" but above conditions always get FALSE.
I tried by checking log.info(URL) and it returns me exact URL with word "index".
I am using BeanShell PostProcessor for above in jmeter.

A: Don't inline JMeter Variables and/or Functions into Beanshell script.
You should be using vars.get("URL"); instead of "${URL}" as "${URL}" string doesn't contain index. You can double check it by adding log.info("${URL}"); line to your script.
String URL = "https://www.example.com/index/checkout";

vars.put("URL", URL);

if (vars.get("URL").contains("index")) {
    log.info("PASS");
} else {
    log.info("FAIL");
}

See How to Use BeanShell: JMeter's Favorite Built-in Component for comprehensive explanation and other tips.


text: Q: error while uploading ci project to cpanel I get the error shown below. I tried removing the user, kept the config/database file username and password empty. Then, i created the user wwwbhak_hajje and kept the username and pw in the db file respectively.


text:
Q: How can I make the temperature visible in indicator-weather in Lubuntu? I've got Lubuntu 11.10 with indicator-weather installed, but indicator-weather doesn't show the current temperature.

Resizing the panel doesn't work, and the application isn't shown in the panel preferences. How can I make indicator-weather show the temperature?

A: converted comment to answer
There is a report on Launchpad with a similar/if not the same issue.
I would suggest you subscribe to this bug-report to receive updates.
Launchpad Janitor has marked this as affecting multiple users - so you are not alone!


text:
Q: re.match() проверка по регулярному Нужна именно проверка строки на совпадение с регулярным выражением, а не поиск подстрок. Есть ли такая функция непосредственно в re пакете, или надо отдельно допиливать?

Пример кода:
string = sys.argv[1]
if re.match("dog{1}", string):
    print("yes")
else:
    print("no")

$ python3 rematch dog
yes
$ python3 rematch dogdog
yes

Во втором случае должна быть ошибка, ведь я ввел две собаки, а по логике программа должна пропустить только с одной собакой.
Если я чего не понимаю, подскажите пожалуйста

A: Если я правильно понял, нужно проверить, вся ли строка подходит под рег.выражение?
import re
a = "abc12def"
b = re.match(r"^\w{3}\d{2}\w{3}$", a)
print(b)

Если строка полностью подходит - функция вернёт объект _sre.SRE_Match, если нет - None
Результат:

IN: abc12def
OUT: <_sre.SRE_Match object; span=(0, 8), match='abc12def'>
IN: abc12defZ
OUT: None


text:
Q: What wrong with this code: first appearance of a word I wrote a program (appear) that keeps generating random letters, from a to z, till a given word appears:
import random

def appear(word):
    word = list(word)
    w = word
    l = list('abcdefghijklmnopqrstuvwxyz')
    i = 0

    while len(w) > 0:
        r = int(random.random() * 26)
        print(l[r], end='')

        if (w[0] == l[r] and i == 1) or (w[0] == l[r] and len(w) == len(word)):
            i = 1
            del w[0]
        else:
            i = 0
            w = word

For example, appear('car') should produce: ajzkcar.
I tried printing in each loop the value of w, and the problem seems to be that the program fails to reset w to the original word if it doesn't find two consecutive letters, even though I clearly say that it should in the last "else"

A: You need to keep the letters that you have generated in memory, and compare them with the letters of the target word.
The word you're looking for has a fixed length. When you generate a new letter, you need to add that new letter to your memory at the right, and discard the oldest letter from your memory, at the left.
What data structure to use for this? Adding letters to the right and removing letters from the left, so that the total length remains fixed? I immediately think about a fixed-length queue.
The simplest way to get a fixed-length queue in python is to use collections.deque with a maxlen argument.
Also, to choose a letter, I have a preference for random.choice(letters) over letters[int(random.random() * 26)]
from collections import deque
from random import choice, choices
from string import ascii_lowercase as alphabet

def appear(word):
    queue = deque(choices(alphabet, k=len(word)), maxlen=len(word))
    target = deque(word)
    print(''.join(queue), end='')
    while queue != target:
        new_letter = choice(alphabet)
        queue.append(new_letter)
        print(new_letter, end='')

appear('a')
# jca

appear('ab')
# zdoxkcnswafzsclmeduwhyhpdfwljujduwvbsxayihtfmlqrjxamlqnestzsncjjzbyfuzaczmuaiddfehckkrcnzfwwgnxfxcaifasaybokkxrqievmwqhisnaqhezcxwxfrstvuvwoedstpsrxkmxbubab


text:
Q: Retrieve ordered list with items from SQLite database I'm designing tables for a database.
Inside an Android app, I download - from a server - an ordered list in JSON. I insert the list and its items into a SQLite db.
The list table's columns:
+ list_id
+ timestamp

The list item table's column:
 + item_id
 + timestamp
 + list of list_ids (a list item can be in multiple lists)

When I retrieve the items for a list they should have the same order as when I downloaded them. What is the most efficient way to store the "list order"? One option is to let the item have a columns with a list of pair like so: list:indexInList. Appreciate advice on betters ways to do this.
Clarification: An item can occur in a list multiple times, e.g. item_ids in a list: 1,2,3,1,5.

A: If you have an id column with an auto-increment then add ORDER BY id to your query.
You can reorder your table.
ALTER TABLE tbl_name ORDER BY col_name

A: You should never store a list of values in a column when you might need to access individual items.
For a M:N relationship like this, you typically use a third table:
CREATE TABLE items_in_lists (
    list_id INTEGER REFERENCES lists(list_id),
    item_id INTEGER REFERENCES items(item_id),
    PRIMARY KEY(list_id, item_id)
);

Once you have this table, it is the natural place to store the item's order in the list.


text:
Q: Skin lesion segmentation MaskRCNN error (bool index does not match) i have a task of using MaskRCNN to do a skin lesion segmentation. I have my work on my github but i have an error on cell 22 when training the model.
https://github.com/leahcimali/Skin-cancer-segmentation/blob/main/Project%20Mask.ipynb
Knowing that the shape of my image is (128,128,3).
My code is based on this project, but i had to remove json description because we i download them, they get corrupted.
https://github.com/NeyoxDrago/Skin-lesion-detection-with-MRCNN
Thank, in advance for advice.
I tried installing different environment because some people with similar error had wrong environment setup. But everything i tried i got the same error. I even tried with the recommanded docker image on https://github.com/matterport/Mask_RCNN .


text:
Q: Find database of Web API project on Visual Studio 2015 LocalDB I'm developing a Code First Web API using ASP.NET 5 and MVC 6. I can test my models and controllers locally and in Azure using a publish profile, but I want to see if the database is applying some constraints. I read that I can see the database's Tables and Columns using the SQL Server Object Explorer.
When I go to View > SQL Server Object Explorer I can see the following:
(localdb)\MSSQLLocalDB
(localdb)\ProjectsV12
(localdb)\v11.0
I know that v11.0 was used on VS 2012 and it was changed to MSSQLLocalDB on VS 2015 (I don't know what ProjectsV12 is doing there). So I open (localdb)\MSSQLLocalDB > Databases and I only see a System Databases subfolder, I can't find my project's database. Am I looking on the right place? Am I missing a step? Thanks for your help.
Here's a pic of what I see.


text:
Q: Google Maps fails to open properly I am updating a cross platform app written in VS2010.
I need to provide driving instructions to the selected location.
I would like my app to open Google Maps (GM) in it's own window with the best route already determined (as if the operator had opened GM themselves and selected the destination manually).
I have been following GM developer's instructions but cannot get it to open GM on Android device, I can get it to open GM on iOS but it hangs (all have GM installed & on Wifi). I do not have a Google API key as instructions say it's not needed.
iOS:
    window.open("maps://www.google.com/maps/dir/?api=1&destination=-36.847456,174.830521&travelmode=driving");

Opens GM with last destination but sits on 'Loading…' forever
Android:
    window.open("https://www.google.com/maps/dir/?api=1&origin=-36.852946,174.763348&destination=-36.847456,174.830521&travelmode=driving");

This opens a web page with recommended route selected, but with a 'No internet' banner.  AndroidBanner
When I click [Navigate] I am asked if I want to use Google Maps app. When I click [Use the app] I get the application error below which takes me to a black screen so I must restart the app.
As an aside, pasting above url into chrome on Android returns 'did not match any documents'.
net::ERR_UNKNOWN_URL_SCHEME(intent://maps.app.goo.gl/?link= https://www.google.com/maps/dir//-36.847456,174.830521/@-36.8660726,174.7966977,12z/data%3D!4m2!4m1!3e0!11m1!6b1&apn=com.google.android.apps.maps&amv=914018424&isi=585027354&ibi=com.google.Maps&ius=comgooglemapsurl&utm_campaign=ml_promo&ct=ml-navfab-nlu-o&mt=8&pt=9008#Intent;package=com.google.android.gms;scheme=https;S.browser_fallback_url=https://play.google.com/store/apps/details%3Fid%3Dcom.google.android.apps.maps&pcampaignid%3Dfdl_long&url%3Dhttps://www.google.com/maps/dir//-36.847456,174.830521/@-36.8660726,174.7966977,12z/data%253D!4m2!4m1!3e0!11m1!6b1&min_version%3D914018424;end;)
What am I missing?
Entire function that is called from a toolbar button complete with previous attempts:
            mapsSelector: function () {

        // helpful url: https://developers.google.com/maps/documentation/urls/ios-urlscheme

        var mapURL = "https";
        if /* if we're on iOS, open in Apple Maps */
            ((navigator.platform.indexOf("iPhone") != -1) ||
             (navigator.platform.indexOf("iPad") != -1) ||
             (navigator.platform.indexOf("iPod") != -1))
            mapURL = "maps";

        /*
        mapURL = mapURL + "://www.google.com/maps/dir/" +
             viewModel.Latitude_Now() + "," + viewModel.Longitude_Now() + "/" +
         viewModel.Latitude_Destination() + "," + viewModel.Longitude_Destination() + ",17/" +
                 "am=t";
        mapURL = "http://maps.google.com/maps?saddr=-36.91078,174.850896&daddr=-36.7492041,174.6866052";
        mapURL = "https://www.google.com/maps/dir/?api=1&saddr=-36.91078,174.850896&daddr=-36.7492041,174.6866052";
        mapURL = "https://www.google.com/maps/dir/?api=1&origin=-36.91078,174.850896&destination=-36.7492041,174.6866052&travelmode=driving";
        */

        mapURL = "https://www.google.com/maps/dir/?api=1&origin=-36.852946,174.763348&destination=-36.847456,174.830521&travelmode=driving";
        //mapURL = "maps://www.google.com/maps/dir/?api=1&destination=-36.847456,174.830521&travelmode=driving";

        alert(mapURL);
        window.open(mapURL);

    }


text:
Q: Neurophysiology recording MATLAB I have my data stored in structures regarding recording from neurons. Neuronal spikes are stored in a logical array where a spike is 1 and no spike is 0.
spike = <1x50 logical>
spike = [1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 1 1 0 1 0 1 0 0 0 1 1 0 0 ...]

What I have to do is to convert these spikes into smooth curve signal using Gaussian filter.
I have the following function for smoothing:
function z = spikes(x, winWidth)
% places a Gaussian centered on every spike
% if x is matrix, then perform on the columns

winWidth = round(winWidth);

if winWidth == 0
    y = [0 1 0];
    w = 1;
else
    w = winWidth * 5;
    t = -w : w;
    y = normpdf(t,0,winWidth);
end

if isvector(x)
    z = conv(x,y);
    z = z(w+1 : end);
    z = z(1 : length(x));
else
    z = zeros(size(x));
    for i = 1 : size(x,2)
        z1 = conv(x(:,i),y);
        z1 = z1(w+1 : end);
        z1 = z1(1 : length(x));
        z(:,i) = z1;
    end
end

end

I was just wondering how can I make nerve signals from spikes that are like the above logical array?
PS: I am very lost and my answers are not understandable to be posted here.

A: If I understood correctly you just have to increase the sampling frequency and convolve. Since your original array corresponds to a signal with sampling frequency of one spike, if you want to increase the resolution of your spikes, you need to artificially introduce more data points between the spikes.
spike = [1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 1 1 0 1 0 1 0 0 0 1 1 0 0];

![n_samples = numel(spike);
resampling_f = 50;
new_signal = zeros(n_samples*resampling_f,1);

spikes_ind = find(spike);
new_signal((spikes_ind-1)*50+round(resampling_f/2)) = 1;

%here you can use the spikes function you defined
winWidth = 10;
w = winWidth * 5;
t = -w : w;
kernel = normpdf(t,0,winWidth);
spikes_sample = conv(x,kernel);

figure, hold on
subplot(1,2,1), hold on
plot(new_signal)

subplot(1,2,2), hold on
plot(spikes_sample)][1]


text:
Q: Attempting to pass Linux command output into a variable I have the following code:
#include <stdio.h>
#include <stdlib.h>

int readCmd(char* cmd) {
    FILE *fp;
    char path[1024];

    /* Open the command for reading. */
    fp = popen(cmd, "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
    }

    /* Read the output a line at a time - output it. */
    while (fgets(path, sizeof(path)-1, fp) != NULL) {
        printf("%s", path);
    }
    /* close */
    pclose(fp);
    return path;
}

int main( int argc, char *argv[] ) {
char* gp123;
char* gp124;

gp124=readCmd("cat /sys/class/gpio/gpio124/direction");
gp123=readCmd("cat /sys/class/gpio/gpio123/direction");
printf("123: %s \n124: %s \n",gp123,gp124);

}

With the following output:
out
in
123: in
124: in

As you can see, gpio pin 123 is set to 'in' and 124 is set to 'out'.
However, both gp123 and gp124 are being assigned 'in'. I am rusty with functions and C. Could you fellas help me out a little please?
More specifically, why is it failing to assign the returned value for each command I read? Is this a local/global variable issue?
Thanks!
EDIT:
#include <stdio.h>
#include <stdlib.h>
char* readCmd(char* cmd)
{
FILE *fp;
static char path[1024];

/* Open the command for reading. */
fp = popen(cmd, "r");
if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
}

/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf("%s", path);
}
/* close */
pclose(fp);
return path;
}

int main( int argc, char *argv[] )
{
    char gp123[50];
    char gp124[50];
    char *answer;

    answer=readCmd("cat /sys/class/gpio/gpio124/direction");
    sprintf(gp124, "%s", answer);
    answer=readCmd("cat /sys/class/gpio/gpio123/direction");
    sprintf(gp123, "%s", answer);
    printf("123: %s \n124: %s \n",gp123,gp124);

}

This seems to work correctly, is there anything here I should change to be more correct?

A: You can't return a pointer to automatic memory from a function. The path array only exists for the duration of the readCmd function (which should return char*, not an int).
To solve it, you can:

*

*declare the array static (or use a global array--pretty much the same thing) and embrace non-reenterability

*use the heap (malloc the array or use the GNU getline function)

*ask the caller to provide provide a pointer to where to save the output (its size should be passed in too)


text:
Q: Sum of the digits of $N=5^{2012}$ The sum of the digits of $N=5^{2012}$ is computed.
The sum of the digits of the resulting sum is then computed.
The process of computing the sum is repeated until a single digit number is obtained.
What is this single digit number?

A: You want to know the value of $5^{2012} \pmod 9$.
Since $\varphi(9) = 3^2 - 3 = 6$ and $\gcd(5,9) = 1$, then, by Euler's theorem,  $5^6 \equiv 1 \pmod 9$.
Since $2012 = 335 \times 6 + 2$,
$$5^{2012} \equiv (5^6)^{335} \times 5^2
\equiv 1^{335} \times 25 \equiv 7 \pmod 9.$$

A: If Euler's Theorem is unknown then we can instead use the Binomial Theorem. By casting nines the iterated digit sum  equals the remainder mod $9$, which we may compute mentally as follows
${\rm mod}\ \color{#c00}9\!:\,\ 5^n\equiv (-4)^n \equiv (-1)^n (1+3)^n \equiv (-1)^n(1 + 3n+ \color{#c00}{3^2}(\cdots))\equiv (-1)^n(1+3n)$
therefore $\ n = 2012\,\Rightarrow\,5^n \equiv 1+3(2012)\equiv 1+3\,\underbrace{(2\!+\!0\!+\!1\!+\!2)}_{\large \rm cast\ nines}\equiv 16\equiv 7\,\pmod 9$

A: Hint : You can prove that if $d(n)$ denotes sum of digits of $n$, then $n$ is congruent to $d(n)$ mod 9. Also, $N<10^{2012}$ implies $d(N)<9*2012<20000$.

A: Hint: if $s$ is the sum of digits of a number $a$ then
$$s\equiv a\pmod 9.$$
Now all you need too do is compute $5^{2012} \pmod 9$.

A: Let $f(n)$ denote the sum of sum of ... sum of digits of $5^n$, then:
$f(n)=\cases
 {
  1 & $n\equiv0\pmod6$\\
  5 & $n\equiv1\pmod6$\\
  7 & $n\equiv2\pmod6$\\
  8 & $n\equiv3\pmod6$\\
  4 & $n\equiv4\pmod6$\\
  2 & $n\equiv5\pmod6$\\
 }
$
Therefore: $2012\equiv2\pmod6 \implies f(2012)=7$.


text:
Q: ASIHTTPRequest memory leaks I have a iOS project in which I am using ARC in my own classes, but have ARC turned off in other libraries like ASIHTTPRequest.
I'm getting huge memory leaks using the code below to fetch an image from a web server:
-(void)buildPhotoView {

self.photoLibView.hidden = NO;

NSString *assetPathStr = [self.cellData objectForKey:@"AssetThumbPath"];

// get the thumbnail image of the ocPHOTOALBUM from the server and populate the UIImageViews
NSURL *imageURL = [NSURL URLWithString:assetPathStr];

__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:imageURL];
__unsafe_unretained ASIHTTPRequest *weakRequest = request;
[weakRequest setCompletionBlock:^{

    // put image into imageView when request complete
    NSData *responseData = [weakRequest responseData];
    UIImage *photoAlbumImage = [[UIImage alloc] initWithData:responseData];
    self.photo1ImageView.image = photoAlbumImage;
}];
[weakRequest setFailedBlock:^{
    NSError *error = [request error];
    NSLog(@"error geting file: %@", error);
}];
[weakRequest startAsynchronous];

}
I've modified the sample code from the ASIHTTPRequest example code page to eliminate compiler warnings in Xcode.
How can I get rid of these memory leaks? I only seem to get them when using blocks.

A: You're referencing the wrong request variable from inside the completion block. You should reference request in the block (that's why you declare it with the __block identifier). In fact, you shouldn't need to declare weakRequest at all.
If you want the request to be kept in memory, store it in an @property (retain) in your class (the one with the buildPhotoView method perhaps).


text:
Q: Angular 2 how to set strictBounds can Somebody help me out on this? I want to create strict bounds like this:
    var strictBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(51.51260063140188, 5.100499215469426),
        new google.maps.LatLng(51.527701526080484, 5.1409469274140065)
    );

    //Listen for the dragend event
    map.addListener('dragend', function () {
        if (strictBounds.contains(map.getCenter())) return;

        //We're out of bounds - Move the map back within the bounds
        var c = map.getCenter(),
            x = c.lng(),
            y = c.lat(),

            maxX = strictBounds.getNorthEast().lng(),
            maxY = strictBounds.getNorthEast().lat(),
            minX = strictBounds.getSouthWest().lng(),
            minY = strictBounds.getSouthWest().lat();

        if (x < minX) x = minX;
        if (x > maxX) x = maxX;
        if (y < minY) y = minY;
        if (y > maxY) y = maxY;
        map.setCenter(new google.maps.LatLng(y, x));
    });

This is what I did in javascript, but how can I implement this in angular2-google-maps here a plunker: LINK
I hope one of you guys can help me out and tell me how to start

A: Execute this function in the _initMapInstance in angular2-google-maps/src/directives/google-map.ts like this:
  private _initMapInstance(el: HTMLElement) {
this._mapsWrapper.createMap(el, {

});
this._handleBoundaries();

private _handleBoundaries() {
   this._mapsWrapper.subscribeToMapEvent<void>('dragend').subscribe(() => {
   this._mapsWrapper.getCenter().then((center: LatLng) => {

      var x = this._longitude;
      var y = this._latitude;

      // console.log('y',y, 'x', x);

      var maxX = 5.139133754119953;
      var maxY = 51.52773156266013;
      var minX = 5.105831446991047;
      var minY = 51.51337849651561;

      if (x < minX) x = minX;
      if (x > maxX) x = maxX;
      if (y < minY) y = minY;
      if (y > maxY) y = maxY;

      this._mapsWrapper.setCenter({lat: y, lng: x});
   });
});

}


text:
Q: How to set the active status for a navbar? I've tried multiple codes for setting an active status on a navbar menu link, but none of them works. Finally I found a bootply link that works: http://bootply.com/70331 , but it won't work on my menu. Here's my navbar:

      emiAAC

      @include('common.menu_addition')
      @include('common.view_special')

 News

              Community

Characters

Online list

Highscores

NOT DONE

Forum

Gallery

Houses

Guilds

Guild Wars

Live casts

              Library

NOT DONE

Exp. stages

Monsters

Quests

Spells

              Help

NOT DONE

Rules

Support

<form id="custom-search-form" class="form-search form-horizontal pull-right" action="{{ URL::action('CharactersController@search') }}" method="get">

        <input type="text" class="search-query" name="character" placeholder="Character/guild name">
        <button type="submit" class="btn"></button>

</form>

A: Try this:

{{ HTML::link('service/'.$user_id.'/'.$filename, 'Service') }}

{{ HTML::link('#', 'Search') }}

{{ HTML::link('diff/'.$user_id.'/'.$filename, 'Compare') }}

A: Here is an example for one of them

Characters


text:
Q: C3JS Uncaught TypeError: Cannot read properties of undefined (reading 'getItem') I know that there is full of question about this problem, but I have this strange scenario where:
Initially I have one C3JS pie chart, where on click needs to generate another C3JS bar chart.
Until here it work fine without any problems.
The C3JS bar chart on click should also generate another C3Js chart.
The problem is when I click  C3JS bar chart it gives me error:

c3.min.js?v=1031:2 Uncaught TypeError: Cannot read properties of undefined (reading 'getItem');

Here is example of my code with dummy data

var data1 = [
    [
        "setosa",
        0.2,
        0.2,
        0.2,
        0.2,
        0.2,
        0.4,
        0.3,
        0.2,
        0.2,
        0.1,
        0.2,
        0.2,
        0.1,
        0.1,
        0.2,
        0.4,
        0.4,
        0.3,
        0.3,
        0.3,
        0.2,
        0.4,
        0.2,
        0.5,
        0.2,
        0.2,
        0.4,
        0.2,
        0.2,
        0.2,
        0.2,
        0.4,
        0.1,
        0.2,
        0.2,
        0.2,
        0.2,
        0.1,
        0.2,
        0.2,
        0.3,
        0.3,
        0.2,
        0.6,
        0.4,
        0.3,
        0.2,
        0.2,
        0.2,
        0.2,
    ],
    [
        "versicolor",
        1.4,
        1.5,
        1.5,
        1.3,
        1.5,
        1.3,
        1.6,
        1.0,
        1.3,
        1.4,
        1.0,
        1.5,
        1.0,
        1.4,
        1.3,
        1.4,
        1.5,
        1.0,
        1.5,
        1.1,
        1.8,
        1.3,
        1.5,
        1.2,
        1.3,
        1.4,
        1.4,
        1.7,
        1.5,
        1.0,
        1.1,
        1.0,
        1.2,
        1.6,
        1.5,
        1.6,
        1.5,
        1.3,
        1.3,
        1.3,
        1.2,
        1.4,
        1.2,
        1.0,
        1.3,
        1.2,
        1.3,
        1.3,
        1.1,
        1.3,
    ],
    [
        "virginica",
        2.5,
        1.9,
        2.1,
        1.8,
        2.2,
        2.1,
        1.7,
        1.8,
        1.8,
        2.5,
        2.0,
        1.9,
        2.1,
        2.0,
        2.4,
        2.3,
        1.8,
        2.2,
        2.3,
        1.5,
        2.3,
        2.0,
        2.0,
        1.8,
        2.1,
        1.8,
        1.8,
        1.8,
        2.1,
        1.6,
        1.9,
        2.0,
        2.2,
        1.5,
        1.4,
        2.3,
        2.4,
        1.8,
        1.8,
        2.1,
        2.4,
        2.3,
        1.9,
        2.3,
        2.5,
        2.3,
        1.9,
        2.0,
        2.3,
        1.8,
    ],
];
var data2 = [
    ["data1", 30],
    ["data2", 120],
];
try {
    c3.generate({
        bindto: "#myChart",
        pie: {
            label: {
                format: function (value, ratio, id) {
                    return value;
                },
            },
        },
        tooltip: {
            format: {
                value: function (value, ratio, id) {
                    var perc = `${parseFloat(ratio * 100).toFixed(1)}%`;
                    return value + " (" + perc + ")";
                },
            },
        },
        data: {
            columns: data1,
            type: "pie",
            onclick: function (event) {
                console.log(event);
                c3.generate({
                    bindto: "#myChart2",
                    legend: {
                        show: false,
                    },
                    axis: {
                        x: {
                            type: "category",
                        },
                    },
                    data: {
                        columns: data2,
                        type: "bar",
                        onclick: function (event2) {
                        myFunction(event2)
                        }

                    },
                });
            },
        },
    });
} catch (ex) {
    console.log(ex);
}

function  myFunction(event2){
    console.log(event2)
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.8/c3.min.css" rel="stylesheet"/>

Versions that I have:
C3js: 0.4.8
D3js: 3.4.4
Why with C3JS pie chart onclick event works fine and with the C3JS bar chart it gives me this error? Any solution to fix this?

A: The issue is because you're using an incredibly outdated version of C3JS - it's from 2014!!
You should update that library to the latest version, which is 0.7.20. You will also need to update D3 to v5 to maintain support.

var data1=[["setosa",.2,.2,.2,.2,.2,.4,.3,.2,.2,.1,.2,.2,.1,.1,.2,.4,.4,.3,.3,.3,.2,.4,.2,.5,.2,.2,.4,.2,.2,.2,.2,.4,.1,.2,.2,.2,.2,.1,.2,.2,.3,.3,.2,.6,.4,.3,.2,.2,.2,.2,],["versicolor",1.4,1.5,1.5,1.3,1.5,1.3,1.6,1,1.3,1.4,1,1.5,1,1.4,1.3,1.4,1.5,1,1.5,1.1,1.8,1.3,1.5,1.2,1.3,1.4,1.4,1.7,1.5,1,1.1,1,1.2,1.6,1.5,1.6,1.5,1.3,1.3,1.3,1.2,1.4,1.2,1,1.3,1.2,1.3,1.3,1.1,1.3,],["virginica",2.5,1.9,2.1,1.8,2.2,2.1,1.7,1.8,1.8,2.5,2,1.9,2.1,2,2.4,2.3,1.8,2.2,2.3,1.5,2.3,2,2,1.8,2.1,1.8,1.8,1.8,2.1,1.6,1.9,2,2.2,1.5,1.4,2.3,2.4,1.8,1.8,2.1,2.4,2.3,1.9,2.3,2.5,2.3,1.9,2,2.3,1.8,],]
var data2 = [["data1", 30],["data2", 120]];

try {
  c3.generate({
    bindto: "#myChart",
    pie: {
      label: {
        format: function(value, ratio, id) {
          return value;
        },
      },
    },
    tooltip: {
      format: {
        value: function(value, ratio, id) {
          var perc = `${parseFloat(ratio * 100).toFixed(1)}%`;
          return value + " (" + perc + ")";
        },
      },
    },
    data: {
      columns: data1,
      type: "pie",
      onclick: function(event) {
        c3.generate({
          bindto: "#myChart2",
          legend: {
            show: false,
          },
          axis: {
            x: {
              type: "category",
            },
          },
          data: {
            columns: data2,
            type: "bar",
            onclick: myFunction
          },
        });
      },
    },
  });
} catch (ex) {
  console.log(ex);
}

function myFunction(event2) {
  console.log(event2)
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.min.css" rel="stylesheet" />

If you absolutely have to retain the outdated version of C3JS, then there's a polyfill you can use to solve the problem available here


text:
Q: Most general space for the Wigner-Weyl transform The Wigner-Weyl transform $\mathfrak{W}$ is a bijective mapping between functions on a phase space and Hilbert space operators in order to map quantum mechanics into a phase-space formulation. Then the $\star$-product can be defined to be the morphism operation $$\mathfrak{W}(fg) = \mathfrak{W}(f) \star \mathfrak{W}(g).$$ Now I´m wondering about the most general underlying space where a Wigner-Weyl transform exists?
I know that Kontsevich (2003) has shown a $\star$-product for any finite-dimensional Poisson manifold, yet with an intrinsic definition of the $\star$-product. Does this already imply a Wigner-Weyl transform on any finite-dimensional Poisson manifold and how does it look like explicitly? Moreover, is this already the most general space where it exists?


text:
Q: Is accessing volatile local variables not accessed from outside the function observable behavior in C++? In C++03 Standard observable behavior (1.9/6) includes reading and writing volatile data. Now I have this code:
int main()
{
    const volatile int value = 0;
    if( value ) {
    }
    return 0;
}

which formally initializes a volatile variable and then reads it. Visual C++ 10 emits machine code that makes room on the stack by pushing a dword there, then writes zero into that stack location, then reads that location.
To me it makes no sense - no other code or hardware could possibly know where the local variable is located (since it's in automatic storage) and so it's unreasonable to expect that the variable could have been read/written by any other party and so it can be eliminated in this case.
Is eliminating this variable access allowed? Is accessing a volatile local which address is not known to any other party observable behavior?

A: The thread's entire stack might be located on a protected memory page, with a handler that logs all reads and writes (and allows them to complete, of course).
However, I don't think MSVC really cares whether or how the memory access might be detected. It understands volatile to mean, among other things, "do not bother applying optimizations to this object". So it doesn't. It doesn't have to make sense, because MSVC is not interested in speeding up this kind of use of volatile.
Since it's implementation-dependent whether and how observable behavior can actually be observed, I think you're right that an implementation can "cheat" if it knows, because of details of the hardware, that the access cannot possibly be detected. Observable behavior that has no physically-detectable effect can be skipped: no matter what the standard says, the means to detect non-conforming behavior are limited to what's physically possible.
If an implementation fails to conform to the standard in a forest, and nobody notices, does it make a sound? Kind of thing.

A: That's the whole point of declaring a variable volatile: you tell the implementation that that variable may change or be read by means unknown to the implementation itself and that the implementation should refrain from performing optimizations that might impact such access.
When a variable is declared both volatile and const your program may not change it, but it may still be changed from outside. This implies that not only the variable itself but also all read operations on it cannot be optimized away.

A:
no other code or hardware could possibly know

You can look a the assembly (you just did!), figure out the address of the variable, and map it to some hardware for the duration of the call. volatile means the implementation is obliged to account for such things too.

A: Volatile also applies to your own code.
volatile int x;
spawn_thread(&x);
x = 0;
while (x == 0){};

This will be an endless loop if x is not volatile.
As for the const. I'm unsure whether the compiler can use that to decide.

A:
To me it makes no sense - no other code or hardware could possibly
  know where the local variable is located (since it's in automatic
  storage)

Really? So if I write an x86 emulator and run your code on it, then that emulator won't know about that local variable?
The implementation can never actually know for sure that the behaviour is unobservable.

A: My answer is a bit late. Anyway, this statement

To me it makes no sense - no other code or hardware could possibly
  know where the local variable is located (since it's in automatic
  storage)

is wrong. The difference between volatile or not is actually very observable in VC++2010. For instance, in Release build, you cannot add a break point to a local variable declaration that was eliminated by optimization. Hence, if you need to set a break point to a variable declaration or even just to watch its value in the Debugger, we have to use Debug build.  To debug a specific local variable in Release build, we could make use of the volatile keyword:
int _tmain(int argc, _TCHAR* argv[])
{
    int a;
    //int volatile a;
    a=1; //break point here is not possible in Release build, unless volatile used

    printf("%d\n",a);
    return 0;
}


text:
Q: Php echo html code and dots I want to echo html code with dots:
echo '
…
' . "\n";

But I get

���

How can I solve this problem?

A: Looks like an encoding problem. You should consider to declare your html in utf8 :
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

and make sure your file is utf8 encoded.

A: Because that's unicode:
Add
<meta http-equiv=Content-Type content="text/html; charset=UTF-8"> for HTML 4.01 & below
<meta charset="UTF-8"> for HTML5

Or execute
header("content-type: text/html; charset=UTF-8");
Or of course just do
echo '
...
' . "\n";

With normal full stops.
Did my answer solve your issue? Please make sure to mark it as accepted to help other people with the same problem.