text:
Q: What is the ray matrix or ABCD matrix for an image located at infinity? I know the object is located at the focal point point, so I will get a transfer matrix of this form:
$$\left(\begin{array}{cc}1 &0 \\ f & 1\end{array}\right)$$
with $f$ the focal length, but then for the image what will be the transfer matrix? Will it be $\left(\begin{array}{cc}1 &0 \\ \infty & 1\end{array}\right)$?
Here is the system that I am describing:

A: A transfer matrix is a representation of a homogeneous linear function that approximates a behavior. As such, it is meant to work for all cases, at least approximately, over a range of inputs. So it doesn't depend at all on where the object and image are. In fact, you compute the image given the object position by using the unique, fixed transfer matrix characterizing an optical element. Before we begin, I believe your transfer matrix should be:
$$\left(\begin{array}{cc}1 &0 \\ -\frac{1}{f} & 1\end{array}\right)\tag{1}$$
instead of what you have written.
So, let's suppose a point source is at the focal point. At the source, we have a bundle of rays i.e. a set of state vectors of the form:
$$B(x)=\left\{\left.\left(\begin{array}{c}x_0\\\theta\end{array}\right)\right|\;\theta\in\mathbb{R}\right\}\tag{2}$$
meaning rays that pass through the transverse plane all at the same transverse position (namely $x_0$) all at different inclinations $\theta$ to the optical axis. After having propagated an axial distance $f$, the ray making an angle $\theta$ with the optical axis still has the same angle, but now its transverse position has changed to $x_0 + f\,\tan\theta\approx x_0 + f\,\theta$. Transfer matrices always describe a linearization of an optical system's behavior about the state of a chief ray, so the small angle approximation always holds. So now, our ray has the state:
$$\left(\begin{array}{c}x_0+f\,\theta\\\theta\end{array}\right)\tag{3}$$
so your task is to work out what the transfer matrix in (1) does to this state, i.e. simply to left multiply (3) by (1). In particular:

*

*What is particularly noteworthy about the angle of the ray after the transformation?

*Work out what this means physically.

and the answering of these questions should show you how the transfer matrix encodes the lens's collimating behavior for all points on the focal plane.


text:
Q: When to use mid-sentence commas when adding a formal name Where is it appropriate to insert a comma when putting a persons name in the middle of a sentence, such as when writing an email or letter.  Is it really before AND after?
Examples:

Thank you for writing me back, Michelle, and all the best to you in
  2019!
I really appreciate you taking the time to meet with me, Michelle, but I hope we don't have to meet under these circumstances again.

Is this correct?
I feel like I use commas too often and this is one scenario where I always question myself.

A: According to the eminently accessible Indiana University East writing center website. Commas are used in this fashion to indicate Direct Address:

6.USE A COMMA TO INDICATE DIRECT ADDRESS.
Rule: When a speaker in a sentence names the person to whom he is speaking, this addressing of his audience is called direct address.  Direct address is indicated by the use of a comma or commas, depending upon its placement within the sentence.

*

*I think, John, you're wrong.

*John, I think you're wrong.

*I think you're wrong, John.

See this and more for yourself at https://www.iue.edu/hss/writingcenter/documents/Commas.pdf

A: It is an example of vocative case. Names that are being addressed directly are said to be in vocative cases. It is always treated as parenthetical text set off by comas. Comma.guide dealing with vocative comma tells us that in language like Latin the vocative case would involve changes to the ending of nouns and various other tortures. But in English, we can simply mark the noun off with commas before and after; job done.
Michelle , the name is used exactly in vocative case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I trigger ajax validation when a button is pressed? I am using the Yii CActiveForm widget to create a form.  On the same page, but separate from the form, I have a button that pops up a JQuery modal dialog box.
Here's what I would like to do (but cannot figure out how to do):  When the button is pressed, I would like to validate the form using Ajax before popping up the modal dialog box.  If the form has an error, I would like to display all the errors and prevent the modal dialog from opening.  If there are no errors, then the modal dialog box should open.
How can I call the Yii ajax validation from within a button click event?


text:
Q: req.query undefined in Nuxt Express Middleware get request Not a pro with things like server middleware, but stuck without much clues.
In a vue component I am retrieving data with axios with this:
  axios
    .get('/api/getDailyFeedback', {
      params: {
        start: '2018-05-01'
      }
    })

Which goes to the express (version 4.16.2) server middleware setup in Nuxt. I have gotten normal get and post requests to work fine but the problem is when I want to pass in a parameter into a get request like the below:
router.get('/getDailyFeedback', (req, res) => {
   console.log('Query:', req.query.start);
   //do stuff
});

What little experience I had with Express 4, it took me a little bit of time to realise why parameters passed in the body of a post request were undefined, but it was because I needed to add body-parser.json() to my nuxt config since they removed that from the main express package. Similarly I thought I needed bodyParse.urlencoded but that has not worked. This is the line I added to my nuxt.config:
serverMiddleware: [bodyParser.urlencoded({ extended: false }), bodyParser.json(), '~/api'],

I am unsure if the content type is not set correctly or I am missing something simple here. I know I am able to use various libraries to grab the parameters from the url string which I have access to, as Axios is working as expected and adding my 'params' object onto the end of my get request. But a lot of solutions I have seen to other problems is 'oh its as simple as accessing req.query' Alas Express fails to define a req.query object, or even req.params or req.body.
Hopefully that is enough detail to go on, thanks a lot for reading and any suggestions.

A: Well that's an unpleasant surprise to try to use the get request in Nuxt for the first time, isn't it? Nuxt creates a connect instance which leads to some pitfalls. It's req is the Node.js http request object, so it doesn't have the query property and request.body is also being skipped in get requests!
But there is a way for everything. Your code:
  axios.get('/api/getDailyFeedback', {
      params: {
        start: '2018-05-01'
      }
    })

Translates to the following URI call:
/api/getDailyFeedback?start=2018-05-01
So you've got all the params in the URI where you can retrieve them from via url parsing. Module url ships with Node.js by the way.
const url = require("url");

router.get('/getDailyFeedback', (req, res) => {
   let queryData = url.parse(req.url, true).query
   console.log('Query:', queryData.start)
});

I wrote a little helper that extends req with a custom property. Here's the code:
router.use((req, res, next) => {
  var theQuery = url.parse(req.url, true).query
  req.queryData = theQuery
  next()
})

Then you can use it like this:
router.get('/getDailyFeedback', (req, res) => {
   console.log('Query:', req.queryData.start)
});

Other way to pass params via get is by using optional uri segments:
router.get('/getDailyFeedback/:start?', (req, res) => {
   console.log('Query:', req.params.start)
});

A: I am using Nuxt 2.15 and I can access the query parameter like this req._parsedOriginalUrl.query

A: You can access Nuxt get params without additional modules.
Just use:

req.request.get()

A: For anyone else in the future

const { Router } = require('express')

Router.get('/orders', async (req, res, next) => {
    const request = req.query.sometext;
    res.json({data: request});
});

module.exports = Router;
<script>
    export default() {
        async mounted() {
            const orders = await axios.get(`/api/orders`, {
                params: {
                    sometext: 'bla bla'
                }
            });
       }
   }
</script>

http://expressjs.com/en/api.html#req


text:
Q: Get Last conversation row from MySQL database table I have a database in MYSQL and it has chat table which looks like this.

I am using this query for fetching these records
SELECT * FROM (
    SELECT * FROM `user_chats`
    WHERE sender_id =2 OR receiver_id =2
    ORDER BY id DESC
) AS tbl
GROUP BY sender_id, receiver_id

But my requirement is only 5,4 ID's records. basically my requirement id fetching last conversation in between 2 users. Here in between 2 & 3 user conversation has 2 records and we want only last one of them i.e. id = 5, here don't need id = 2.
So how we can write a query for that result?

A: SELECT
 *
FROM
 user_chats uc
WHERE
 not exists (
   SELECT
    1
   FROM
     user_chats uc2
   WHERE
     uc2.created > uc.created AND
     (
       (uc.sender_id = uc2.sender_id AND uc.reciever_id = uc2.reciever_id) OR
       (uc.sender_id = uc2.reciever_id AND uc.reciever_id = uc2.sender_id)
     )
  )

A: The following gets you latest record (assuming that the bigger id, the later it was created) meeting your criteria:
SELECT * FROM `user_chats`
WHERE (`sender_id` =2 AND `receiver_id` =3) OR (`sender_id` =3 AND `receiver_id` =2)
ORDER BY `id` DESC
LIMIT 1

which would be a good idea, if id is primary key and it rises along with rising value of created. Otherwise (if you are not sure that id rises when created rises) replace ORDER BY line with the following:
ORDER BY `created` DESC

Plus, in both cases, put proper indexes on: id (if it is your primary key, then there is no need to put additional index on it), sender_id and receiver_id (preferably composite index, meaning the single index for both columns), created (if you want to use ORDER BY created DESC instead of ORDER BY id DESC - otherwise there is no need for that).

A: try GROUP BY LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)


text:
Q: Deleting the last node in the linked list Please can you explain to me how this function deletes the last node in a single linked list
void deleend()
{

    Node *q;
    Node *p;

    for (q = head; q != NULL; q = q->next)
    {
        p=q;
        p->next=NULL;
    }
    delete q;
}

A: The deletion of the last item of a list is a pretty simple algorithm.
You need to loop throught the whole list until you reach a node with the next pointer equals to NULL. This is your last element, the element you want to delete.
So you need to free the memory allocated by this object and set the next pointer for your previous item to NULL. This is the most important thing since it avoids to get segfaults.
Now, about the code you posted, I see you are doing something pretty bad.. you're declaring *q and *p, then looping throught your list (pointed by a global Node* head, I suppose).
The issue is that with the code in your loop you're unlinking the first item from the linked list and then the loop ends because You're copying the pointer q in p and then setting it's next pointer tu Null which leads to setting q->next to NULL. The first iterations goes ""fine"" leading you to have the first element with next set to Null the second iteration finds the next set to Null and thus it stops.
NOTE: Before posting the code solution I'd like to know if you have pretty clear in mind what the algorithm purpose is, try make an attempt to fix your code, if you can't do it again I'll post the correct algorithm :)


text:
Q: cakephp 2.1 black hole in google chrome I am working on a plugin for cakephp 2.1
all things are working fine on localhost on all browsers
But this plugin is not working on google chrome on server however it is working fine on Firefox
I am getting Error: The requested address '/login' was not found on this server when I submit the form.
For ex.
http://umpremium.ektasoftwares.com/login
Please check this on google chrome as well as Firefox. Can somebody help me out??

A: I can reach that site in both Google Chrome and Firefox, using Chrome 18.0.1025.151


text:
Q: Cannot update record with children using Thymeleaf and Spring Boot - Getting NullPointerException I have looked in SO for similar problems and although I have found some relevant questions none have been answered. So I post my problem here hoping for better luck.
I have a parent record Resource with children (One-to-Many) ResourceSkills. I can display the values of both Resource and ResourceSkills on my Thymeleaf page that I use for editing the Resource, however on save I see in my controller class that ResourceSkills is Null. This results in a NullPointerException.
So here is the code:
Resource
@Entity
public class Resource {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Version
    private Integer version;

    private String firstName;
    private String lastName;

    @OneToMany (mappedBy = "resource", orphanRemoval=false, fetch=FetchType.EAGER)
    private List<ResourcesSkills> skills;

    @ManyToOne (fetch=FetchType.EAGER)
    @JoinColumn(name="project_id")
    private Project project;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public List<ResourcesSkills> getSkills() {
        return skills;
    }

    public void setSkills(List<ResourcesSkills> skills) {
        this.skills = skills;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }
}

ResourcesSkills
@Entity
@IdClass(ResourcesSkillsId.class)
public class ResourcesSkills {

    @Id
    @ManyToOne
    @JoinColumn(name="resource_id")
    private Resource resource;

    @Id
    @ManyToOne
    @JoinColumn(name = "skill_id")
    private Skill skill;

    @Version
    private Integer version;

    private boolean primarySkill;

    public Resource getResource() {
        return resource;
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public Skill getSkill() {
        return skill;
    }

    public void setSkill(Skill skill) {
        this.skill = skill;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public boolean isPrimarySkill() {
        return primarySkill;
    }

    public void setPrimarySkill(boolean primarySkill) {
        this.primarySkill = primarySkill;
    }
}

ResourceController
@Controller
public class ResourceController {

    ResourceService resourceService;
    SkillService skillService;

    @Autowired
    public void setResourceService(ResourceService resourceService){
        this.resourceService = resourceService;
    }

    @Autowired
    public void setSkillService(SkillService skillService){
        this.skillService = skillService;
    }

    @RequestMapping(value="resources", method = RequestMethod.GET)
    public String list(Model model){
        model.addAttribute("resources", resourceService.listAllResources());
        return "resources";
    }

    @RequestMapping(value="resource/{id}")
    public String showResource(@PathVariable Integer id, Model model){
        model.addAttribute("resource", resourceService.getResourceById(id));
        return "resourceshow";
    }

    @RequestMapping(value = "resource/new")
    public String newResource(Model model){
        model.addAttribute("resource", new Resource());
        model.addAttribute("skills", skillService.listAllSkills());
        return "resourceform";
    }

    @RequestMapping(value = "resource/edit/{id}")
    public String editResource(@PathVariable Integer id, Model model){
        Resource resource = resourceService.getResourceById(id);
        model.addAttribute("resource", resource);
        return "resourceform";
    }

    @RequestMapping(value = "resource/delete/{id}")
    public String deleteResource(@PathVariable Integer id){
        resourceService.deleteResource(id);
        return "redirect:/resources";
    }

    @RequestMapping(value = "resource", method = RequestMethod.POST)
    public String saveResource(Resource resource){

        /* AT THIS POINT resource.skills is NULL and save FAILS */
        ResourceService.saveResource(resource);
        return "redirect:/resource/" + resource.getId();
    }
}

And finally the Thymeleaf code:

Resource Details

        <form class="form-horizontal" th:object="${resource}" th:action="@{/resource}" method="post">
            <input type="hidden" th:field="*{id}"/>
            <input type="hidden" th:field="*{version}"/>

                First name:

                    <input type="text" class="form-control" th:field="*{firstName}"/>

                Surname:

                    <input type="text" class="form-control" th:field="*{lastName}"/>

                        Skill
                        Primary

                        Skill Description
                        <input type="checkbox" name="primary" th:disabled="disabled" th:checked="${resSkill.primarySkill}" />

                Edit Skills

                <button type="submit" class="btn btn-default">Submit</button>

        </form>

The error I get is the following (for reference):
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
        at eu.kororos.ccplanner.controllers.ResourceController.saveResource(ResourceController.java:79) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
        at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]

A: Looks like you forgot to @Autowire the ResourceService and the SkillsService?


text:
Q: vue-spinner for page router I use vue-spinner and I have a project on codesandbox.
Main page is Home.vue with links on other components:
 <router-link to="/">Home</router-link>
 <router-link to="/helloworld">Hello World</router-link>
 <router-link to="/bigimg">Big Img</router-link>

main.js:
import Vue from "vue";
import App from "./App";

import router from "./router";

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  components: { App },
  template: "<App/>"
});

router.beforeEach((to, from, next) => {
  //loading = true;
  next();
});

I want to make loader like on fishtripr.com website (vue website).
Question: How I can make vue website loader and How can make loader (vue-spinner) when moving from page to page (like NProgress.start() & NProgress.done() )?

A: In my opinion the best way is to have a data property loading that is set to true (you can do this with a mixin) and then once the server has responded with the actual data you dismiss the loader by setting this.loading = false. I don't think you can put this logic inside the global router.beforeEach because it does not have access to the component. You would need to put the logic in the instance beforeRouteUpdate, which i don't think is ideal.

A: You need a mix of router.beforeEach and of manually updating the variable as Justin mentioned. Probably something like vuex makes sense in this case since many components will be changing the data.
In your vuex store
  mutations: {
    resetLoading(state){
      state.isLoading = true
    },

    // This needs to be called on each component individually
    finishedLoading(state){
      state.isLoading = false
    },
    ..

Something like this for the router
router.beforeEach((to, from, next) => {
  store.commit("resetLoading")
  next()
})

And then in your component
  ..
  created(){
    var self = this
    this.$store.dispatch("fetchData").then(function(){
      self.$store.commit("finishedLoading")
    })
  },
  ..


text:
Q: How to deserialize WSO2 Message Broker object message queue with a Talend tJMSInput I'm working on a talend job that allows me to get the content of a WSO2 Message Broker Queue.
However, when I get the message body of an 'ObjectMessage' using the Talend tJMSInput, the result is "Not supported .."
I want to deserialize the object in the queue before call the tJMSInput component.
I have two questions,

*

*How can I get the serialized content of the WSO2 Message Broker Queue
with the tJMSInput in Talend Data Integration ?

*How can I deserialize this Java Object in Talend Data Integration.

is it the right way to get all content of my java serialized object into the JMQ Queue.


text:
Q: Why check concurrent modifications when iterating thread-unsafe collections? The fail-fast mechanism for checking the concurrent modification in synchronized collections is reasonable, since these collections are considered thread-safe in multi-threads environment and thus they should be aware of the concurrent modification.
But I'm confused why those thread-unsafe collections like ArrayList which should work in single-thread environment also need to be aware of the concurrent modification in iteration?
Thanks for your reply in advance!

A: Don't mistake the "concurrent" in "concurrent modification" as referring only to multithreading.
You can get a ConcurrentModificationException in single-threaded code too:
List<String> list = new ArrayList<>();
list.add("");
Iterator<String> it = list.iterator();
list.add("");
it.next(); // ConcurrentModificationException


text:
Q: How to change table prefix when a user logs in to account? I am in new laravel, In my application When a user logs into his account I want to change the default database prefix from the env file. I setup wildcard subdomain for every users. When every user logs in I want to change  the database prefix according to the sub domain.
So is it possible to change the laravel prefix globally if a user logs in Laravel?. Please suggest me if there is any solution. Thanks is advance.

A: Of course you can:
config/database.php
'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'mysql_earth' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_EARTH_DATABASE', 'earth'),
        'username' => env('DB_EARTH_USERNAME', 'earth'),
        'password' => env('DB_EARTH_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

  'mysql_moon' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_MOON_DATABASE', 'moon'),
    'username' => env('DB_MOON_USERNAME', 'moon'),
    'password' => env('DB_MOON_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=forge
DB_USERNAME=forge
DB_PASSWORD=forgepw

DB_EARTH_DATABASE=earth
DB_EARTH_USERNAME=erth
DB_EARTH_PASSWORD=earthpw

DB_MOON_DATABASE=moon
DB_MOON_USERNAME=moon
DB_MOON_PASSWORD=moonpw

Use in your Controller example put your conditions on the connection and then you can have the query in each database:
$db = \DB::connection('mysql');
$db = \DB::connection('mysql_earth');
$db = \DB::connection('mysql_moon');

        $products = $db->table('products')
            ->distinct()
            ->select("*" )
            ->orderBy('products.id','asc')
            ->get();


text:
Q: Selenium Grid Extras 2.0.4 : org.openqa.selenium.WebDriverException: Error forwarding the new session I tried to use Selenium Grid Extras from the page: https://github.com/groupon/Selenium-Grid-Extras
I managed to use it successfully on my private machine. I ran the command "java -jar Selenium-Grid-Extras-Jar.jar" and after configuration (https://ibb.co/j4wZPH), I was able to see the nodes by going to the address http://localhost:4444/grid/console:

Then I ran the tests via IntellIj and everything passed as expected:
But when I try to do the same process on my corporate laptop, I get the error:

I will attach full log of this error:
kwi 24, 2018 12:07:06 PM org.openqa.selenium.remote.DesiredCapabilities chrome
INFO: Using `new ChromeOptions()` is preferred to DesiredCapabilities.chrome()`

org.openqa.selenium.WebDriverException: Error forwarding the new session
Empty pool of VM for setup Capabilities {browserName: chrome, version: }
Command duration or timeout: 157 milliseconds
<4 internal calls>
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$new$0(JsonWireProtocolResponse.java:53)
    at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$getResponseFunction$2(JsonWireProtocolResponse.java:91)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:545)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:209)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:132)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:145)
    at com.sii.BaseTest.RemoteWebdriverTestBaseDemoqa.setUp(RemoteWebdriverTestBaseDemoqa.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
    at org.testng.TestRunner.beforeRun(TestRunner.java:626)
    at org.testng.TestRunner.run(TestRunner.java:594)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
    at org.testng.TestNG.runSuites(TestNG.java:1144)
    at org.testng.TestNG.run(TestNG.java:1115)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: org.openqa.selenium.WebDriverException: Error forwarding the new session Empty pool of VM for setup Capabilities {browserName: chrome, version: }
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:26:55.152Z'
System info: host: 'BXKBFH2', ip: '192.168.56.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'
Driver info: driver.version: unknown
    at org.openqa.grid.web.servlet.handler.RequestHandler.process(RequestHandler.java:118)
    at org.openqa.grid.web.servlet.DriverServlet.process(DriverServlet.java:86)
    at org.openqa.grid.web.servlet.DriverServlet.doPost(DriverServlet.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.seleniumhq.jetty9.servlet.ServletHolder.handle(ServletHolder.java:860)
    at org.seleniumhq.jetty9.servlet.ServletHandler.doHandle(ServletHandler.java:535)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
    at org.seleniumhq.jetty9.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
    at org.seleniumhq.jetty9.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
    at org.seleniumhq.jetty9.servlet.ServletHandler.doScope(ServletHandler.java:473)
    at org.seleniumhq.jetty9.server.session.SessionHandler.doScope(SessionHandler.java:1564)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
    at org.seleniumhq.jetty9.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.seleniumhq.jetty9.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.seleniumhq.jetty9.server.Server.handle(Server.java:530)
    at org.seleniumhq.jetty9.server.HttpChannel.handle(HttpChannel.java:347)
    at org.seleniumhq.jetty9.server.HttpConnection.onFillable(HttpConnection.java:256)
    at org.seleniumhq.jetty9.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
    at org.seleniumhq.jetty9.io.FillInterest.fillable(FillInterest.java:102)
    at org.seleniumhq.jetty9.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
    at org.seleniumhq.jetty9.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:247)
    at org.seleniumhq.jetty9.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:140)
    at org.seleniumhq.jetty9.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:131)
    at org.seleniumhq.jetty9.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:382)
    at org.seleniumhq.jetty9.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:708)
    at org.seleniumhq.jetty9.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:626)
    at java.lang.Thread.run(Unknown Source)

And when I go to: http://localhost:4444/grid/console - I see this:
I tried to figure out why I get this error and found the answer (https://stackoverflow.com/a/42187314/7967616) that Selenium Grid doesn't have any node available with a browser that has the desired capabilities.
But during configuration I set the PORT 5555 for Selenium Grid Node and it works on my private laptop. I could not find the answer in the internet, so my hunch is that there is some problem with that PORT, but I don't know how I can check this.
Anyone had similar issues or problems or can help me with this issue?
Will be grateful for any help.
EDITED
ChromeDriver version is 2.38 (latest)
Chrome Browser version is 66.0.3359.117 (actual)
I made sure that I have latest version of ChromeDriver and Browser.

A: Unlock selenium extras, hub and node ports in firewall and then it should work

A: This error message...
Caused by: org.openqa.selenium.WebDriverException: Error forwarding the new session Empty pool of VM for setup Capabilities {browserName: chrome, version: }

...implies that the ChromeDriver wasn't able to initiate an active connection with the WebClient i.e Chrome browser.
In absence of ChromeDriver and ChromeBrowser versioning information it seems to be version compatibility issue between the binaries you are using as follows :

*

*Your chromedriver version is unknown to us.

*Your chrome version is unknown to us.

Solution

*

*Upgrade ChromeDriver to  current ChromeDriver v2.38 level.

*Keep Chrome version at Chrome v66.x levels. (as per ChromeDriver v2.38 release notes)

*Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

*Use CCleaner tool to wipe off all the OS chores before and after the execution of your test Suite.

*If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.

*Take a System Reboot.

*Execute your @Test.

A: My teammate helped me solve the problem. I had to unlock the ports in Windows Defender Firewall.

*

*Go to Windows Defender Firewall (Open as admin)

*Go to "Incoming rules"

*In section "Actions" add new Rule -> select Port -> Select:

*

*Once - TCP

*Secondly - UDP

*Provide ports (4444, 3000, 5555)

*Enable connection

Repeat the proces but:

*

*Go to "Leaving rules"

*In section "Actions" add new Rule -> select Port -> Select:

*

*Once - TCP

*Secondly - UDP

*Provide ports (4444, 3000, 5555)

*Enable connection

Reboot the system and set up the Selenium Grid Extras again. It worked!


text:
Q: (C++) Pointers to Pointers of objects in different classes everyone. I'm working on a final project for school and it's coming along great, but I've run into a bit of a problem with trying to use a pointer to a pointer. I'll do my best to explain the problem below:
So I have a class called Player that sort of looks like this:
class Player
{
    Player();
    int health;
    void adjustHealth(int);
};

Player::Player()
{
    health = 40;
}

void Player::adjustHealth(int adjust)
{
    health += adjust;
}

I have another class called Shelter, that include "Player.h" and looks a little like this:
class Shelter
{
    Shelter();
    Player* player;     // Create a pointer to Player class.
};

In the Shelter header file, I have the following in my default constructor:
Shelter::Shelter()
{
    ...Other code here.
    player = new Player();
}

In the Shelter header file, I use this new player for things like:
 player->adjustHealth(-1);  // Subtract one health from the player.

Which works great.
The problem I'm facing is with creating another class called Church, that is in a separate header file and acts as a separate location in the game. I want Church to use the same player that Shelter does, so it has all of the same stats, etc, rather than creating a new player in Church (which is what I did in Shelter.h).
Right now, I have something like:
class Church
{
Church();
Shelter **cplayer; // This is supposed to be the pointer to the pointer.
};

The default constructor is where I'm having my problem. I want to use the same player from Shelter, not create a new player like I did in Shelter.
Church::Church
{
    What should I do here?
}

I've tried a number of things, but I can't quite get it working. Eventually I want to be able to do something like this:
   player->adjustHealth(-1);    // Subtract one health from the player.

Only in Church, so that player's stats, like health, are adjusted no matter which location they are in.
I hope my question makes sense. If not, I can try to clarify better. Anyway, thanks in advance.

A:
The problem I'm facing is with creating another class called Church, that is in a separate header file and acts as a separate location in the game. I want Church to use the same player that Shelter does, so it has all of the same stats, etc, rather than creating a new player in Church

This sounds like an ideal situation to use std::shared_ptr.
class Shelter
{
    Shelter();
    std::shared_ptr<Player> player;     // Create a pointer to Player class.

    // Provide a public accessor
    public:
       std::shared_Ptr<Player> getPlayer() const { return player; }
};

and
class Church
{
    Church(std::shared_ptr<Player> pl) : player(pl) {}
    std::shared_ptr<Player> player;

    // You haven't explained in your post why you need this.
    // Maybe you don't need it.
    // Shelter** shelter;
};


text:
Q: Error: invalid types 'int[int]' for array subscript I want to type this form in my program: s1[k[I]], but it doesn't let me. How can I fix this? Here's my code:
#include <iostream>
using namespace std;
int main(){
    int N;
    cin>>N;
    string s1[N];
    for(int k=0;k<N;k++)
    {
        cin >> s1[k];
    }
    int counter=0;
    for(int k=0;k<N-1;k++)
    {
        for(int i=0;i<s1[k].size();k++)
        {
            if(s1[k[i]] == s1[k[i]])
            {
                cout << s1[k][i] << endl;
            }
        }
    }
    return 0;
}

A: Using the index ([]) operator is generally for arrays. But in this statement: if(s1[k[i]]==s1[k[i]]), k is an int, not an int[]. So how can you index an integer?
Additional: Don't use using namespace std; as it isn't a good practice.

A: Looks like you tried to join different ideas that don't realy want work together, mixing char arrays and std::strings can be done but is a no good idea because is messy.
As you can see in the example, use the std::string as intended and that's it.
#include <iostream>

int main(){
    int N, i;

    std::cout << "Add a number -> ";
    std::cin  >> N;

    std::cout << "Add a string -> ";
    std::string string;
    std::cin >> string;

    // recomended method
    std::cout << "From std::string -> " << N << " | "  << string << std::endl;

    char * char_vec = new char [string.length()];
    memcpy(char_vec, string.c_str(), sizeof(char) * string.length());

    std::cout << "From array -> " << N << " | ";
    for(i = 0; i < string.length(); i++){
        std::cout << char_vec[i];
    }
    std::cout << std::endl;
    delete [] char_vec;

    return 0;
}


text:
Q: Curious about the text when booting So whenever I boot up Ubuntu or shut it down, it displays the whole process on black screen with white text, instead of showing only the loading screen of ubuntu.  Why is that?  It does not look really good..

A: If you want to disable the text boot, you can do that. Here's how:

*

*Open a terminal window (press Ctrl + Alt + T) and to edit the /etc/default/grub file type:
sudo nano /etc/default/grub
this should open the file. Look for the line GRUB_CMDLINE_LINUX_DEFAULT= and change its value to "quiet splash" so that the line would look like GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

*Press Ctrl + O to save the edits, and Ctrl + X to exit the editor,

*Now, run this command:
sudo update-grub

A: Many Linux distros will display the boot loading process and the shutdown process in a command-line style. This happens before the window manager has loaded, and after it has closed down. It's normal, though not always pretty. I've never investigated if there are any methods to make those processes "quiet". In some cases, it can be handy if something goes awry during those processes, as it is a command shell of sorts and you might be able to recover from an error though it, or see what process is causing problems.


text:
Q: Removing features with 0 importance is changing the predictions I am working on a binary classification model using LightGBM.
After fitting the model, I decided to analyse feature importances. I have found out that values of some of the feature importances are equal to 0. feature_importances_ is taken as default, so the method is split.
I decided to make a test and remove a few of those variables, expecting the results to be the same as before. The model results (predictions for some of the records and hence ROC-AUC scores etc.) are changing. When changing importance_type to gain, those variables still give value of 0 and removing them still make the same difference in predictions, obviously.
My question is: how come, if those variables have never been used to make even 1 split?


text:
Q: Retriveing blob content from sqlite database error I have a table in which my 2nd field is of type blob.
Now when i am trying to access the contents of this field i am getting the following error.
CODE
SQLiteDatabase sb= openOrCreateDatabase("/data/data/helios.maggi/Recipe.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
if(sb.isOpen())
   Log.i("mytag","the database is open "+sb.getPath());
   //sb.execSQL("drop database Recipe");
   Cursor c = sb.rawQuery("SELECT * FROM RecipeDetails", null);
   byte []myarray = c.getBlob(c.getColumnIndex("recipeimage"));

ERROR

02-06 19:54:16.626: ERROR/AndroidRuntime(1812): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4

What is causing this error? I have verified that the content of the field recipeimage is blob, this is because i extracted the table from the device and checked the field names myself. the second field is of type blob and has 4 entries.

A: Apply this
Cursor c=db.query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)

Example
get the name of the Student from the student table to apply this query.
Cursor c=db.query ("student",null,"name like 'jon'",null,null,null,null);


text:
Q: Deploy bitbucket public repo as application dependancy through composer on Heroku My application's dependencies are managed using composer, and one of dependency is from bitbucket public repo. Which is working fine locally, but when I deploy it to Heroku its not resolved and even not getting any error.
My composer.json is:
"repositories": [
    {
        "type": "vcs",
        "url":  "git@bitbucket.org:vendor/repo.git"
    }
],

"require": {
    "vendor/repo": "dev-master"
},

Thank for any help.

A: At last, I am able to fix problem. Actually it was SSH Keys issue as mentioned by @HonzaHaering in comment. I thought it will be useful for someone to add solution here.
First check do you have any SSH-Key on Heroku by:
ls ~/.ssh/id_rsa

If you don't have key then generate key using:
ssh-keygen -C test@example.com -t rsa

You will be prompted for passphrase enter passphrase if you want and at the end you will be presented with fingerprint etc. on successful key generation.
Than go to bitbucket account and follow instructions to add generated SSH Key to account:
https://confluence.atlassian.com/display/BITBUCKET/Add+an+SSH+key+to+an+account


text:
Q: Android upload file to website threw html and php I'm getting a error when trying to upload a file to my website through android.
Once I click on the photo i get this:

this is my Main.java
    package test.com.phonegap.app;
import org.apache.cordova.DroidGap;
import android.os.Bundle;

public class Main extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

This is my HTML file  Where everything happens etc etc etc
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>File Transfer Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
    <script type="text/javascript" charset="utf-8">

        // Wait for PhoneGap to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // PhoneGap is ready
        //
        function onDeviceReady() {

        }

        function getImage() {

            // Retrieve image file location from specified source
            navigator.camera.getPicture(uploadPhoto, function(message) {
                    alert('get picture failed');
                },{
                    quality: 50,
                    destinationType: navigator.camera.DestinationType.FILE_URI,
                    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
                }
            );

        }

        function uploadPhoto(imageURI) {
            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = new Object();
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;
            options.chunkedMode = false;

            var ft = new FileTransfer();
            ft.upload(imageURI, "http://monaiz.byethost7.com/upload.php", win, fail, options);
        }

        function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            alert(r.response);
        }

        function fail(error) {
            alert("An error has occurred: Code = " = error.code);
        }

        </script>
</head>
<body>
    <button onclick="getImage();">Upload a Photo</button>
</body>
</html>

And here is my PHP file loacated on my website
    <?php
print_r($_FILES);
$new_image_name = "namethisimage.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "/htdocs/".$new_image_name);
?>

Can anyone please give me a solution to this problem? Thanks!

A: remove this line from your PHP code

print_r($_FILES);

If you wanted to return if the file upload was successful or not you could do something like
$fileUploaded = move_uploaded_file($_FILES["file"]["tmp_name"], "/htdocs/".$new_image_name);

echo ($fileUploaded) ? 'File uploaded' : 'Upload failed';


text:
Q: Help for TRIAC strange behavior I try to rebuild an electronic board for an old potter's wheel. I try to build a "Phase Angle Control" with BTA16-800BWRG and MOC3043SR2M to control motor speed (the old board seem to use this principle).
Here is the old factory board :

Here is the full schematic of the old board
Here is my homemade new board :

Here is the full schematic of the new board
For instance I use filament light to build the firmware but I got problem, my output stage work only when I do measurement. (I use transformer to check signal with my oscilloscope).

*

*When I plug the transformer to isolate and see signal between pin 4 and 6 of the MOC3043 the signal on oscilloscope almost look like I was expecting and filament light is lighting (depend on pulse characteristics), all is OK while a leave transformer connected.

*When I remove the transformer the filament light is completely off, and when I try to see signal at the terminals of the lamp (with my isolation transformer) I got no signal at all.

*When I put the transformer at the load, filament light stay off and I got no signal at all.

*When I put the MCU pin "motor" at steady high level, the filament light is lighting and I can get signal with transformer at the load. (I got the full 50Hz wave without glitch)

To sum up, I'm be able to steady glow light with steady high level on "motor" pin, on when I put transformer on pin 6/4 of the MOC3043 when I pulse the gate with pulse signal synchronized with a zero crossing detector.
This is the first time I use TRIAC and I don't understand what append.
Here is the interesting schematic part :

- Only filament light OR motor (with 16uF capacitor) is connected at the same time.
 - The motor, light and transformer characteristics came from measurement with ohmmeter and LC100-A
 - I try with and without R1
Here is the TRIAC gate signal with the /20 isolation transformer :

I could not get both signal (gate and load) because I got only one transformer
Here is the MOC3043 command signal :

In yellow : The zero crossing detector signal entering the MCU
In blue : The "motor" pin signal from the MCU. I know high level of pulse is very long but it's to be sure TRIAC is really fired
Can someone help me to solve the problem and calculate the right value for components for filament lamp and for motor ?
(I'm more comfortable with software than hardware, I need help)
EDIT 2019-11-29 (1)
Thank to I directly replace the MOC3043 by MOC3023 (without zero-crossing trigger) and I replace R3 by 130 ohms resistor to increase current in led to 14mA.
Here is the new schematic :

Now I'm able to control the phase for the filament light. YipHa !
Here is the signal at load with the /20 isolation transformer :

All is not perfect, I got some random glitch. Sometime the light quickly glow strongly. I use my transformer to capture the glitch
Here is the glitch capture at load with the /20 isolation transformer :

We can clearly see the glitch, the phase continue after crossing down to zero.
I don't think glitch came from my firmware, I could not implement the supplier recommended schematic for instance page 7 of MOC3023 datasheet
Here is the recommended schematic :

Do you think glitch can come from the lake of snubbering the MOC023 as it recommended on schematic ?
EDIT 2019-11-29 (2)
My glitch problem came from software problem, I try to "hand" build the pulse from a STM32 timer triggered by zero crossing interrupt. I update the timer period twice for low and high level of pulse with complicated "state machine" automaton. I got jig from flash latency and interrupt preemption.
Now I use a simple "output compare" timer (OC) in "one pulse" mode, and the output signal is very stable now use much less resources. Ready to implement motor control algorithm like PID or other algorithm...
I think I will re-route the board with the recommended MOC3023 schematic

A: If you want phase control, you can't use a zero-crossing optocoupler. They are designed to prevent phase control to minimize switching noise (EMI). Try a MOC3052-M instead. You will need to lower R3 significantly to get 10 mA. And don't aim for just 10, aim for 15 or more. My version of Jasen's quote -- aim between the goal posts (great quote, I may borrow it) is when margin is cheap, put in a lot.
Edit: Glitch issue: Put the optocoupler input on the scope at the same time. If the trigger pulse from the MCU extends into the next half-cycle, the next half-cycle will be full.
Make sure that your MCU zero-cross detector is not sensitive to noise. The AC input (mains) can have a tremendous amount of noise on it, your design needs to deal with this. This can be done in hardware or software.


text:
Q: Javascript Capturing Groups I am struggling with capturing and non-capturing groups in Javascript.
I have the following string
var string = "#Blah blah blah\n#ENV:This is env note 1\n#MISC:this is a misc note\n#ENV:this is env note 2\n\n";

I would like to capture each text that starting with #ENV: and ending with new line, without capturing the '#ENV:' tag itself. (i.e. I want to return ["this is env note 1", "this is env note 2"]
I have tried the following:
var capture = string.match(/(?:#ENV)([^\n]*)/gi);
// Returns: ["#Blah blah blah", "#ENV:This is env note 1", "#MISC:this is a misc note", "#ENV:this is env note 2"]

var capture2 = string.match(/(?:(#ENV))([^\n]*)/gi);
//Returns ["#ENV:This is env note 1", "#ENV:this is env note 2"]

Any advice is greatly appreciated.
Thanks
Leo

A: Two regexs have same result, you have to cut #ENV: from result

A: Found solution.
Problem comes from match method.
The following code works instead
var regex = /#ENV:(.*?)\n/gi;
var match;
var result=[];
while(match = regex.exec(string)) {result.push(match[1]);}


text:
Q: Empty List variable in Python I want to create an empty list variable in the function every time when the function is called. I have tried this but not working.
def funarr(initarr):
    global count
    arr'count'= []
    arr'count'.append(intarr[:1,:1])
    count += 1

count = 1

I want to print output like this:
print(arr1)
print(arr2)
print(arr3)

and so on how many times function called.
(Procedure: when the first-time function is called count var have intially value one so arr'count' (it is wrong syntax for create new empty list) create arr1 first time and second time arr2, arr3, arr4 and so on. Also I want to append the value in newly created list in function)

A: I hope this is what you are asking
count = 0
def funarr(arr):
        global count
        arr.append([])
        count += 1
        print('function has been called and count is '+str(count))
arr=[]
funarr(arr)
funarr(arr)
funarr(arr)
print(arr)

Adding one more answer after your explanation :
def funarr():
    global count
    exec("%s=%s" % ('arr'+str(count),'[]'),globals())
    count += 1

count = 1
funarr()
print(arr1)
funarr()
print(arr2)
funarr()
print(arr3)

A: Instead of having funarr create lists with unique names each time (this seems like a bad idea), I'd just modify a global.
$ cat so.py
_funarrs = []

def funarr(initarr):
    global _funarrs
    _funarrs.append(initarr[:1])

funarr([1, 2, 3])
funarr(["abc", "xyz"])

print(_funarrs)

$ python so.py
[[1], ['abc']]

You can put the new lists in a dictionary or something else if you want.


text:
Q: Designing Kalman Filter So, I was asked to design a Kalman filter and run some simulations to see the results.
Given equations:
x(k+1) = -0.8*x(k) + sin(0.1k) + w(k)
y(k) = x(k) + v(k)
where w(k) and v(k) are processing and measurment noises
w(k)~N(0, 0.01)
v(k)~N(0, 1)
I want to make sure that everything works fine and makes sense in my code.
A = -0.8;
B = 1;
C = 1;

% Covariance matrices
% Processing noise
W = 0.01;
Q=W;

% Measurement noise
V = 1;
R=V;

% Initial conditions
x0 = 0;
P0 = 0;
xpri = x0;
Ppri = P0;
xpost = x0;
Ppost = P0;

% State
Y = zeros(1, size(t,2));
X = Y;
X(1) = x0;

% xpri - x priori
% xpost - x posteriori
% Ppri - P priori
% Ppost - P posteriori

for i = 1:size(t,2)
    %Simulation
    Y(i) = C*sin((i-1)*0.1)+normrnd(0,sqrt(V));

    if i > 1

        % Prediction
        xpri = A*xpost+B*sin((i-1)*0.1);
        Ppri = A*Ppost*A' + Q;

        eps = Y(i) - C*xpri;
        S = C*Ppri*C' + R;
        K = Ppri*C'*S^(-1);
        xpost = xpri + K*eps;
        Ppost = Ppri - K*S*K';
        X(i) = xpost;
    end
end

plot(t, Y, 'b', t, X, 'r')
title('Kalman's Filter')
xlabel('Time')
ylabel('Value')
legend('Measured value', 'Estimated value')

Does this KF work properly? If not, what is wrong?

A: The code looks OK and the results also. What makes you suspicious?
Here is a generic Kalman-filter implementation as a function that you can check out if you want to double-check. But with the filter, its all about the tuning of the covariance matrices P, Q, R...
function [v_f,xyz] = KF(u,z,A,B,C,D,x0,P0,Q,R)
%% initialization
persistent x P
if isempty(x)||isempty(P)
   % state vector
   x = reshape(x0,numel(x0),1);  % ensure vector size

   if nargin < 8 || isempty(P0)
       P0 = eye(length(x)); %default initialization
   emd
   P = P0;    % covariance matrix
end

%% covariance matrices
if nargin < 9 || isempty(Q)
    Q = diag( ones(length(x) )*1e1;  % proess-noise-covariance
end
% % Q = 0 -> perfect model. Q =/= 0 -> pay more attention to the measurements.
%
if nargin < 10
     R = diag( ones(length(z)) ) *1e1;     % measurement-noise-covariance
end
% The higher R, the less trusting the measurements

%% prediction
x_P = A*x + B*u;
P = A*P*A.' + Q;   % covariance matrix

%% update
H = C;

K = P*H.'*(H*P*H.' +R)^-1;
x = x_P + K*(z - H*x_P);
P = (eye(length(x)) - K*H)*P;

%% Output
y = C*x;
end

In any case, I would suggest to transfer this question to the codereview-pages because you have apparently no problem and just want to review your code, right?


text:
Q: C#: Semi-Abstract Automatic Properties? In a base class, I want to define an abstract get, but at that point, I don't care about the set. How can I define a setter in my child class?
I tried a few things, but I can't get it to work. For example I tried :
public class BaseClass
{
    public abstract bool MyBool { get; }
}

public class ChildClass : BaseClass
{
    public override bool MyBool { get; protected set;}
}

And :
public class BaseClass
{
    public bool MyBool { abstract get; }
}

public class ChildClass : BaseClass
{
    public bool MyBool { override get; protected set;}
}

I know I can workaround this by not using automatic properties in the child class and directly setting the underlying field instead of creating a setter, but I'm looking for something better.
Edit: I don't want to add an abstract setter in the BaseClass.

A: It may make more sense to use an interface rather than a base class. Then you simply have the classes that need to provide that property implement that interface.
For instance, you can create this interface:
public interface IBoolable {
     bool MyBool { get; }
}

Then it is still valid to implement the interface like so:
public class BoolableItem : IBoolable {
     public bool MyBool { get; protected set; }
}

Done this way, your code can safely assume anything that implements IBoolable has a property called MyBool that is at minimum read-only.

A: One solution is to make MyProperty not abstract but delegate its implementation to an abstract protected property that children must override:
public abstract class BaseClass
{
    public bool MyBool { get { return MyBoolInternal; } }
    protected abstract bool MyBoolInternal { get; set; }
}

public class ChildClass : BaseClass
{
    protected override bool MyBoolInternal { get; set; }
}

A: You have to make up your mind what behavior you want: if it is defined as abstract then a deriving class MUST implement it.
So what you should do is this:
public abstract class BaseClass
{
    public abstract string MyProperty { get; set; }
}

public class DerivedClass : BaseClass
{
    public override string MyProperty
    {
        get { return "myValue"; }
        set { /* do nothing, not applicable for this class */ }
    }
}

Don't throw the NotImplementedException - that is not what you want, you simply want the setter to do nothing for some child classes.

A: To leave it ambiguous whether you want a setter in inherited classes would violate OOP principles--that is, if a class (abstract or not) has a public/protected setter (abstract or not), then all inheriting classes must also; if a class does not, then inheriting classes must not.
Another way to think about this is to consider properties such that read-only or read-write is part of the contract of the class.  Since instances of inheriting classes must adhere to an "Is-a relationship" (the LSP), inheriting classes cannot "add a setter" where the main class didn't have one, because the fact that the main class had a property without as setter is part of the main class definition.  In effect, since the main class cannot change the property in question via a setter, therefore all inheriting classes MUST guarantee the same behavior.
Consider using a protected backing field; then you can split this property into a read-only property and a separate setter method. Then, the main class can have the property only and the subclass can have a setter method that the main class doesn't know about.  However, I'm not sure this would be a good design either.


text:
Q: Quick start with Murky for Mercurial? I just started using Mercurial, and I'm having some difficulties. I'm using Murky for Mercurial.
I have several projects' files at localhost, want to keep them local to work on, and then upload to a server. So:

*

*Created a folder named "_reps" at localhost to keep all repositories.

*Opened Murky app

*Repository > New Local

*Created rep as project name. (under _reps folder)

Now how can I add files to this project rep? How can I relate the project with this _rep, and work on changes?

A: With Mercurial, you keep your repositories generally inside the working directory (inside a .hg dir; which should be hidden by default on OS X). So I'm guessing you should just do New Local in your current project dir (not under the _reps thingy you created), then start adding files.


text:
Q: JSON.parse() not working even though JSON string is valid I am trying to post a form through AJAX jQuery. The PHP script to which it points returns a JSON encoded array. But, at the receiving end on the main page JSON.parse() is not working.
Please suggest if I am missing on some file types which need to be included
Here is my code.

< script type = "text/javascript" >
  $(document).ready(function() {
    $("#send").submit(function() {
      //$("#submit_form").html('');
      $("#modal-text2").html(" 0) {
          alert("Hi");
        }
      });

      //Important. Stop the normal POST
      return false;
    });
  });
< /script>

The JSON encoded array which is being sent back by the PHP script is:
{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}

A: don't know if its the cause of hte problem or if its just a typo in here, but you have a typo in the following line:
</br

you aren't closing the first linebreak, and the slash should come after the br - also not sure why you have so many quuotes in that html block - it should be :
$("#modal-text2").html("

DATA VALIDATION IN PROCESS !!! PLEASE WAIT
")

A: *

*You should console.log(data) to check if the data value has any problem.

*use try/catch to catch message if error happened in JSON.parse.
try {
  var decode = JSON.parse(data);
}catch(e){
  console.log(e) ;
}

*Make sure your php responses the json in the right way. Or there may have some invisible character and make the problem.
<?php
  $data = ... ;
  header('Content-type:application/json;charset=utf-8');
  echo json_encode($data) ;
?>

A: I thought there is a sytax error in your script just check it out in the last line of script the closing tag of < /script> has space, remove it and try -
</script>

i execute the parsing snippet of your code it is working fine.
var data = '{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}';

    var decode = JSON.parse(data);

     if (decode.err > 0) {
        alert("Hi");
      }


text:
Q: apksigner: command not found Specifications:

*

*Android Studio Version: Android Bumblebee

*Android Build SDK Build-Tool : 30.0.3

*Android SDK Command-line Tools: 7.0

I am trying to sign apk using apksigner. I am using this command in my Android Studio Terminal
apksigner sign --ks release.jks app.apk

I am following the official documentation but I am getting this error
bash: apksigner: command not found

When I dig further I found that Android/sdk/cmdline-tools/7.0/bin does not have apksigner it has following command line tools

What am I missing here?
I tried downloading cmdline-tools/6.0 and 3.0 but I don't see apksigner there.

A: apksigner is part of the SDK build tools. So, you should find it in $ANDROID_SDK/build-tools/30.0.3/, where $ANDROID_SDK is wherever you have your Android SDK installed.

A: You need to add a path variable in bash profile
I have written this answer based on the discussion with Commansware and Pierre on Commansware answer.
Let's discuss these questions to fix the command not found the issue on Android Studio.

Where is apksigner?

You can find apksigner at Android/sdk/build-tools/30.0.3

How to use apksigner using terminal?

*

*with absolute path (painful way)
$ ~/Library/Android/sdk/build-tools/30.0.3/apksigner verify ~/Desktop/app-release.apk

*with $path variable (the smart way)
$ apksigner verify ~/Desktop/app-release.apk
For this, you need to set a path variable in your bash profile

How to set path variable?

Add this to your bash profile
export PATH="$PATH:$HOME/Library/Android/sdk/build-tools/30.0.3"

Now you should be able to run $ apksigner verify ~/Desktop/app-release.apk anywhere even inside Android Studio terminal.

Still can't run the command on Android Studio?

In my case, I was not able to run apksigner command even after setting the path variable. So wrote export PATH="$PATH:$HOME/Library/Android/sdk/build-tools/30.0.3" on Android Studio terminal. And it worked!
Extra discussion
apksigner is part of Android Studio CLI tools. But I found that other Android Studio CLI tools (d8, avdmanager, aapt etc) command work by default except for apksigner. I don't know if it was just me or if it happens with others too.


text:
Q: linq query to return 1 row with complex values instead of 2 var query = from t1 in Context.Table1
    join t2 in Context.Table2 on t1.Id equals t2.Id
    join t3 in Context.Table3 on t3.Id equals t1.Id
    join t4 in Context.Table4 on t1.Id equals t4.Id into temp
    from temp_values in temp.DefaultIfEmpty()
    where t1.Id == id
    select new
    {
        Field1 = t1.Id,
        Field2 = t1.Field2,
        SpecialField = t4.temp_values
    };

I have this Linq query that returns 2 rows, because of the last join with Table4.
Notice that both rows have the same values on Field1 and Field2.
Any smart way to return instead just 1 row, that has SpecialField marked as a List that has all the temp_values stores in it?
so instead of:
Field1 / Field2/ SpecialField
1           /2          /{ Id=1, Prop1=2, Prop1=3}
1           /2          /{ Id=2, Prop1=12, Prop1=13}

I want:
Field1 / Field2/ SpecialField
1           /2          /List with 2 entries: { Id=1, Prop1=2, Prop1=3}, { Id=2, Prop1=12, Prop1=13}


text:
Q: A formula to work out $1+2+3+4+\cdots$ to the $n$th degree I am involved in a challenge, called the Press Up Challenge. This involves starting on day 1, for me the 1st January, and doing 1 press up. This is followed on day 2 with 2 press ups.
As you can see, day 32, the 1st February will involve 32 press ups.
This morning I managed my 49 press ups but it is getting harder!
So far I am simply keeping a log of what I have completed by way of adding each days number to my running total.
Is there a mathematical equation that will allow me to work out how many press ups I have achieved and will have achieved on any given day?

A: Call the value $f(n)$. Then:
$$\begin{align}2f(n)&=(1+2+\cdots+n)+(n+n-1+\cdots+1)\\&=(1+n)+(2+n-1)+\cdots+(n+1)\\&=(n+1)+(n+1)+\cdots+(n+1)\quad(\text{$n$ times})\\&=n(n+1)\end{align}$$
So:
$$f(n)=\frac{1}{2}n(n+1)$$

A: Another way: write the sum as
$$S= 1+ 2+ 3+ ...+ (n-1)+ n$$ and then as $$S= n+(n-1)+ (n-2)+ ...+ 2+ 1$$
Adding vertically that gives
\begin{align*}2S&= (n+1)+ (2+ n-1)+ (3+ n-2)+ ...+ (n-1+ 2)+ (n+ 1) \\ &= (n+1)+ (n+1+ (n+ 1)+ ...+ (n+1)+ (n+ 1)\end{align*}
And there are $n$ such sums so $$2S= n(n+ 1), S= \frac{n(n+1)}{2}.$$
(That method is attributed to Gauss when he was a child.)


text:
Q: Are the directrix line and focus unique for a conic?
How to prove of disprove the uniqueness of pair of (or single for parabola) directrix line and pair of focal points for a conics?

(Ignore the degenerate cases and the circle.)

A: Choose a generic parabola $y=ax^2$ (with $a>0$), defined as the locus of points having the same distance from a given focus $F=(0,1/(4a))$ and a given directrix $d$ of equation $y=-1/(4a)$ (the argument for an ellipse or hyperbola is similar but is left to the reader). We must prove that no other pair point/line can be a focus/directrix for the parabola.
Let $F'$, $d'$ be a possible focus/directrix pair. We show at first that $d'$ is parallel to $d$. For if it were not so, we could consider two points $P$, $Q$ on the parabola such that $PQ\parallel d'$, so that $P$ and $Q$ have the same distance from $d'$. That would imply $PF'=QF'$, hence $F'$ would lie on the perpendicular bisector of $PQ$. But a different line $P'Q'\parallel d'$ has a different perpendicular bisector, as you can easily show, parallel to the previous one, which is impossible because $F'$ cannot lie on two different parallel lines. (The case when $d'$ is parallel to the $y$-axis must be treated separately, but it's easily dealt with, as in that case $d'$ would intersect the parabola).
Hence $d'$ must be parallel to $d$. Suppose then $y=-k$ is the equation of $d'$, which entails $F'=(0,k)$. We must have $k>0$, for otherwise $d'$ would intersect the parabola and that leads to a contradiction. Consider then point $S=(\sqrt{k/a},k)$ on the parabola. Its distance from $F'$ is $\sqrt{k/a}$, while its distance from $d'$ is $2k$. Hence it must be $\sqrt{k/a}=2k$, that is $k/a=4k^2$ and $k=1/(4a)$: that proves that $F'=F$ and $d'=d$.


text:
Q: RoR: what are the benefits of erb in Rails code? I read an evocative post by Magnus Holm entitled Block Helpers in Rails 3, in which he points out that Rails 3 has bent the syntax of ERB too far.  (In 'original' ERB, an ERB construct can only span a single statement.  Rails 3 allows -- even requires -- spanning multiple statements.)
Which leads me to wonder: what are the real advantages to using ERB over Ruby's native string processing?  To dig into this, I took the example listed in the ERB documentation and tried it both in ERB and native Ruby strings.  It turns out that Ruby's rich library of string processing makes the translation really simple -- even intuitive.
Here's how it looks.  Common to both (lifted directly from the ERB documentation):
require "erb"

# Build template data class.
class Product
  def initialize( code, name, desc, cost )
    @code = code
    @name = name
    @desc = desc
    @cost = cost
    @features = [ ]
  end

  def add_feature( feature )
    @features << feature
  end

  # Support templating of member data.
  def get_binding
    binding
  end
end

Here's the template and the expansion written in ERB:
# ================================================================
# using ERB
erb_template = %{

      <title>Ruby Toys -- <%= @name %></title>

<%= @name %> (<%= @code %>)

<%= @desc %>

          <% @features.each do |f| %>

<%= f %>

          <% end %>

          <% if @cost < 10 %>
            Only <%= @cost %>!!!
          <% else %>
             Call for a price, today!
          <% end %>

  }.gsub(/^  /, '')
rhtml = ERB.new(erb_template)
# Produce results
@r1 = rhtml.result(toy.get_binding)

And here's the template written in pure Ruby:
# ================================================================
# using native Ruby strings
ruby_template = %q{"

      <title>Ruby Toys -- #{ @name }</title>

#{ @name } (#{ @code })

#{ @desc }

          #{ @features.map do |f|
               "
#{f}
\n"
             end.join }

          #{ if @cost < 10
               "Only #{ @cost }!!!"
             else
               "Call for a price, today!"
             end
           }

  "}
# Produce results
@r2 = eval(ruby_template, toy.get_binding)

These produce the same results (modulo whitespace).  Whether the ERB is simpler or more difficult is really a matter of taste and experience.  Judging from the number of questions about ERB and <%= ... %> vs <% ... %> vs <%= ... -%>, it appears that many people might have an easier time sticking to straight Ruby.
At the risk of starting some sort of holy war, why bother with a ERB when the native Ruby does the same job?  Do you think ERB is useful?  Should Rails accept "native Ruby" templates as well?

A: Magnus Holm here; good to see that you enjoyed the article :-)
First let's have a look at templates (yes, interpolation is a template) as an evolution from constructing a string with regular code:
# "Regular" way of constructing a string:
str = "Hello World: "
@users.each do |user|
  str << "How are you today, "
  str << user.name
  str << "? \n"
end

If we look at this code, it's evident that there are three patterns that repeat themselves:

*

*We have plenty of static text which are appended: str << "Static"

*We have some dynamic code which are appended: str << expresstion

*We have some blocks of code which change the control flow: @users.each
The great thing about ERB is that it's a perfect isomorphism of these patterns, which means that the user can think of it in terms of constructing the string the regular way. It's simply a way to construct a string with more focus on the static parts (since they are common) than the dynamic parts.
As the "purist" you are, you've noticed that this is not the lowest level. That is completely true: As long as you can evaluate Turing complete code, your template engine becomes Turing complete and technically you don't need anything else. You don't need blocks when you can simply nest your template engine.
Now we need think about the difference between low level and easy to understand. Yes, as you remove building parts you end up with a smaller core, but that doesn't necessarily make it easier to understand. You could draw an analogy to GOTOs: You can create any looping/conditionals using one single concept (GOTOs), but it turns out that it's easier to reason about code with if/while-statements. Why? Because a pattern appears! Instead of conceptually parse these patterns every time we look at them, it's easier to create abstractions which we can understand instantly.
In your example, there's one pattern which I believe will be used in any template: @users.map { |f| code }.join. This is exactly what ERB tries to abstract away so you can forget about the details and reason about your logic instead.
I also believe that if you're making a template engine simpler, but still make it Turing complete, you will abstract away these details anyway. You will realize that a pattern emerges and, as the DRY coder you are, you will start creating helpers and such. You're actually implementing your own little template engine on top of another. Now everything depends on the syntax flexibility of the base language whether or not you manage to abstract away the real details without too much other noise. For instance, there are Lisp flavours which supports static typing and pattern matching, but often it can't beat a syntax designed especially for the problem.
So, what are the real advantages to using ERB over Ruby's native string processing? In one sentence: It gives you nice syntax for common patterns.

Do you think ERB is useful?

Yes and no. I think interpolation is definitely not the right way. You will see patterns in your templates and nothing beats a custom syntax when it comes to templates. I think ERB is quite useful, but it lacks in some ways: It doesn't have the concept that blocks are also expressions:
# This block is more like a statement (we don't care about the return value)
@users.each do |foo|
  str << "Hello"
end

# This block is an expression
str << form_for(thing) do
  another_string
end

I have no idea if you can fix this with syntax, but right now it's "fixed" in each framework and there's no way to write block helpers that works across several frameworks. I'd love to see a more "official" way to deal with this.

Should Rails accept "native Ruby" templates as well?

Tilt already does, and the best solution would be if Rails switched over to Tilt, but I don't think "native Ruby" is that useful after all. If it's a short template, you can of course just use an interpolated string right in your code. And if it's a big template and you're going to move it out of your Ruby file, why not use a syntax designed for templates?

A: Rails is opinionated software. It ships with a bunch of 'default' ways of doing things which I guess the core team agree is their preferred way of doing things - erb, Test::Unit, prototype, etc. but there's nothing to stop you changing these (more so with Rails 3).
In my opinion, erb in Rails, even though not quite like normal erb is far, far nicer than ruby string interpolation - especially when it comes to blocks. Having to break back into strings for the HTML within the block looks horrible to me.
But then again, haml looks horrible to me while others swear by it and hate erb. It's all down to your preference. That's why Rails makes it very easy for developers to create their own templating systems. I don't know if one exists, but there's nothing stopping devs from creating a templating system which uses solely ruby strings like that.
So, in answer to "Should Rails accept "native Ruby" templates as well?", it already does. So long as someone else implements it ;)


text:
Q: How can I keep myself from flying through the windshield when I get in an accident? Once in a while I'll run my car into something and I'll go flying through the windshield and die. Other times, I'll ram into something at at even higher speed, stay inside the car, and be just fine.
Is there something that governs whether or not I'm wearing a seatbelt, or is this just random?

A: On PC, if you hold f, the character will buckle up, and won't fly out so easily.

A: Well, simply you can't. It's real life physics that when you drive into a solid object with that much force that your body is sent flying. I tried using a roll cage to see if it helps you at all but to no avail.
There are rumors going about that if you wait in the car long enough without driving you put on a seat belt, I'll try to test this theory tomorrow and if it's true I'll edit this question.

A: There is no way to buckle up, even if you sit there he still doesn't buckle up. He will put a helmet on, though. There has been plenty of times I flew through the window and lived.


text:
Q: Need to identify idle kafka consumers I have 3 spark-streaming consumers with same group id subscribed to a Kafka topic which has only one partition. So that one partition is assigned to one consumer and other consumers are idle. We need to kill the idle consumers. We are using Spark with YARN.
How to identify the consumer which is idle
Is there any commands from kafka to check which consumer is idle or is there any other we can achieve the same?

A: kafka-consumer-groups --group name will show all clients within a group and those assigned a partition
Although, it doesn't hurt to have backup processes incase one of the consumer threads fails

A: Try this -
$ kafka-consumer-groups.sh --describe --group group_name --members


text:
Q: Can I change lines of code in a loaded module in Perl? When I use the FLV::Info module to extract metadata from or merge multiple FLV files, I frequently receive a "Tag size is too small" error and then the module will just refuse to work. Someone issued a bug report here three years ago but there does not seem to be a fix.
Well, recently I find if I simply comment out the following lines of code in Tag.pm, one of FLV::Info's dependency modules like so:
=pod
if ($datasize < 11)
   {
      die "Tag size is too small ($datasize) at byte " . $file->get_pos(-10);
   }
=cut

FLV::Info will then readily do the work as expected.
I'm not sure if this is a very dumb question but I feel curious:
Is there a simple way of changing a couple of lines of code in a loaded module without modifying the original .pm file?
Any ideas, suggestions or comments?
Thanks like always :)
UPDATE
Big thanks to @Shwern. Your answer is highly satisfying :) Also thanks to @DVK for the suggestion and that "monkey patch" term and @brian for the book recommendation.
Here's my feedback for tests on a sample FLV file that would throw me "Tag size is too small" error if I use the original module without doing anything to it.
The "eval it back" approach solves the problem
use FLV::Info;

use Data::Dump::Streamer;
my $original = FLV::Tag->can("parse");
my $code = Dump($original)->Out;
#$code =~ s{\Qif ($datasize < 11)\E}{if (0)}; #This somehow won't work
$code =~ s{die "Tag}{warn "Tag}; #Let it warn but not die

no warnings 'redefine';
*FLV::Tag::parse = eval $code;

my $reader = FLV::Info->new();
$reader->parse('sample.flv');
my %info = $reader->get_info();
print "$info{video_count} video frames\n";
print $reader->report();

The "overide die to not die" approach also works
BEGIN {
    *CORE::GLOBAL::die = sub { return CORE::die(@_) };
}
use FLV::Info;

{
    local *CORE::GLOBAL::die = sub {
         return if $_[0] =~ /^Tag size is too small/;
         return CORE::die(@_);
};

my $reader = FLV::Info->new();
$reader->parse('sample.flv');
my %info = $reader->get_info();
print "$info{video_count} video frames\n";
print $reader->report();
}

The "redefine" approach, however, does not work as I expected.
I copy-and-pasted the original FLV::Tag::parse subroutine and commented out the lines of code exactly the way I modified the original Tag.pm file like so:
use FLV::Info;
no warnings 'redefine';
*FLV::Tag::parse = sub {
    ...
    ...
=pod
   if ($datasize < 11)
   {
      die "Tag size is too small ($datasize) at byte " . $file->get_pos(-10);
   }
=cut
   ...
   ...
};

my $reader = FLV::Info->new();
$reader->parse('sample.flv');
my %info = $reader->get_info();
print "$info{video_count} video frames\n";
print $reader->report();

but I got this error:
Unknown tag type 18 at byte 13 (0xd)

Well, even if copy-and-pasted exactly the same parse subroutine without any modification in my redefinition, I'm receiving the "Unknown tag type" error instead of "Tag size is too small".
This is strange!
For reference, the "eval it back" and "override die to not die" approaches will give me the following:
1992 video frames
File name                sample.flv
File size                5767831 bytes
Duration                 about 79.6 seconds
Video                    1992 frames
  codec                  AVC
  type                   interframe/keyframe
Audio                    1712 packets
  format                 AAC
  rate                   44100 Hz
  size                   16 bit
  type                   stereo
Meta                     1 event
  audiocodecid           10
  audiosamplerate        22050
  audiosamplesize        16
  audiosize              342817
  creationdate           unknown
  datasize               805
  duration               79.6
  filesize               5767869
  framerate              25
  height                 300
  keyframes              {
    >>>                    'filepositions' => [
    >>>                                         '780',
    >>>                                         '865',
    >>>                                         '1324122',
    >>>                                         '2348913',
    >>>                                         '2978630',
    >>>                                         '3479001',
    >>>                                         '3973756',
    >>>                                         '4476281',
    >>>                                         '4997226',
    >>>                                         '5391890'
    >>>                                       ],
    >>>                    'times' => [
    >>>                                 '0',
    >>>                                 '0',
    >>>                                 '9.6',
    >>>                                 '19.2',
    >>>                                 '28.8',
    >>>                                 '38.4',
    >>>                                 '46.32',
    >>>                                 '55.92',
    >>>                                 '64.88',
    >>>                                 '73.88'
    >>>                               ]
    >>>                  }
  lastkeyframetimestamp  73.88
  lasttimestamp          79.6
  metadatacreator        Manitu Group FLV MetaData Injector 2
  metadatadate           1281964633858
  stereo                 1
  videocodecid           7
  videosize              5424234
  width                  400

FINAL UPDATE
I've figured out why the "redefine" approach failed by turning on strict and warnings pragma. Thanks to @Schwern for the reminder :)
Add the following lines of code (copied from the FLV::Util module) first and then do the redefining of the FLV::Tag::parse subroutine.
Readonly::Hash our %TAG_CLASSES => (
   8  => 'FLV::AudioTag',
   9  => 'FLV::VideoTag',
   18 => 'FLV::MetaTag',
);

A: OK, Schwern's answer was pretty thorough, but here's one approach that will be less "bad"...
Go with his second approach (cut & paste the whole routine into your code and inject it after loading the original)... BUT... condition it on the specific version of FLV::Info (or FLV::Tag).
This way, you still have your monkey patch (is this technically considered a monkey patch?), BUT you remove one of the biggest reasons this approach would be considered "bad" - namely, that any upgrade to the module would possibly clash with your custom patched subroutine. If you guard the overwrite with the version check, you eliminate that concern.

A: Simple?  No.  But there are some crazy things you can do.  Here's some bad ideas.
One of the more obvious is to put a hacked copy of the .pm file into your project, somewhere so its seen before the system version.
Another is similar, but to cut & paste the whole routine into your code and inject it after loading the original.
use FLV::Tag;

no warnings 'redefine';
*FLV::Tag::parse = sub {
    ...copy of FLV::Tag::parse with your edits...
};

You could override die to not die when it sees that message.
BEGIN {
    # In order to override die() later, you must override it at compile time.
    *CORE::GLOBAL::die = sub { return CORE::die(@_) };
}

{
    local *CORE::GLOBAL::die = sub {
        return if $_[0] =~ /^Tag size too small/;
        return CORE::die(@_);
    }

    ...do your thing...
}

You could dump the contents of that subroutine back into Perl, do a string replace on the code, and eval it back.
use Data::Dump::Streamer;
my $original = FLV::Tag->can("parse");
my $code = Dump($original)->Out;
$code =~ s{\Qif ($datasize < 11)\E}{if( 0 )};

no warnings 'redefine';
*FLV::Tag::parse = eval $code;

Or you could walk the opcode tree of that subroutine and change the condition, which I leave as an exercise for someone with more time on their hands.
They are all bad ideas.  You're better off just changing the code in place and contacting the author again about it letting them know there's new information.


text:
Q: Scheduling events in a WSGI framework I've written a Python app that reads a database of tasks, and schedule.enter()s those tasks at various intervals.  Each task reschedules itself as it executes.
I'd like to integrate this app with a WSGI framework, so that tasks can be added or deleted in response to HTTP requests.  I assume I could use XML-RPC to communicate between the framework process and the task engine, but I'd like to know if there's a framework that has built-in event scheduling which can be modified via HTTP.

A: Sounds like what you really want is something like Celery. It's a Python-based distributed task queue which has various task behaviours including periodic and crontab.
Prior to version 2.0, it had a dependency on Django, but that has now been reduced to an integration plugin.


text:
Q: when Device Time Setting is in 24h Formate Get time is null I am having problem displaying proper date in my app. When user sets 24 hour format 'OFF' in his date time preferences..my app shows correct time. but when 24 hour format is set to 'ON' it shows nothing.
        NSString *FireDate_Str = [NSString stringWithFormat:@"%@:%@:00 %@",Hour_Str,Minute_Str,[[AM_PM_Btn titleLabel].text lowercaseString]];
        NSLog(@"FireDate_Str: %@ ", FireDate_Str);

//      FireDate_Str Formate: 02:02:00 am

        NSDateFormatter* df = [[NSDateFormatter alloc]init];
        [df setDateFormat:@"hh:mm:ss a"];
        NSDate *wakeTime = [df dateFromString:FireDate_Str];

But i Got wakeTime is (null) When Device time Setting in 24h is ON.

A: Try:
[df setDateFormat:@"HH:mm:ss a"];

See the unicode date formatting reference and Apple's Date formatting guide.


text:
Q: php error with $option['label'] === I put this code in a view.phtml file to retrieve a list of an attribute's values in all product page with a specific css style for a particular value. But there's php errors that I don't find.
Can someone help to resolve or share anything to do?  Thanks
 <?php $attribute_code = "my_attribute_code" ?>
 <?php $attribute_details = Mage::getSingleton("eav/config")->getAttribute("catalog_product", $attribute_code) ?>
 <?php $options = $attribute_details->getSource()->getAllOptions(false) ?>

        <?php foreach($options as $option): ?>

             <?php if ($_product->getResource()->getAttribute('my_attribute_code')->getFrontend()->getValue($_product);?>) === $option['label']): ?>

<?php echo $option['label']; ?>

             <?php else: ?>

<?php echo $option['label']; ?>

             <?php endif; ?>

        <?php endforeach; ?>

A: Synax error:
I removed this string: ;?>) from the first conditional statement and everything looks fine.
<?php if ($_product->getResource()->getAttribute('my_attribute_code')->getFrontend()->getValue($_product) === $option['label']): ?>


text:
Q: CSS display block doesn't work on a certain element In the sliding menu I created, I set up two close buttons (close-btn-2 and close-btn) for each one perform a different slide animation, triggered by jQuery (close-btn = slide right to left/ close-btn-2 = slide top to bottom) when screen change size.
When screen size shrinks, close-btn_2 is shown dynamically through jQuery (through the show method) whereas close-btn is hidden in the same way.
The only issue that I am facing is that, when I hover over close-btn-2, the  element changes color just around the "X" tag and not the entire block. Whereas the other close btn works just fine, as the other menu elements are.
What is wrong with the styling?
HTML:

        ×
        ×
        Accomodations
        Services
        Merchandising
        About us

CSS
.sidebar {
   height: 640px;
   width: 0px;
   background-color: black;
   float: right;
   overflow: hidden;
   position: absolute;
   top: 0;
   right: 0;
   transition: 0.5s;
   -webkit-transition: 0.5s;
   -moz-transition: 0.5s;
 }

.sidebar a {
   display: block;
   text-decoration: none;
   padding: 20px;
   font-size: 20px;
}

.sidebar a:hover {
   background-color: #ff0066;
   color: black;
   text-decoration: none;
}

Jquery
else if (width < 415) {

      $("#menu-btn").hide();
      $("#menu-btn-2").show();

      $("#close-btn").hide();
      $("#close-btn-2").show();

      $("#menu-btn-2").on("click", function() {
         $(".sidebar").attr("id", "topbar-on");
         $(".inner-title").fadeOut("fast");
      });

      $("#close-btn-2").on("click", function() {
         $(".sidebar").removeAttr("id", "topbar-on");
         $(".inner-title").fadeIn("slow");
      });

  }

A: As it turned out, I messed it up a little.
First of all, I decided to use a single close button (which by the way I switched to a button tag). I gave it a width and a height (in addition to the display:block css property) so to make it use the entire width of the menu and have the hover animation work the way I was looking for.
As @denis suggested, media query where much more easier to use for responsiveness, so I took rid of the all jQuery window.resize situation and used media queries to change style of the styling menu.


text:
Q: Contribution of gravitational waves to a maximum-entropy big bang Our universe did not have a maximum-entropy big bang. If it did, then by the second law of thermodynamics we wouldn't see the universe today in a non-equilibrium state. I've seen this explained by saying that the gravitational degrees of freedom were for some reason not activated, and this was the motivation for Penrose's failed CCC theory.
Is there any simple way to estimate quantitatively how much of a contribution gravitational waves should have made to the total number of accessible states in a maximum-entropy big bang? Or is there at least some simple argument that their contribution should have been significant?
Thermodynamically, I would think that gravitational waves would act a lot like electromagnetic waves, which tended to dominate in the early universe because of the way the equation of state of a massless particle connects the scale factor to the energy density.


text:
Q: SOLVED: Adding error messages to an array in bash procedure Here I placed working example, solved thanks to all you and completed with comments:
#!/bin/bash

errors=()  #array to store all errors
to=""      #a variable
DEST=""    #another variable
from=""    #and so on

e=$(mv "$from" "$to" 2>&1) #this command makes first error
if [ -n "$e" ] ;then errors+=("$e"); fi  #and this save it to array

e=$(mv "$DEST" "$to" 2>&1)   #so this makes second error
if [ -n "$e" ] ; then errors+=("$e"); fi #and this saves it to array

if [ ${#errors[@]} -eq 0 ]; then #if no errors
   echo OK
else           #if there are error (YES)
    echo "ATTENZIONE: SI SONO VERIFICATI DEGLI ERRORI DURANTE L'OPERAZIONE DI RESTORE:"
    for t in "${errors[@]}"; do  #display all errors
      echo "$t"
    done
fi

Thank you very mutch.

This is the first answare before the solution:
I need to add to an array all error messages in my bash file.
Thanks to  shellcheck.net and Cyrus and Freddy I adjusted code:
I did it:
#!/bin/bash
#set -x    #DEBUG
errors=()
to=""
DEST=""

if ! mv "$from" "$to" ; then errors+=("$?"); fi

if ! mvv "$DEST" "$to" ; then errors+=("$?"); fi

if [ ${#errors[@]} -eq 0 ]; then
   echo OK
else
    echo "ATTENZIONE: SI SONO VERIFICATI DEGLI ERRORI DURANTE L'OPERAZIONE DI RESTORE:"
    for t in "${errors[@]}"; do
      echo "$t"
    done
fi

the output that I obtain is :

ATTENZIONE: SI SONO VERIFICATI DEGLI ERRORI DURANTE L'OPERAZIONE DI RESTORE:
0
0

How can I do to obtain the right error messages in my array "$errors" ?
Thanks

A: The problem is that you aren't getting the exit status of the command (e.g. mv "$from" "$to"), but of the negated command (e.g. ! mv "$from" "$to") -- since the command failed (nonzero exit status), the negated status is success (zero). In order to do this, you need to avoid negating the status between the command and when you record the status. The easiest way I know of to do this is to use || instead of if, like this:
mv "$from" "$to" || errors+=("$?")


text:
Q: php eregi() problem I have this problem with my code, the page is redirecting and wouldn't stop.. The browser stop it because it's redirecting all the time, and I have a global.php file that included in all php pages, so I putted this code for the session and it went like what I said
if (!session_is_registered('username')) {
    if(!eregi('login.php', $PHP_SELF)) header('Location: login.php');
}

Also global.php included in login.php, but when I start it on the web server of my site, it does what i said before, but on my based server on computer it works fine, so please help me fast
and sorry for my english..

A: Try this:
session_start();
if (!isset($_SESSION['username']) && stripos($_SERVER['PHP_SELF'], 'login.php') === false) {
    header('Location: login.php');
}

Both session_is_registered() and eregi() are deprecated functions and shouldn't be used. Plus, regular expressions are overkill for what you're doing anyways.

A: Try:
if (!isset($_SESSION('username'))) {
    if(FALSE === strpos($_SERVER['PHP_SELF'], 'login.php')) {
      header('Location: login.php');
      exit();
    }
}

Some Suggestions:

*

*Make sure that you have session_start() placed on top of your script

*Use isset($_SESSION.......

*Use strpos instead of deprecated eregi

*Don't use deprecated session_is_registered

*Use exit/die after header redirect

*It is $_SERVER['PHP_SELF'] not $PHP_SELF

*Use error handling, put these lines on top of your script:

*

*ini_set('display_errors', true);

*error_reporting(E_ALL);


text:
Q: Fonts on launch screen are different than main storyboard On Xcode 6.3.1 I created a launch screen for my app with the same initial ViewController for the app.
The problem is that when the app is launched all the fonts have a slightly different size.
I'm using the Headline and Caption 1 text styles on the labels.
There are some pictures below to make the problem clearer.
Thanks!
Launch screen:

Main Storyboard initial view controller:

The difference is noticeable when superimposing both images:

A: It's because during launch screen is being shown, the custom fonts in your app aren't loaded yet. I would advise you to use an image on the launch screen if you really need to use custom fonts.

A: You can't use custom fonts on the Launch screen.
Only standard system fonts.
System will automatically replace your custom font to system during runtime.


text:
Q: Weird sum that is almost definitely not $\sqrt 2$ I have not the ability to compute more than four digits of
$$\sum_{n=1}^\infty \frac{1}{n^2 H_n^{(\ln n)}}$$
$H_n^{(m)} = \sum_{k=1}^n \frac{1}{k^m}$ is the generalized harmonic number.
I know this is the weirdest sum and it offers me no actual interest.  All I know is that the decimal number starts off as $1.414...$ and I want to settle my mind that it is not actually $\sqrt 2$. That would be crazy. I have no reason to expect it. I just want some confirmation.
My calculations were from Desmos here https://www.desmos.com/calculator/helb1dgf1g.