text:
Q: Maven multi module project - start module from another module? I'm a maven newbie...maybe someone can help.
Is it possible to start a module from another?
For example:
My modules: F-Frontend, B-Backend
Now i start my frontend-module via jetty, but i need the backend functionality and need to run the backend-module too.
Is it possible? Any ideas?
Thanks a lot
PS. I'm using intelliJ
UPDATE
parent pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xxx.maven</groupId>
    <artifactId>project-name</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>project-name-parent</name>
...

frontend pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>project-name</artifactId>
        <groupId>com.xxx.maven</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>project-name-frontend</artifactId>
...
<dependency>
            <groupId>com.xxx.maven</groupId>
            <artifactId>project-name-backend</artifactId>
            <version>1.0-SNAPSHOT</version>
</dependency>

...

backend pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>project-name</artifactId>
        <groupId>com.xxx.maven</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>project-name-backend</artifactId>
    <packaging>jar</packaging>
...

UPDATE 2
After mvn deploy backend.
 [WARNING] The POM for com.xxx.maven:project-name-backend:jar:1.0-SNAPSHOT is missing, no dependency information available
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1.285s
    [INFO] Finished at: Wed Sep 09 15:45:13 CEST 2015
    [INFO] Final Memory: 13M/304M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal on project project-name-cmf-frontend: Could not resolve dependencies for project com.xxx.maven:project-name-frontend:jar:1.0-SNAPSHOT: Failure to find com.xxx.maven:project-name-backend:jar:1.0-SNAPSHOT in http://maven.vaadin.com/vaadin-addons was cached in the local repository, resolution will not be reattempted until the update interval of vaadin-addons has elapsed or updates are forced -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

A: Maven modules are not separate applications. The different modules can be used for specifying different parts of an application as different Jars, for reusability.
What you really start is an application (or war, etc). Where a project may link to a submodule by importing that jar.
parent pom need to call the modules to build (and need to be ran out of the pom.xml location of the parent :
<modules>
    <module>front-end</module>
    <module>back-end</module>
</modules>

So do you mean import a different jar through the pom.xml?
For more information on jetty-maven-plugin
Pom.xml like:
<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>parent.project</groupId>
        <artifactId>artifact</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>group_id</groupId>
            <artifactId>artifact_id</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            ...<!-- add plugin for mvn jetty:run (check the name to match your project name) -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.3.1-SNAPSHOT</version>
                <configuration>
                    <war>${project.basedir}/target/mycustom.war</war>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
Q: Spring Security и нормализованная база данных В Spring Security класс JDBCDaoImpl по умолчнаию использует в качестве первичного ключа имя пользователя, а не id, что у меня (джуна) вызволо недоумение. Если я не ошибаюсь, то нормализованная бд для хранения пользователей состоит из 3-ёх таблиц:

*

*[таблица пользователей] id,username,password

*[таблица ролей] id, имя роли

*[связующая таблица] id пользователя - id роли

Как я понял, для того, чтобы заставить Spring Security работать с первичным ключём id, нужно писать свою реализацию JDBCDaoImpl или UserDetailsService.
Подскажите в чём я прав/не прав. Меня смутило, что разработчики Spring Security не сделали встроенную реализацию через id, возможно, это и не нужно и я просто этого не понимаю.
P.S.
В Spring Security реализована работа с пользователями через бд, но на основе двух таблиц, а не трёх, как в моём примере.
1 - ая это имя пользователя/пароль и тд, а во второй имя пользователя - имя роли.

A: Лучше не гадать, как устроена схема для стандартной реализации JdbcDaoImpl, а просто посмотреть в документации: https://docs.spring.io/spring-security/site/docs/3.0.x/reference/appendix-schema.html
В вашей реализации уникальными являются и id, и username одновременно - не бывает двух пользователей с одинаковым username. В результате получается дублирование информации (дополнительная нагрузка на дисковую и систему), мусор в базе (надо отдельно проверять уникальность username) и мусор в коде клиента.
Вместо этого стандартной схеме spring security из этих колонок оставлена только одна - username.
Промежуточная таблица у вас получилась тоже как следствие наличия id. Вместо этого в Spring Security таблица authority индексируется по композиции username+authority - именно в таком виде, в котором их чаще всего зовут в реальных приложениях.
Если вы понимаете что да - вам обязательно нужен id - вы просто идете и реализуете это поведение. Это архитектурный вопрос, в архитектурных вопросах вы наедине со своей идеей. Всегда нужно знать, что хочешь конкретно ты, а не бездумно копировать стандартное поведение со Spring Security или откуда-то еще. Поэтому в вопросе было очень неплохо также иметь и аргументацию за использование id, чтобы отвечающие могли отталкиваться от нее.

redpajama_set_name: RedPajamaStackExchange


text:
Q: fetch is not giving the correct JSON response in ReactJS? I am trying to use fetch method on API endpoint but I am getting some unexpected error. I am not able to view JSON data in my brower's console.
app.js:
import React, { Component } from 'react';
import './App.css';

class App extends Component {

    componentDidMount() {
        fetch('www.flymine.org/query/service/search?q=BRCA1')
            .then(res => res.json())
            .then(res => {
                console.log(res)
            })
    }

  render() {
    return (
      <div>

      </div>
    );
  }
}

export default App;

Error screenshot:

A: Add the protocol http:// before the URL, like:
componentDidMount() {
        fetch('http://www.flymine.org/query/service/search?q=BRCA1')
            .then(res => res.json())
            .then(res => {
                console.log(res)
            })
    }

A: Currently, you're using a page-relative URL: www.flymine.org/query/service/search?q=BRCA1. That means that if you do that fetch, the full URL will be something like http://localhost:3000/www.flymine.org/query/service/search?q=BRCA1. Unless you're running a server on port 3000 that does web requests and returns the results, that's not the right URL.
To make it protocol-relative, put // in front of it. Then it'll take the protocol from the page (http or https) and add //www.flymine.org/query/service/search?q=BRCA1 to it, giving us http://www.flymine.org/query/service/search?q=BRCA1 or https://www.flymine.org/query/service/search?q=BRCA1. Or add http:// in front of it to make it specifically http (since they don't support https):
fetch('http://www.flymine.org/query/service/search?q=BRCA1')
  .then(res => res.json())
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.error(err);
  });

Live Example on JSBin
Note that if you're doing this in a browser, the only reason it works is that they specifically allow all origins via Cross-Origin Resource Sharing. If they didn't, you'd be blocked by the Same Origin Policy.


text:
Q: Simplifying Water Areas in QGIS for Artwork I am using QGIS to create geographic artwork with topo and water features.
I have downloaded the NHDWaterbody dataset from the USGS. Some of the wetlands are causing me real issues. For example, here there are tens or maybe hundreds of tiny little areas that are essentially adjacent.

I am trying to make artwork where this shape is cut out of material and the machine can't capture nearly this much detail. I am looking for a method where I can, as much as possible, combine all these very close shapes into a single large shape. Some loss of detail and precision is perfectly acceptable.
As is, it will try to trace out these hundreds of basically overlapping lines which will cause significant issues.

A: You can use the "Dissolve" tool in Vector > Geoprocessing Tools > Dissolve to merge all of the features into one.
You could also use the "Select by expression" attribute table tool to select and then remove all the adjacent wetland areas. You would need to find a unique identifier in the attribute table for the classes you do and don't want. For example, given you have a column in the attribute table called 'class' and it is filled with 1s (water) and 0s (wetland), you could do:
'class' = 2

to select all wetland attributes and then use the delete attributes icon to remove them.


text:
Q: Angle of deflection in gravitational lensing We are currently studying general relativity in school and also had a brief look at gravitational lensing.
My teacher gave us the angle of deflection between the apparent location of a star and its actual location (as seen on picture) to be
theta = 1.75" R/d where R is the radius of the object and d is the distance at which the light beam passes the massive object.

Our teacher was not very clear on where this is applicable and showed no derivation.
The equation does not contain mass or density as a variable which irritates me. Does this mean that the formula only works for a specific stellar object (e.g. Is it tailored to the sun's lensing or does it work for a different object as well?)
Could it also be that R and d are different variables than what I have mentioned?

A: The derivation of the gravitational lensing equation requires more maths than you'll learn at school, and indeed more than you'll learn in your first year or two as an undergraduate. General relativity isn't taught in any detail until your postgraduate studies, or possibly in the final year of your degree.
The full equation is:
$$ \theta = \frac{4GM}{c^2b} $$
where $G$ is Newton's constant, $M$ is the mass of the object, $b$ is the distance of closest approach and $c$ is the speed of light. Strictly speaking $b$ is a quantity called the impact parameter, but it's approximately the distance of closest approach.
The radius of the object doesn't appear in the equation because the spacetime geometry outside a spherically symmetric object depends only on the object mass and not on its radius.
This equation is derived in an approximation called the weak field limit, which basically means the spacetime curvature is small. It works as long as $\theta$ is small but would fail very close to a black hole where the bending of the light becomes large. In practice the gravitational lensing we've observed is all in the weak field limit so the equation works fine.


text:
Q: How to tell the maximum data alignment requirement in C++ Referencing this question and answer Memory alignment : how to use alignof / alignas? "Alignment is a restriction on which memory positions a value's first byte can be stored." Is there a portable way in C++ to find out the highest granularity of alignment that is required for instructions not to fault (for example in ARM)?  Is alignof(intmax_t) sufficient since its the largest integer primitive type?
Further, how does something in malloc align data to a struct's boundaries?  For example if I have a struct like so
alignas(16) struct SomethingElse { ... };

the SomethingElse struct is required to be aligned to a boundary that is a multiple of 16 bytes. Now if I request memory for a struct from malloc like so
SomethingElse* ptr = malloc(sizeof(SomethingElse));

Then what happens when malloc returns a pointer that points to an address like 40?  Is that invalid since the pointer to SomethingElse objects must be a multiple of 16?

A:
How to tell the maximum data alignment requirement in C++

There is std::max_align_t which

is a POD type whose alignment requirement is at least as strict (as large) as that of every scalar type.

Vector instructions may use array operands that require a higher alignment than any scalar. I don't know if there is a portable way to find out the the upper bound for that.
To find the alignment requirement for a particular type, you can use alignof.

Further, how does something in malloc align data to a struct's boundaries?

malloc aligns to some boundary that is enough for any scalar. In practice exactly the same as std::max_align_t.
It won't align correctly for "overaligned" types. By overaligned, I mean a type that has higher alignment requirement than std::max_align_t.

Then what happens when malloc returns a pointer that points to an address like 40?

Dereferencing such SomethingElse* would be have undefined behaviour.

Is that invalid since the pointer to SomethingElse objects must be a multiple of 16?

Yes.

how even would one go about fixing that? There is no way to tell malloc the alignment that you want right?

To allocate memory for overaligned types, you need std::aligned_alloc which is to be introduced in C++17.
Until then, you can use platform specific functions like posix_memalign or you can over allocate with std::malloc (allocate the alignment - 1 worth of extra bytes), then use std::align to find the correct boundary. But then you must keep track of both the start of the buffer, and the start of the memory block separately.

A: You might be looking for std::max_align_t


text:
Q: Script not displaying output I'm trying to write a simple script. I want to ask for inputs and then calculate a power.t.test.
numberoftests <- as.numeric(readline(prompt="Number of samples? "))
rangedata <- as.numeric(readline(prompt="Range? "))
Sdev <- as.numeric(readline(prompt="Standard deviation? "))
P<- power.t.test(n=numberoftests,delta=rangedata,sd= Sdev,power=NULL)

And then this is the output I get
> source('~/R/power.R')
Number of samples? 2
Range? 0.10
Standard deviation? 0.07
>
>
>

If I set the formula as a variable I can see it in the environment window, so I know it's calculating.
How do I get the results to display?


text:
Q: Code to account for all checkboxes in a userform? I have code on a userform that contains several checkboxes and several DTPickers.
The code looks like so:
Private Sub CheckBox11_Click()
If CheckBox11.Value = True Then
    DTPicker22.Enabled = True
Else
    DTPicker22.Enabled = False
End If
End Sub

Private Sub CheckBox12_Click()
If CheckBox12.Value = True Then
    DTPicker24.Enabled = True
Else
    DTPicker24.Enabled = False
End If
End Sub

The Userform contains a lot of checkboxes that have clauses next to them. Upon their completion the DTPicker will enable entering the date of completion.
Whilst this does what I want, it only enables one DTPicker when the checkbox is ticked per private sub. There has to be some way to make this so I wouldn't need to create different private subs for every checkbox click event.
Could you also tell me where to put it, as in, what event?

A: The first thing I'd recommend is following a proper naming convention. "CheckBox11" and "DTPciker1" are really vague and once you get further into your code, you'll forget which control is which. I would recommend naming them something that relates the two control together, like "firstDate" and "firstDateDTP". My alternate answer below uses this approach.
You could make a public function that enables the DTPicker based upon the checkbox's value.
Public Function EnableDTPicker(myPicker as String, enableBool as Boolean)

    UserFormName.Controls(myPicker).Enabled = enableBool

End Function

Then, you can call the function in your CheckBox123_Click() subs like this:
Private Sub CheckBox123_Click()
    EnableDTPicker("thePickerName", CheckBox123.Value)
End Sub

Alternatively, you could make a timer event that runs x number of seconds that just loops through the controls and performs the checks as needed. See this page on how to set up the timer. Using the code in the link shown, You could do something along the lines of:
'Put this in Workbook events
Private Sub Workbook_Open()
    alertTime = Now + TimeValue("00:00:01")
    Application.OnTime alertTime, "EventMacro"
    UserForm1.Show
End Sub

'Put this in a Module
Public Sub EventMacro()
    With UserForm1
        For each ctrl in .Controls
            If TypeName(ctrl) = "CheckBox" Then
                'The code below assumes the naming convention outlined above is followed
                .Controls(ctrl.Name & "DTP").Enabled = ctrl.Value
            End If
        Next ctrl
    End With

    alertTime = Now + TimeValue("00:00:01")
    Application.OnTime alertTime, "EventMacro"
End Sub

A: A "control array" is the typical approach for something like this.
See:
http://www.siddharthrout.com/index.php/2018/01/15/vba-control-arrays/
eg:
Class module clsEvents
Option Explicit

'Handle events for a checkbox and a date control, associated with a worksheet cell
Private WithEvents m_CB As MSForms.CheckBox
Private WithEvents m_DP As DTPicker
Private m_dateCell As Range

'set up the controls and the cell
Public Sub Init(cb As MSForms.CheckBox, dp As DTPicker, rng As Range)

    Set m_CB = cb
    Set m_DP = dp
    Set m_dateCell = rng

    If rng.Value > 0 Then
        cb.Value = True
        m_DP.Value = rng.Value
    Else
        cb.Value = False
    End If

    m_DP.CustomFormat = "dd/MM/yyyy"

End Sub

Private Sub m_CB_Change()
    m_DP.Enabled = (m_CB.Value = True)
End Sub

Private Sub m_DP_Change()
    m_dateCell.Value = m_DP.Value 'update the cell
End Sub

Userform:
Option Explicit

Dim colObj As Collection 'needs to be a Global to stay in scope

Private Sub UserForm_Activate()
    Dim obj As clsEvents, i As Long, ws As Worksheet

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    Set colObj = New Collection
    'loop over controls and create a class object for each set
    ' 3 pairs of controls on my test form...
    For i = 1 To 3
        Set obj = New clsEvents
        obj.Init Me.Controls("CheckBox" & i), _
                  Me.Controls("DTPicker" & i), _
                  ws.Cells(i, "B")
        colObj.Add obj
    Next i

End Sub


text:
Q: How to make fallback for Google Font? How to make fallback for Google Font? If Google Font not available, then load from local server url, all the same font.
It's not typical css font fallback, because need all the same font.
Maybe, already exist decision for Webpack?

A: Load local font using custom web-font API(@font-face) and also load google font.
p{font-family: google font , local web-font, system font;}

p{font-family: "Roboto","Times New Roman", serif;}

It will first try to load google web font. If not found it will go for local web font then if not found then it will fallback to system font.


text:
Q: VB.Net Finding class ID to click when it's buried in the DOM Example of the tree I'm dealing with
I am trying to click the 'followers' button on an IG account I run to see see the new users who have followed me automatically. (The example in the included picture is not my account for privacy reasons) I can find the class ID, but using something like
 Dim allelements As HtmlElementCollection = webBrowse.Document.All
    For Each webpageelement As HtmlElement In allelements
        If webpageelement.GetAttribute("class") = "g47sy " Then
            webpageelement.InvokeMember("click")
        End If
    Next

returns nothing for me... I know it's because this class is buried in JS and then further down the line. I can't for the life of me figure out how to check the elements of something buried so far in..
Any help would be super appreciated! Thank you!

A: Posted by Jimi in comments:
GetElementsByTagName() where the TAG name is SPAN, Then .GetAttribute("className"), not "class". Using LINQ, you can just add a .Where or FirstOrDefault clause to the collection returned by GetElementsByTagName() to single one out directly. – Jimi 12 hours ago


text:
Q: How can I send and receive text from two different applications using twilio? I need to be able to send and receive messages from two different applications. They both use webhooks; however I can't find a way that will work and sync text between the two.
Tried this, but didnt work.
enter image description here


text:
Q: Error CORS Api Node Localhost Mi proyecto se encuentra corriendo en un servidor propio de nuestra empresa, lo que hice fue exponer el puerto para poder acceder desde afuera, pero cuando intento hacer peticiones por ejemplo la de loguin me encuentro con el siguiente error

Access to XMLHttpRequest at
'http://192.168.100.11:3001/api/users/login' from origin
'http://nipponcarsrl.ddns.net:3000' has been blocked by CORS policy:
The request client is not a secure context and the resource is in
more-private address space private.

Codigo de mi APP
require('dotenv').config('.env'); // Variables de entorno
const cors = require('cors');
const express = require('express');
const dbConnect = require('./config/mongo'); // Archivo de configuracion de BD
const path = require('path');

const app = express(); // Inicio del servidor

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static('public'));
app.use(express.static(path.join(__dirname, '../front/build')));

// TODO: Main de rutas
const {
    damageDetailsRoutes,
    sectorDamageRoutes,
    severityCodeRoutes,
    damageCodeRoutes,
    damageTypeRoutes,
    damagesRoutes,
    usersRoutes,
    adminRoutes
} = require('./routes/Index');

app.use('/api/damage-details',damageDetailsRoutes);
app.use('/api/severity-code', severityCodeRoutes);
app.use('/api/sector-damage', sectorDamageRoutes);
app.use('/api/damage-code', damageCodeRoutes);
app.use('/api/damage-type', damageTypeRoutes);
app.use('/api/damages', damagesRoutes);
app.use('/api/users', usersRoutes);
app.use('/api/admin', adminRoutes);

app.listen(process.env.APP_PORT || 3000, () => {
    console.log('*** Server running ***');
    console.log(`http://localhost/${process.env.APP_PORT || 3000}`);
})
dbConnect();

Archivo Login
import { useForm } from "../../hooks/useForm";

import Swal from "sweetalert2";

import axios from "axios";
import { Global } from "../../helpers/Global";

export const Login = () => {
  const { form, changed } = useForm({});

  const login = async (e) => {
    e.preventDefault();

    const user = form;

    try {
      await axios.post(`${Global.url}users/login`, user).then((res) => {
        Swal.fire({
          position: "top-end",
          icon: res.data.status,
          title: res.data.msg,
          showConfirmButton: false,
          timer: 1300,
          toast: true,
        });

        const { tokenSession, user } = res.data;
        window.sessionStorage.setItem("token", tokenSession);
        window.sessionStorage.setItem("user", JSON.stringify(user));
        window.location.reload();
      });
    } catch (error) {
      console.log(error)
      document.getElementById("formLogin").reset();

      Swal.fire({
        position: "top-end",
        icon: "error",
        title: error.response.data.msg,
        showConfirmButton: false,
        timer: 1300,
        toast: true,
      });
    }
  };
  return (
    <>

INICIO DE SESION

        <form onSubmit={login} id="formLogin">

                Email
                <input
                  type="email"
                  className="form-control"
                  name="email"
                  aria-describedby="emailHelp"
                  onChange={changed}
                />

                Contraseña
                <input
                  type="password"
                  className="form-control"
                  name="password"
                  onChange={changed}
                />

            <button type="submit" className="btn btn-success">
              INGRESAR
            </button>

        </form>

    </>
  );
};

A: Has probado colocando el origin dentro de la configuración del cors
app.use(cors({origin: '*'}));

esto hará que este accesible desde cualquier origen.


text:
Q: Not able to find audio source element in amazon music web I have been using Amazon music for a while and I was just playing around in  "Chrome Developer tools".
As far as I know, audio/video tag is used for embedding multimedia content. So I was trying to find on audio tag but I can't locate one.
I am curious to know how Amazon streams music on the web.
Is it possible to stream audio without any audio/video tag on a webpage?


text:
Q: I need to run a TCL script in python, my TCL script also has a user-defined(internal) package I need to run a TCL script in python, my TCL script also has a user-defined(internal) package
I tried these scripts:
1.
import Tkinter
import socket

def TCLRun():
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect(('127.0.0.1', 5006))
 root = Tkinter.Tk()
## root.tk.eval('package require XXX')
 tcl_script ="""
package require XXX
set YYY [COMMAND FROM PACKAGE]
puts $YYY
} """
 # call the Tkinter tcl interpreter
 root.tk.call('eval', tcl_script)
 root.mainloop()

with this error:
import TCLCall
>>> TCLCall.TCLRun()

    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        TCLCall.TCLRun()
      File "C:\Users\XXX\Desktop\PKT\TCLCall.py", line 24, in TCLRun
        root.tk.call('eval', tcl_script)
    TclError: can not find channel named "stdout"

and,
2.
import Tkinter
root=Tkinter.Tk()
root.tk.eval('package require XXX')
root.tk.eval('set YYY COMMAND')

returns error about sdtout!
other one:
3.
 import subprocess
    p = subprocess.Popen(
        "tclsh tcltest.tcl",
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    print stdout
    print stderr

returns the following error:
can't find package __teapot__

    while executing

"package require __teapot__"

none of them working, please help me with this issue!
I can use some commands that operating something on our product with following code:
import socket
import time

def Sckt():
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect(('127.0.0.1', 5006))

 s.send('0 COMMAND \r\n')

that would give you some ideas!
thank,

A: With a custom package that is not part of your vendor's installation, you need to instruct Tcl where to search for it from. To do that, append the parent directory of the directory containing the package to Tcl's global auto_path variable. For example, if the XXX package is in the directory /home/amir/.tclpackages/XXX1.0 then you would have your script do this:
lappend auto_path /home/amir/.tclpackages

This can go anywhere in the Tcl script before the package require XXX. (Well, you could put it afterwards but then the package require would fail…)


text:
Q: sqlite.net table where condition on a child table I'm using Xamarin forms, SQLite.net and SQLitenet extensions and I'm unable to figure out why something that I would expect to be simple just doesn't work.
I have two classes
public class MeasurementInstanceModel
{
    public MeasurementInstanceModel ()
    {
    }

    [PrimaryKey]
    [AutoIncrement]
    public int Id {
        get;
        set;
    }

    [ForeignKey(typeof(MeasurementDefinitionModel))]
    public int MeasurementDefinitionId {
        get;
        set;
    }

    [ManyToOne(CascadeOperations = CascadeOperation.CascadeRead)]
    public MeasurementDefinitionModel Definition {
        get;
        set;
    }

    [ForeignKey(typeof(MeasurementSubjectModel))]
    public int MeasurementSubjectId {
        get;
        set;
    }

    [ManyToOne(CascadeOperations = CascadeOperation.CascadeRead)]
    public MeasurementSubjectModel Subject {
        get;
        set;
    }

    public DateTime DateRecorded {
        get;
        set;
    }

    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<MeasurementGroupInstanceModel> MeasurementGroups {
        get;
        set;
    }
}

and
public class MeasurementSubjectModel
{

    [PrimaryKey]
    [AutoIncrement]
    public int Id {
        get;
        set;
    }
    public string Name {
        get;
        set;
    }

    [OneToMany (CascadeOperations = CascadeOperation.All)]
    public List<MeasurementInstanceModel> MeasurementInstances {get;set;}
}

I'm simply trying to do the following query and it always fail.
db.Table<MeasurementInstanceModel>().Where(w => w.Subject.Name == avariable);

I get this exception

System.Diagnostics.Debugger.Mono_UnhandledException (ex={System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object
    at SQLite.Net.TableQuery1[MeasureONE.MeasurementInstanceModel].CompileExpr (System.Linq.Expressions.Expression expr, System.Collections.Generic.List1 queryArgs) [0x00000] in :0
    at SQLite.Net.TableQuery1[MeasureONE.MeasurementInstanceModel].CompileExpr (System.Linq.Expressions.Expression expr, System.Collections.Generic.List1 queryArgs) [0x00000] in :0
    at SQLite.Net.TableQuery1[MeasureONE.MeasurementInstanceModel].CompileExpr (System.Linq.Expressions.Expression expr, System.Collections.Generic.List1 queryArgs) [0x00000] in :0
    at SQLite.Net.TableQuery1[MeasureONE.MeasurementInstanceModel].GenerateCommand (System.String selectionList) [0x00000] in <filename unknown>:0
    at SQLite.Net.TableQuery1[MeasureONE.MeasurementInstanceModel].GetEnumerator () [0x00000] in :0
    at System.Collections.Generic.List1[MeasureONE.MeasurementInstanceModel].AddEnumerable (IEnumerable1 enumerable) [0x00000] in :0
    at System.Collections.Generic.List1[MeasureONE.MeasurementInstanceModel]..ctor (IEnumerable1 collection) [0x00000] in :0
    at System.Linq.Enumerable.ToList[MeasurementInstanceModel] (IEnumerable1 source) [0x00000] in <filename unknown>:0
    at MeasureONE.Repository1[MeasureONE.MeasurementInstanceModel].GetAll[DateTime] (System.Linq.Expressions.Expression1 predicate, System.Linq.Expressions.Expression1 orderBy, Nullable1 descending, Nullable1 skip, Nullable1 count) [0x00094] in /Users/jean-sebastiencote/MeasureONE/MeasureONE/Models/Repository/Repository.cs:48
    at MeasureONE.Repository1[MeasureONE.MeasurementInstanceModel].GetAllWithChildren[DateTime] (System.Linq.Expressions.Expression1 predicate, System.Linq.Expressions.Expression1 orderBy, Nullable1 descending, Nullable1 skip, Nullable1 count) [0x00009] in /Users/jean-sebastiencote/MeasureONE/MeasureONE/Models/Repository/Repository.cs:54
    at MeasureONE.MeasurementListViewModel.Load (System.Linq.Expressions.Expression1 pred, Nullable1 skip, Nullable1 count) [0x00049] in /Users/jean-sebastiencote/MeasureONE/MeasureONE/ViewModels/MeasurementListViewModel.cs:42
    at MeasureONE.MeasurementListViewModel.Load (MeasureONE.FilterViewModel filter) [0x000cf] in /Users/jean-sebastiencote/MeasureONE/MeasureONE/ViewModels/MeasurementListViewModel.cs:34
    at MeasureONE.MeasurementListViewModel.m__1 (GalaSoft.MvvmLight.Messaging.NotificationMessage`1 msg) [0x00007] in /Users/jean-sebastiencote/MeasureONE/MeasureONE/ViewModels/MeasurementListViewModel.cs:21
    at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
    at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0
    --- End of inner exception stack trace ---

As you can see from the stack trace, I have a few more things in the code, such as an order by. But this all work fine, as long as I don't have a condition on the child table.

A: SQLite-Net Extensions doesn't add any query functionality (at least by now). This means that you cannot access a relationship at query time, because that object requires a JOIN that it's not being performed. This is why you are obtaining a NullReferenceException.
You'll need to perform the JOIN manually. Replace this code:
db.Table<MeasurementInstanceModel>().Where(w => w.Subject.Name == avariable);

With this one:
var result = conn.Query<MeasurementInstanceModel>(
    "SELECT * " +
    "FROM MeasurementInstanceModel AS it " +
    "JOIN MeasurementSubjectModel AS sb " +
    "ON it.MeasurementSubjectId == sb.Id " +
    "WHERE sb.Name == ?", avariable);

Creating this kind of queries automatically is quite complex and it's not planned to be supported in a near future in SQLite-Net Extensions.
Another option using SQLite-Net Extension relationships is using GetAllWithChildren method to filter the desired subjects and then navigate through the relationships to obtain the instances:
var subjects = conn.GetAllWithChildren<MeasurementSubjectModel>(s => s.Name == avariable);
var result = subjects.Select(s => s.MeasurementInstances).Distinct().ToList();

This way you don't have to manually type the JOIN and the result is exactly the same, however this option suffers from the N+1 issue, so it may suffer some performance penalty.
Hope it helps.


text:
Q: Why does my Pandas DataFrame not display new order using `sort_values`? New to Pandas, so maybe I'm missing a big idea?
I have a Pandas DataFrame of register transactions with shape like (500,4):
Time              datetime64[ns]
Net Total                float64
Tax                      float64
Total Due                float64

I'm working through my code in a Python3 Jupyter notebook. I can't get past sorting any column. Working through the different code examples for sort, I'm not seeing the output reorder when I inspect the df. So, I've reduced the problem to trying to order just one column:
df.sort_values(by='Time')
# OR
df.sort_values(['Total Due'])
# OR
df.sort_values(['Time'], ascending=True)

No matter which column title, or which boolean argument I use, the displayed results never change order.
Thinking it could be a Jupyter thing, I've previewed the results using print(df), df.head(), and HTML(df.to_html()) (the last example is for Jupyter notebooks). I've also rerun the whole notebook from import CSV to this code. And, I'm also new to Python3 (from 2.7), so I get stuck with that sometimes, but I don't see how that's relevant in this case.
Another post has a similar problem, Python pandas dataframe sort_values does not work. In that instance, the ordering was on a column type string. But as you can see all of the columns here are unambiguously sortable.
Why does my Pandas DataFrame not display new order using sort_values?

A: df.sort_values(['Total Due']) returns a sorted DF, but it doesn't update DF in place.
So do it explicitly:
df = df.sort_values(['Total Due'])

or
df.sort_values(['Total Due'], inplace=True)

A: My problem, fyi, was that I wasn't returning the resulting dataframe, so PyCharm wasn't bothering to update said dataframe.  Naming the dataframe after the return keyword fixed the issue.
Edit:
I had return at the end of my method instead of
return df,
which the debugger must of noticed, because df wasn't being updated in spite of my explicit, in-place sort.


text:
Q: Curve Fitting in Python for extrapolation, Regression analysis This question is regarding curve fitting in python.
First, I would say that I do not know the curve fit function to insert into "curve_fit" function in the scipy library; therefore, I am trying to use a polyfit which is OK if I am interested in interpolation but my goal is to predict values at future points, in other words extrapolation.
I have attached a screenshot of a raw signal, smoothed and its polyfit result. It has the correct poly order but still fails at extrapolation. My conclusion is that poly fit is not the right approach here, but I can not estimate the curve function. What are you thoughts?
Please note that this is not a distribution since the y values may keep slowly decreasing infinitely, even below 0.
I'd say the function looks like an exponential Gaussian but again it's not a distribution so dont want to do that.
My last thought was to split the plot into two, the first model can certainly be modeled as a polynomial and the second as an exponential. (values are different than first png cuz it's of a different signal).

Then, maybe combine the two. What do you think about this?
Attached is a screenshot of this too.

A: Since many curves can fit the data and extrapolate differently, you need to choose the right basis functions to get the behaviour you want.
So far you have tried polynomials for instance, these however tend to +- infinite, which is perhaps not what you want.
I would try and use curve_fit on a sum of Hermite polynomials or Laguerre polynomials. For instance, for Laguerre polynomials, you could try
a + b*exp(-k x) + c*(1-x)*exp(-k x) + d*(x^2 - 4*x + 2)*exp(-k x) + ...

Python has a lot of convenience functions built in for this, see e.g. https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.polynomials.laguerre.html
Note however that you should also fit k to your data, which you could use curve_fit for.


text:
Q: Should I plug out my laptop after shutting it down? I have 5 Lenovo ideapad 330 laptops in my office and developers work with them. Laptops are plugged in all the time when they are working. My first question: Is it correct usage of laptops?
And the second question is: After they have done and I want to close the office, should I plug-out them or I can just leave them plugged in all the time?(24/7)

A: *

*No, generally not a good idea. Use on battery about half the time and on AC about half the time. Leaving the machine always plugged in can reduce overall battery life and also the ability to hold charge. Not always but it can happen.

*When the laptop is off, I always unplug them. This is an extension of point 1 above.


text:
Q: How to solve: Unable to locate publishable resources error (Laravel 8 Passport) In Laravel 8, I am trying to publish passport components using the following.
php artisan vendor:publish --tag=passport-components

It gives me this error.

Unable to locate publishable resources.


text:
Q: Microsoft Graph Change contentType of uploaded file and filter I have a VBA macro I'm using to interface with the graphAPI to upload a ton of files to SharePoint Online.
That's working fine.
The issue is changing the contentTypes after the fact.  I'm using the createUploadSession method of uploading the file, which treats the document library as a Drive. Evidently, document libraries are somewhat hybrid lists and OneDrive drives. The only way I've found to modify the contentType is to grab the library using the list API and changing the items that way.
However, I can't seem to search or filter the results in graph...based on anything. I've tried etag and createdDateTime, I only get "invalid filter clause" errors.
Is it possible to search or filter listitem results?
UPDATE:
I've found it's possible to do:
/items?$filter=fields/Created lt '{date}'

this isn't ideal. Can I filter by etag or a more identifying property?  The title isn't populated by uploading the list.

A: Got it!
you can do:
/items?$filter=startswith(fields/FileLeafRef, {fileName})

if you add the following header:
"Prefer": "HonorNonIndexedQueriesWarningMayFailRandomly"
Basically, this will work so long as the list isn't huge, my list happens to only have a few fields so it works perfectly.


text:
Q: Replicate Scipy's RegressionResults.predict functionality Here's my sample program:
import numpy as np
import pandas as pd
import statsmodels
from statsmodels.formula.api import ols
df = pd.DataFrame({"z": [1,1,1,2,2,2,3,3,3],
                   "x":[0,1,2,0,1,2,0,1,2],
                   "y":[0,2,4,3,5,7,7,9,11]
                   })
model = ols("y ~ x + z + I(z**2)", df).fit()
model.params

newdf = pd.DataFrame({"z": [4,4,4,5,5,5],
                   "x":[0,1,2,0,1,2]
                   })
model.predict(newdf)

You'll notice, if you run this, that model.params is a pandas Series with indices the same as the right-hand side of the formula, except with an additional entry: "Intercept"
>  Out[2]:
>     Intercept   -2.0
>     x            2.0
>     z            1.5
>     I(z ** 2)    0.5
>     dtype: float64

And, using some internal functionality I can't determine, the RegressionResults object's .predict() can recognize the column headers from newdf, match them up (including the patsy syntax "I(z**2)"), add the intercept, and return an answer Series. (this is the last line of my sample code)
This seems convenient! Better than writing out my formula again in python/numpy code whenever I want to evaluate slight variations on it. I feel like there should be some way for me to construct a similar pd.Series for formula coefficients, instead of having created it through a model and fit. Then I should be able to apply this to an appropriate dataframe as a way of evaluating functions.
My attempts to figure out how statsmodel is doing this haven't worked, I haven't found anything obvious in the related function doc pages, in patsy, nor can I seem to enter this section of the source code while debugging.
Anyone have any idea how to set this up?

A: I eventually pieced together one way of doing this.
def predict(coeffs,datadf:pd.DataFrame)->np.array:
    """Apply a series (or df) of coefficents indexed by model terms to new data

    :param coeffs: a series whose elements are coefficients and index are the formula terms
                or a df whose column names are formula terms, and each row is a set of coefficients
    :param datadf: the new data to predict on
    """
    desc = patsy.ModelDesc([],[patsy.Term([]) if column=="Intercept" else patsy.Term([patsy.EvalFactor(column)]) for column in coeffs.index] )

    dmat = patsy.dmatrix(desc,datadf)
    return np.dot(dmat, coeffs.T)

newdf["y"] = predict(model.params,newdf)

The reason this seemed so appealing to me, in case anyone is baffled, is that I was fitting data piecewise using df.groupby("column").apply(FitFunction). It seemed like having FitFunction() return the model.params series would be the cleanest approach within the pandas paradigm.


text:
Q: boost::signal and std::bind confusion, should I try something else? I'm trying to figure out a way that I can send messages to other objects in C++. For example when an object collides with another object, it will send out a message that there was a collision that occured. I'm trying to use boost:signal's, but they don't seem to be exactly what I want, unless I'm just using them in the wrong manner.
Here's the main reason:
I don't really understand is why this code still works even known that the object I allocated on the stack has been destroyed...
class SomeClass
{
public:

   void doSomething()
   {
      std::cout << "Testing\n";
   }
};

int main(int argc, char** argv)
{
     boost::signal<void ()> sig;

     {
           SomeClass obj;
           sig.connect(std::bind(&SomeClass::doSomething, &obj));
     }

     sig();
}

Okay so that code outputs:
Testing

Why does it still work? Shouldn't I get some sort of run-time error or it not call the method at all? I don't really want that to actually happen, I want the connection to be lost as soon as the object is destroyed.
I was thinking of sending messages another way, perhaps Objective-C style using their type of delegates, where you would inherit from a class to have a message sent to you. But then again, it seems to lead to me for some confusion, such as if I want multiple delegates I would have an array of delegate pointers, and if a delegate gets destroyed I would have to remove it from that array... Which could cause some confusion.
e.g.
class ColliderDelegate
{
public:

    virtual ~ColliderDelegate() {}

    virtual void onCollisionEnter(Collider* sender, Collider* withWho) = 0;
    virtual void onCollisionExit(Collider* sender, Collider* withWho) = 0;
    virtual void onCollisionStay(Collider* sender, Collider* withWho) = 0;

private:

    // I would have to have an array of Collider's that this object is connected to,
    // so it can detatch itself when it's destroyed...
 };

 class Collider
 {
 public:
    void add(ColliderDelegate* delegate);
    void remove(ColliderDelegate* delegate);

    void checkForCollisionWith(Collider*);

 private:

     // I would have to have an array of ColliderDelegate's that this object
     // needs to send information to.
 };

Can anyone suggest how I could implement what I want to do? I'm really confused on what I should do...

A: The signal slot in your example is a non-virtual member function, which doesn't access any object members. Non-virtual function address is resolved in compile-time, this pointer is not needed here -- so there's no reason for crash.
On the other hand, you could use singal "tracking" feature to disconnect the slot automatically. See the following: tracking in Boost.Signals; tracking in Boost.Signal2.

A:
Why does it still work?

It's actually Undefined Behavior because doSomething() is being called on a destructed object. (To see this, add a print statement to the destructor.) When you ran the program, "Testing" was printed to the screen, but the program could have crashed.
What you might consider is adding a connection member to SomeClass. This way, in the SomeClass destructor you could disconnect the signal–slot connection.

A: To answer at least some of your questions:

Why does it still work? Shouldn't I get some sort of run-time error or it not call the method at all?

I guess you are just lucky. You object gets destroyed nevertheless you can still call methods on it. It is undefined behaviour but in your case it does not crash.
You are not very specific on what problem you want to solve. So it is difficult to tell what is the best solution.
For your delegate approach take a look at std::shared_ptr and std::weak_ptr. You can hold arrays of std::weak_ptr and call your delegates through those.
Or maybe boost::signal is the right choice. Have a look at scoped connections.


text:
Q: How to call a Javascript method in iOS?

<link rel="stylesheet" type="text/css" href="style.css" />

1. What is the answer to this question?

<input type="radio" name="q1" value="a" id="q1a">Answer 1

<input type="radio" name="q1" value="b" id="q1b">Answer 2

<input type="radio" name="q1" value="c" id="q1c">Answer 3

<input type="radio" name="q1" value="d" id="q1d">Answer 4

2. What is the answer to this question?

<input type="radio" name="q2" value="a" id="q2a">Answer 1

<input type="radio" name="q2" value="b" id="q2b">Answer 2

<input type="radio" name="q2" value="c" id="q2c">Answer 3

<input type="radio" name="q2" value="d" id="q2d">Answer 4

3. What is the answer to this question?

<input type="radio" name="q3" value="a" id="q3a">Answer 1

<input type="radio" name="q3" value="b" id="q3b">Answer 2

<input type="radio" name="q3" value="c" id="q3c">Answer 3

<input type="radio" name="q3" value="d" id="q3d">Answer 4

4. What is the answer to this question?

<input type="radio" name="q4" value="a" id="q4a">Answer 1

<input type="radio" name="q4" value="b" id="q4b">Answer 2

<input type="radio" name="q4" value="c" id="q4c">Answer 3

<input type="radio" name="q4" value="d" id="q4d">Answer 4

5. What is the answer to this question?

<input type="radio" name="q5" value="a" id="q5a">Answer 1

<input type="radio" name="q5" value="b" id="q5b">Answer 2

<input type="radio" name="q5" value="c" id="q5c">Answer 3

<input type="radio" name="q5" value="d" id="q5d">Answer 4

6. What is the answer to this question?

<input type="radio" name="q6" value="a" id="q6a">Answer 1

<input type="radio" name="q6" value="b" id="q6b">Answer 2

<input type="radio" name="q6" value="c" id="q6c">Answer 3

<input type="radio" name="q6" value="d" id="q6d">Answer 4

7. What is the answer to this question?

<input type="radio" name="q7" value="a" id="q7a">Answer 1

<input type="radio" name="q7" value="b" id="q7b">Answer 2

<input type="radio" name="q7" value="c" id="q7c">Answer 3

<input type="radio" name="q7" value="d" id="q7d">Answer 4

8. What is the answer to this question?

<input type="radio" name="q8" value="a" id="q8a">Answer 1

<input type="radio" name="q8" value="b" id="q8b">Answer 2

<input type="radio" name="q8" value="c" id="q8c">Answer 3

<input type="radio" name="q8" value="d" id="q8d">Answer 4

9. What is the answer to this question?

<input type="radio" name="q9" value="a" id="q9a">Answer 1

<input type="radio" name="q9" value="b" id="q9b">Answer 2

<input type="radio" name="q9" value="c" id="q9c">Answer 3

<input type="radio" name="q9" value="d" id="q9d">Answer 4

10. What is the answer to this question?

<input type="radio" name="q10" value="a" id="q10a">Answer 1

<input type="radio" name="q10" value="b" id="q10b">Answer 2

<input type="radio" name="q10" value="c" id="q10c">Answer 3

<input type="radio" name="q10" value="d" id="q10d">Answer 4

Show me the answers!

Question 1: The correct answer is the Answer 1.

Question 2: The correct answer is Answer 2.

Question 3: The correct answer is Answer 3.

Question 4: The correct answer is Answer 4.

Question 5: The correct answer is Answer 1.

Question 6: The correct answer is Answer 2.

Question 7: The correct answer is Answer 3.

Question 8: The correct answer is Answer 4.

Question 9: The correct answer is Answer 1.

Question 10: The correct answer is Answer 2.

You answered them all right!

I faced a big problem on my iOS Coding. My requirement is I have a HTML file. That file contain some multiple choice Q&A. I Load that html file in a UIWebView. And when I click that answer button I have to retrieve which button is clicked on webView.
I have to retrieve that method from html file.
How is it possible?
Its not a duplicate Q, I already googled on this and whatever i got, its not satisfying my requirement.
My code is like below :
- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"Untitled" ofType:@"html"];
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];
   [_webview loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
  }
  - (void)webViewDidFinishLoad:(UIWebView*)theWebView
  {
    NSString* returnValue =[theWebView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
    NSLog(@"returnValue = %@ ",returnValue);
  }
  - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
  {
     NSLog(@" didFailLoadWithError");
  }

But my output is : Sample_JS[2218:44719] returnValue =
Please help me out ....

A: In your code,this is the order that things happen:

*

*You load the request in viewDidload

*Your webview finished load.So you get the value selected.But at this time.You have not select anything.

*When you select a item, you did not do anything to tell iOS that you select one

So,what I suggest is using WKWebview,it is good to work withs JS Code.

*

*In your js code,add a button to submit.
Then in the button action function
function submit () {
    var message = //here get all your selected items
    window.webkit.messageHandlers.observe.postMessage(message);
 }

*In ViewController,create WKUserContentController to handle notification
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
WKUserContentController *controller = [[WKUserContentController alloc]
                                   init];
[controller addScriptMessageHandler:self name:@"observe"];
 configuration.userContentController = controller;
_webView = [[WKWebView alloc] initWithFrame:self.view.frame
                          configuration:configuration];

*In delegate method,handle js event
-(void)userContentController:(WKUserContentController *)userContentController
  didReceiveScriptMessage:(WKScriptMessage *)message {
//message.body
}

Update whole project
#import <WebKit/WebKit.h>
@interface ViewController ()<WKScriptMessageHandler>

@property (strong, nonatomic) WKWebView  * webview;

@end

@implementation ViewController

- (void)viewDidLoad {
    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"Untitled" ofType:@"html"];
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
    WKUserContentController *controller = [[WKUserContentController alloc]
                                       init];
    [controller addScriptMessageHandler:self name:@"observe"];
    configuration.userContentController = controller;
    _webview = [[WKWebView alloc] initWithFrame:self.view.frame
                              configuration:configuration];
    [_webview loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
    [self.view addSubview:self.webview];
}

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"%@",message.body);
}

And htmlfile

<link rel="stylesheet" type="text/css" href="style.css" />

1. What is the answer to this question?

<input type="radio" name="q1" value="a" id="q1a">Answer 1

<input type="radio" name="q1" value="b" id="q1b">Answer 2

<input type="radio" name="q1" value="c" id="q1c">Answer 3

<input type="radio" name="q1" value="d" id="q1d">Answer 4

     <button onclick="getFirstSelect()">Submit</button>

When click submit

This is test project,I believe you can figure out rest by yourself

A: Finally I am able to solve this Big Issue..
First Set the delegate method for your WebView.
 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
 if ([[[request URL] absoluteString] hasPrefix:@"ios:"])
 {
    // Call the given selector
    [self performSelector:@selector(webToNativeCall)];
    return NO;
 }
 return YES;
}

- (void)webToNativeCall
{
 NSString *returnvalue =  [self.webview stringByEvaluatingJavaScriptFromString:@"returnVal()"];
 NSLog(@"returnvalue == %@",returnvalue);
}

In javascript file :
function getData ()
{
   window.location  = 'ios:webToNativeCall';
}
function returnVal(){
  return values;
}

A: Please check below code , I have tested in my system .
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"html"];
    NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:htmlString baseURL:nil];

}

Button action method to check html results after click on radio button -
- (IBAction)action:(id)sender {

    NSString* javaScriptString = @"document.querySelector('input[name=\"sex\"]:checked').value;";
    NSLog(@"%@",  [self.webView stringByEvaluatingJavaScriptFromString: javaScriptString]);
}

Html Files -
<!DOCTYPE html>

        <form action="">
            <input type="radio" name="sex" value="male">Male

            <input type="radio" name="sex" value="female">Female
        </form>

A: You have to make a global variable in JavaScript which store the value of answer.
your function myFunction() was called after the webview load and when user was selected at that time there are no function called. so you have to call the function rapidly in some time and check it what is the value


text:
Q: Responsive drop down menu not rendering I'm trying to create a responsive drop down navigation menu for my webpage. I already have a working drop down menu, but I want to make it so that when the screen reaches a certain size, I get a ☰ icon with my menu items. However, when I test this (by re-sizing my browser), I only see my drop down menu displayed as a block element, and the ☰ icon doesn't show. Here is a fiddle with my code:
http://jsfiddle.net/Lwdc4/
My JavaScript code is in an external file. This is what the file looks like:
$("#nav").addClass("js").before('<div id="menu">☰ </div>');
$("#menu").click(function(){
    $("#nav").toggle();

});

$(window).resize(function(){
    if(window.innerWidth > 768){
        $("#nav").removeAttr("style");

    }
});

And my import to HTML:
<head>
 <title>Title</title>

    <link rel="stylesheet" type="text/css" href="nav-menu.css"
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="nav-menu.js"></script>
  </head>

What is wrong with my code? Any help is appreciated. Thanks in advance.

A: You need to add the jquery library to use the $ object
Add this line in your HTML to use it
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

Or choose your version directly on the jQuery website http://jquery.com/download/
Updated fiddle :
http://jsfiddle.net/Lwdc4/1/


text:
Q: Android fail to load google map in fragment I'm trying to use google map in fragment, but I meet a problem I don't understand.
I don't arrive to load the map in this line :
gMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

This line seems to return always null...
I tried to use MapFragment inseatd of SupportMapFragment, but it's not possible.
How to resolve it ?
To explain why i want to show it in a fragment, it's because i'm using a navigationdrawer, and one of my item needs to show the map.
thx,
EDIT : My xml :
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:name="com.google.android.gms.maps.MapFragment"/>

A: I think you should call with getsupportFragmentManager not with getFragmentManager otherwise it will return null always

A: If you are using SupportMapFragment, you need to change your layout!
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:name="com.google.android.gms.maps.SupportMapFragment"/>

This is a basic example using SupportMapFragment:
public class MainActivity extends ActionBarActivity implements OnMapReadyCallback{

    private SupportMapFragment map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        map.getMapAsync(this);//remember getMap() is deprecated!
    }

    @Override
    public void onMapReady(GoogleMap map) {
           map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(47.17, 27.5699), 16));
            map.addMarker(new MarkerOptions()               .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                    .position(new LatLng(47.17, 27.5699))); //Iasi, Romania
            map.setMyLocationEnabled(true);
    }
}

and change the reference in your layout:
<fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

A: I dont think it is possible as google map contains a < fragment> tag. See here why:

Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.

Some people in SO however managed to show map in a fragment, but the solution was hacky.


text:
Q: MongoDB - Mongoose - Can only call the controllers save method once. Then it never saves again SEE EDIT DOWN BELOW PLEASE
What I am doing is calling the controllers save function via a post request. When I run the method for the first time is seems to save the 2 objects I made. And then it redirects me to the good route. But when I go back post the same POST request. It gives me the console.log's but never actually saves them.
The router:
app.post('/new', function(req, res, next){
  poll.newPoll(req, res, next);
  next();
}, function(req, res){
  res.redirect('/ok');
})

Schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//Schema for the polls
var pollSchema = new Schema({
  title: String,
  hash: String
});

var Poll = mongoose.model('Poll', pollSchema);

module.exports = Poll;

And controller:
var Poll = require('../modules/poll.js');
var hash = require('randomstring');

var randomHash = hash.generate({
  length: 5
});

//Function for creating new polls
module.exports.newPoll = function(req, res, next){
    var createdPoll = new Poll({title: "Wazap", hash: randomHash});
    var secondPoll = new Poll({title: "Ok", hash: randomHash});
    createdPoll.save(function (err, createdPoll) {
      if (err) {
        console.log(err);
        return handleError(err);
      }
      console.log("New Poll saved");
    });

    secondPoll.save(function (err, secondPoll) {
      if (err) {
        console.log(err);
        return handleError(err);
      }
      console.log("New Poll saved");
    });
}

Mongoose initialization:
var mongoose = require('mongoose');

//controllers
var poll = require('./controllers/poll.js');

//Mongostuff
mongoose.Promise = global.Promise;
mongoose.connect('localhost:27017/pollr');

mongod log:
2016-08-11T14:51:38.142+0200 I COMMAND  [conn3] command pollr.polls command: insert { insert: "polls", documents: [ { title: "Wazap", hash: "pxeZP", _id: ObjectId('57ac74d997df31a423f20049'), __v: 0 } ], ordered: false, writeConcern: { w: 1 } } ninserted:1 keyUpdates:0 writeConflicts:0 numYields:0 reslen:40 locks:{ Global: { acquireCount: { r: 2, w: 2 } }, Database: { acquireCount: { w: 1, W: 1 } }, Collection: { acquireCount: { W: 1 } } } protocol:op_query 197ms
2016-08-11T14:51:38.143+0200 I COMMAND  [conn4] command pollr.polls command: insert { insert: "polls", documents: [ { title: "Ok", hash: "pxeZP", _id: ObjectId('57ac74d997df31a423f2004a'), __v: 0 } ], ordered: false, writeConcern: { w: 1 } } ninserted:1 keyUpdates:0 writeConflicts:0 numYields:0 reslen:40 locks:{ Global: { acquireCount: { r: 1, w: 1 } }, Database: { acquireCount: { w: 1 }, acquireWaitCount: { w: 1 }, timeAcquiringMicros: { w: 143945 } }, Collection: { acquireCount: { w: 1 } } } p

Only when i delete all my data in the database it can save again. I hope this is enough info to give. I have searched on google for more than 2 hours to search for a solution but it did not give me one. It is probably something stupid I did or I overlooked something.
Thanks!

EDIT:
Apparantly it is saving, but not documenting it in the logs. If I only knew haha. Is there something I could do about this?

A: Try using the following method for creating multiple documents at the same time. It uses an array to hold the documents and then passes that array to the create method which has a callback that can be used to call an error or do something with the resulting saved documents.
//Function for creating new polls

module.exports.newPoll = function(req, res, next){
    var docs = [{title: "Wazap", hash: randomHash}, {title: "Ok", hash: randomHash}];
    Poll.create(docs, function (err, wazap, ok) {
        if (err) {
            console.log(err);
            return handleError(err);
        }
        console.log("Saved Wazap :" + wazap + " Saved Ok: " + ok)
    });
}

I have added the saved documents to the console.log so you can check their _id as well to ensure they are unique.


text:
Q: ModuleNotFoundError: No module named 'facenet_pytorch' but it seems indeed installed I'm in this python3 virtualenv:
(base) marco@pc01:~/PyTorchMatters/facenet_pytorch/examples$ pyenv virtualenvs
  3.7.3/envs/facenet_pytorch (created from /home/marco/.pyenv/versions/venv373)
  3.7.3/envs/venv373 (created from /home/marco/.pyenv/versions/3.7.3)
* facenet_pytorch (created from /home/marco/.pyenv/versions/venv373)
  venv373 (created from /home/marco/.pyenv/versions/3.7.3)

As far as I understand, the required module is already installed:
(base) marco@pc01:~/PyTorchMatters/facenet_pytorch/examples$ pip3 install facenet_pytorch
Requirement already satisfied: facenet_pytorch in /home/marco/.pyenv/versions/3.7.3
/envs/facenet_pytorch/lib/python3.7/site-packages (2.2.8)
Requirement already satisfied: requests in /home/marco/.pyenv/versions/3.7.3
/envs/facenet_pytorch/lib/python3.7/site-packages (from facenet_pytorch) (2.23.0)
Requirement already satisfied: numpy in /home/marco/.pyenv/versions/3.7.3
/envs/facenet_pytorch/lib/python3.7/site-packages (from facenet_pytorch) (1.18.1)
Requirement already satisfied: chardet<4,>=3.0.2 in /home/marco/.pyenv/versions/3.7.3
/envs/facenet_pytorch/lib/python3.7/site-packages (from requests->facenet_pytorch) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /home/marco/.pyenv/versions/3.7.3
/envs/facenet_pytorch/lib/python3.7/site-packages (from requests->facenet_pytorch) (2.9)
Requirement already satisfied: certifi>=2017.4.17 in /home/marco/.pyenv/versions/3.7.3
/envs/facenet_pytorch/lib/python3.7/site-packages (from requests->facenet_pytorch)
(2019.11.28)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /home/marco/.pyenv
/versions/3.7.3/envs/facenet_pytorch/lib/python3.7/site-packages (from
requests->facenet_pytorch) (1.25.8)

And with pip freeze it seems indeed installed in its virtualenv:
(base) marco@pc01:~/PyTorchMatters/facenet_pytorch/examples$ pip3 freeze --local
certifi==2019.11.28
chardet==3.0.4
facenet-pytorch==2.2.8
idna==2.9
numpy==1.18.1
requests==2.23.0
urllib3==1.25.8

But when I try to execute this one-line-code:
prova.py :
from facenet_pytorch import MTCNN

I get ModuleNotFoundError: No module named 'facenet_pytorch'
(base) marco@pc01:~/PyTorchMatters/facenet_pytorch/examples$ python3 prova.py
Traceback (most recent call last):
  File "prova.py", line 1, in <module>
    from facenet_pytorch import MTCNN
ModuleNotFoundError: No module named 'facenet_pytorch'

*

*pip3 version: pip-20.0.2

*OS: Ubuntu 18.04.4 Desktop

*python version: Python 3.7.4

Update)  SOLVED:
Just installing it with pip install (not pip3) solved the problem
Marco

A: pip install facenet-pytorch

This solved the issue for me


text:
Q: Is there a way to use DPI in css media queries instead of px Number of pixels width and height does not always tell the whole story. That works great for adding or removing items from the screen, but isn't quite right for setting the right image. With the retina display on the MBP, a browser window set to half of the screen would have the same number of pixels in width as most machines today. Yet, images displayed would likely be too small given the higher DPI.
Is there a way to change out images based on DPI rather than the number of pixels width and height?

A: In 2021 you can use a media query for resolution, min-resolution, max-resolution in all modern browsers except safari.
header {
  background-image: url(low-res-background.jpg);
}
@media (resolution >= 2dppx) {
  header {
    background-image: url(hi-res-background.jpg);
  }
}

But CSS is not the only anwer. You can also just use HTML. Have a look at Resposive Images withe .
p.s.
You could also use dpi to specify resolution, but this only makes sense for print:
@media print and (min-resolution: 72dpi) {
  p {
    text-decoration: underline;
  }
}

See https://developer.mozilla.org/en-US/docs/Web/CSS/@media/resolution

A: You can do either:
<link
    rel="stylesheet"
    type="text/css"
    href="/css/retina.css"
    media="only screen and (-moz-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2)"
/>

or
@media only screen and (-moz-min-device-pixel-ratio: 2),
       only screen and (-o-min-device-pixel-ratio: 2/1),
       only screen and (-webkit-min-device-pixel-ratio: 2),
       only screen and (min-device-pixel-ratio: 2) {
 /*use CSS to swap out your low res images with high res ones here*/
}

A: What you are looking for is the Device Pixel ratio. Because things like the iPhone display like a 320px screen but with a 640px layout (Pixel ratio of 2). In media queries, use "device-pixel-ratio". Though I would make sure to still use the vendor prefixes.
A good post on it: http://menacingcloud.com/?c=highPixelDensityDisplays

A: There are also  and -webkit-image-set css function, but they seem to be supported only by Safari/Chrome/Opera. Example:

background-image:  -webkit-image-set(
     url(icon1x.jpg) 1x,
     url(icon2x.jpg) 2x
);

I'm not sure if the examples in the accepted answer by Moin Zaman work on IE/Firefox. Probably "min-resolution" needs to be used:
@media only screen and (min-resolution: 192dpi),
       only screen and (min-resolution: 2dppx)


text:
Q: Javascript Image Preview for page with lots of forms I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.
The forms are of the form below:
<form class="myForm" ...>

    <input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>

And I have javascript to handle the image preview as follows:
function handleFiles(files) {
    $(".obj").remove();
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var imageType = /image.*/;

        if (!file.type.match(imageType)) {
            continue;
        }

        var pic_div = document.getElementById("imagePreview");
        var img = document.createElement("img");
        img.classList.add("obj");
        img.file = file;
        pic_div.appendChild(img);

        var reader = new FileReader();
        reader.onload = (
            function(aImg) {
                return function(e) {
                    aImg.src = e.target.result;
                };
            }
        )(img);
        reader.readAsDataURL(file);
    }
}

I want to replace the line:
var pic_div = document.getElementById("imagePreview");

with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.
Any help is much appreciated.

A: The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:

Or, if you will have multiple divs with the same class get them using jQuery like this:
$(".imagePreview").each(function(index){
    //Do Something
});

Or:
var pic_div = $(".imagePreview")[0]


text:
Q: Why are terminal commands 'git add .', git commit...' and 'git push...' listed as optional when deploying React project? Apologies, I am still a bit confused by git, although I am trying to teach myself more and improve.
I recently successfully deployed a React website to GitHub pages, following the often recommended steps of installing gh-pages to the project, adding a homepage property to the package.json file, adding scripts to the scripts properties on the package.json file, running 'npm run deploy' and so on. It worked fine, and now a build of the project has been added to my repository (here), and I can view the actual project online (here).
However, the issue I have is this: most guides on deploying a react app also mention the following steps:
in the terminal type:
git add .
git commit -m "commit"
git push origin master
These final steps are often listed as optional. Everything worked fine without me doing these steps: my code was added to the repository, and my website is deployed online, so what do these steps do exactly? Why are they considered optional? What is best practice?

A: These commands are not optional to me - when using only the command-line Git client, these commands accomplish the interaction of pushing the code (that, after you edit it, only exists locally on your own PC) to the Git repository server.

Everything worked fine without me doing these steps: my code was added to the repository, and my website is deployed online

I can see the following possibilities:

*

*You are using another Git client and the push was done there;

*You are using a Git tool (e.g. editing purely on the GitHub website), where the push happened without you being aware of it;

*You did the terminal commands, without being aware of them;

A common resource to learn more about Git would be the Git book on the official Git SCM website: https://git-scm.com/book/en/v2


text:
Q: Make children process wait until receiving parent's signal I want to create N children from a parent. I want all the children to start (a function - to measure time) at the same time. So I put the function in a signal handler and when the parent finish creating (fork) all children, it sends the signal (using kill(children_id)) to all children to let make start. The code is below but it doesn't work as expected. Specifically, it forked all children but does not execute function "measure_time" at all. This function does not thing but record execution time and print out.
Could someone let me know if I am doing something wrong?
    int n_task = 4;
    for (i = 0; i < n_task; i++){
            pid = fork();
            if (pid < 0){
                    printf("cannot fork!\n");
            } else
            if (pid == 0){ //child
                    printf("printed from child [%d]\n", getpid());
                    signal(SIGUSR1, measure_time); //measure_time is a function
                    exit(0);
            } else {
                    pid_array[i] = pid;
            }
    }

    //This code is executed from parent only
    for (int i = 0; i < n_task; i++)
    {
            kill(pid_array[i], SIGUSR1);
    }

A: if (pid == 0){ //child
    printf("printed from child [%d]\n", getpid());
    signal(SIGUSR1, measure_time); //measure_time is a function
    exit(0);
}

The children get created, set up the handler, and immediately exit (i.e. die).  Make them sleep or block on something so there is actually time for the parent to deliver the signals.
Update
#define _POSIX_SOURCE

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

void measure_time(int sig)
{
    printf("child [%d] received signal %d\n", getpid(), sig);
}

int main(int argc, char *argv[])
{
    int n_task = 4;

    pid_t pid;
    pid_t pid_array[n_task];

    for (int i = 0; i < n_task; i++)
    {
        pid = fork();

        if (pid < 0)
        {
            perror("fork");
            exit(1);
        }

        if (pid == 0) //child
        {
            printf("printed from child [%d]\n", getpid());
            signal(SIGUSR1, measure_time); //measure_time is a function
            sleep(5);

            exit(0);
        }

        //parent
         pid_array[i] = pid;
    }

    //This code is executed from parent only
    sleep(1);

    for (int i = 0; i < n_task; i++)
        kill(pid_array[i], SIGUSR1);

    for (int i = 0; i < n_task; i++)
        wait(NULL);

    return (0);
}

All processes and threads are subject to whims of the OS scheduler.  In your initial code the children and the parent can potentially terminate before the sequence of events you hope to take place can ever occurs.  The children can die before the parent ever sends a signal; the parent can send its signals before the children ever set up their handler (and SIGUSR1 kill the process because that is its default in the absence of a handler).  There is so little code to execute all this takes place in milliseconds, less than the time than any of these processes gets scheduled to run (and thus setting up enough to fulfill your expections).  I have added some sleep to give it all some breathing room and a wait so the parent doesn't die.  This should allow you to see how it works.

A: if (pid == 0){ //child
    printf("printed from child [%d]\n", getpid());
    signal(SIGUSR1, measure_time); //measure_time is a function
    pause();
    exit(0);
}

I think problem is, child Processes are terminated immediately after they created. so
Use pause() function to wait for the signal to arrive.
And if some child Processes won't respond as expected try this also.
for (j = 0; j < n_task; j++)
    {
            kill(pid_array[j], SIGUSR1);
            sleep(1);
    }


text:
Q: Android - get Saved Bitmap from internal Storage and with ID How can I get a saved Bitmap from internal Storage with the Resource ID?
saveImageToInternalStorage(context, bitmap, "car" );
int drawable = getImageFromInternalStorage(context, "car"); // <- How to do this and put it in the Array imageIDs below?

final int[] imageIDs = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d,
                R.drawable.e, R.drawable.f , drawable };

A: How to display bitmap from internal storage? might help...u need to create file input/outputstream and specify path in order to get the bitmapimage...


text:
Q: How can I get the MKMarkerAnnotationView image? I have created a map image using the MKMapSnapshotter.  Unfortunately the snapshotter does not let you add annotations so I would like to add my annotation directly onto the view.
I know for a pin you can do the following get the UIImage of the pin:
let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = pinView.image

This works fine.  However I want the image of the marker.  I have tried the following but unfortunately nothing appears.
let markerView = MKMarkerAnnotationView(annotation: nil, reuseIdentifier: nil)
let markerImage = markerView.image

I have changed image to glyphImage and no difference.  Is there anyway to get the marker image?


text:
Q: What is the difference between "submit" and "deposit"? I am trying to find out the difference between "submit" and "deposit" these words are very confusing when you visit to a bank and somebody ask you "what is the purpose of you to come here and you replied that "I came here to submit a payment" or "I came here to deposit a payment" out of these two sentences which is correct and why?

A: I have never encountered the word submit used with "money"; it is sometimes used with "payment" - but that would mean paying for something, which is different from what you usually do in a bank.
COCA (the corpus of Contemporary American English) does not have a single instance of "submit money" (or of "submit the money" or "submit some money").


text:
Q: issue with user interface in windows form Hi i am currently doing this leave project and the user interface have problems when changing computer. I have added a code to change the DPI which was supposed to solve the problem based on the computer.The code that was used is:
namespace WindowsFormsApplication1
{
static class Program
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern bool SetProcessDPIAware();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        if (Environment.OSVersion.Version.Major >= 6)
            SetProcessDPIAware();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Login());
    }
}
}

This is the display for the computer with problem:

This is the display for the computer that does not have the problem:

Thanks in advance..!


text:
Q: VBA script for multiple pivot tables I replace source data ever week, and have many pivot tables attached to it. However, when I refresh the tables, they start to miss some data. So, I went ahead and recorded some "macros" to create and replace new pivot tables every time. The pasted areas will stay the same, and I gave them enough surrounding room to never overlap. Unfortunately, I get many errors and am not good with VBA at all. I only know it from forums etc.
The source data is on "CopyData"
The Country Pivot Tables should go on "Country"
So my questions are:
1. How can I create a VBA script that creates and replaces pivot tables and can be used many time after (So maybe start with deleting old pivots?)
2. How can I keep the pivot table's names general?  I won't know what the next pivot table will be called when it is run
Any help would be great!
Below is my code for one of the "macros" and it should create and replace two pivot tables.
   Sub Pivots_Country()
' Pivots_Country Macro
'
'
    Range("B215").Select
    ActiveWorkbook.Worksheets("Region").PivotTables("PivotTable10").PivotCache. _
        CreatePivotTable TableDestination:="Sheet1!R2C2", TableName:="PivotTable10" _
        , DefaultVersion:=xlPivotTableVersion14
    Sheets("Sheet1").Select
    Cells(2, 2).Select
    ActiveSheet.PivotTables("PivotTable11").AddDataField ActiveSheet.PivotTables( _
        "PivotTable11").PivotFields("storeId"), "Count of storeId", xlCount
    With ActiveSheet.PivotTables("PivotTable11").PivotFields("NewCountry")
        .Orientation = xlRowField
        .Position = 1
    End With
    Sheets("CopyData").Select
    Range("B10").Select
    ActiveWorkbook.Worksheets("Sheet1").PivotTables("PivotTable11").PivotCache. _
        CreatePivotTable TableDestination:="Sheet1!R4C6", TableName:="PivotTable12" _
        , DefaultVersion:=xlPivotTableVersion14
    Sheets("Sheet1").Select
    Cells(4, 6).Select
    With ActiveSheet.PivotTables("PivotTable12").PivotFields("plan")
        .Orientation = xlColumnField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable12").PivotFields("planCode")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable12").PivotFields("NewCountry")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable12").AddDataField ActiveSheet.PivotTables( _
        "PivotTable12").PivotFields("storeId"), "Count of storeId", xlCount
    ActiveWindow.SmallScroll Down:=-7
    Range("B2:C56").Select
    Selection.Copy
    Sheets("Country").Select
    Range("B4").Select
    ActiveSheet.Paste
    ActiveWindow.SmallScroll Down:=7
    ActiveWindow.SmallScroll ToRight:=-2
    ActiveWindow.SmallScroll Down:=-2
    ActiveWindow.SmallScroll ToRight:=-1
    ActiveWindow.SmallScroll Down:=-1
    ActiveWindow.SmallScroll ToRight:=-2
    ActiveWindow.SmallScroll Down:=-30
    Sheets("Sheet1").Select
    ExecuteExcel4Macro "(""PivotTable12"",""planCode"",3,FALSE,TRUE)"
    Range("F2:P52").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Country").Select
    ActiveWindow.SmallScroll ToRight:=3
    ActiveWindow.SmallScroll Down:=-1
    ActiveWindow.SmallScroll ToRight:=2
    Range("R3").Select
    ActiveSheet.Paste
    ActiveWindow.SmallScroll Down:=1
    Range("Q15").Select
    Sheets("Sheet1").Select
    Cells.Select
    Range("F2").Activate
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlUp
    Range("J11").Select
    Sheets("CopyData").Select
End Sub

A: You really don't need to recreate the pivot tables.  You need to find out why data is missing from the pivot tables after you refresh your data.  This shoudl be a LOT less work.
I suspect the pivot tables are getting data from a range and that when you refresh the data the new data has more rows than the old data, so the pivot tables miss the extra rows.
The best way around this to ensure that you pivot tables are based on a range that has enough rows for all the current and future data you put into the sheet.
Inspect the  pivot table.

*

*click on pivot table

*in ribbon>Pivot table tools>analyse>data>Change data source you can see what the range is (and change it)
Please let me know how you get on.
In the future you might consider using excel tables (also known as ListObjects)
For example

*

*select the range that has your data

*click the ribbon>Insert>Table button to convert the range to be an excel table.

*change your pivot tables to reference data in the tables

*Change how you refresh you data.
As you are new to excel, I wouldn't use Excel tables now, get it working first, and then convert it to use them.
I hope this helps.
Harvey


text:
Q: returning the content of cell X in a range I am looking for the content of a cell in a given row, knowing its position in the row. For example I am looking for the content of cell 4 in a row of 10 cells. then the content of cell 8 in the same range. Any idea?

A: Use INDEX to return a value from a range based purely on its position in the range. For example, for your purposes if the data is in the 10 cells between A13 and J13 this might look like:
=INDEX($A$13:$J$13,4)

The range can be a horizontal row or vertical column. Or indeed an area, where you would use x,y row and column to reference a cell.

A: Please try this:
=OFFSET(A1,,COLUMN(A1)*3)


text:
Q: Dagger 2 Not injecting into dependant module I checked all questions but did not find any clue. I stripped my problem to a simplest code:
Situation:
I want to have:
    CatComponent catComponent = DaggerCatComponent.builder()
        .kameModule(new KameModule(MainActivity.this))
        .build();
   catComponent.getCatAnalyzer().analyze();

I have created component:
@Component(modules = {KameModule.class, CatAnalyzerModule.class})
public interface CatComponent {

    CatAnalyzer getCatAnalyzer();
}

And modules:
@Module
public class KameModule {

    private Context context;

    public KameModule(Context context) {
        this.context = context;
    }

    @Provides
    KameCat provideKameCat() {
        return new KameCat(context );
    }
}

@Module(includes = KameModule.class)
public class CatAnalyzerModule {

    @Inject
    KameCat cat;

    @Provides
    CatAnalyzer provideCatAnalyzer() {
        return new CatAnalyzer(cat);
    }
}

And classes:
public class KameCat {

    Context context;

    public KameCat(Context context) {
        this.context = context;
    }

    public void doCatStuff() {
        Toast.makeText(context, "Poo and Meow", Toast.LENGTH_LONG).show();
    }
}

public class CatAnalyzer {

    @Inject
    KameCat cat;

    @Inject
    public CatAnalyzer(KameCat cat) {
        this.cat = cat;
    }

    void analyze() {
        cat.doCatStuff();
    }
}

When I retrieve my CatAnalyzer object from CatComponent it has cat field nulled.
I have no idea why Dagger won't inject it. Could you guide me somehow?

A: Proper code:
@Module(includes = KameModule.class)
public class CatAnalyzerModule {

    @Inject //remove this
    KameCat cat;// remove this

    @Provides
    // Add cat as a argument and let KameModule provide it..
    CatAnalyzer provideCatAnalyzer(KameCat cat) {
        return new CatAnalyzer(cat);
    }
}

Thanks to:
https://www.future-processing.pl/blog/dependency-injection-with-dagger-2/


text:
Q: Unity5.2.2+Parse1.6.2+iOS9, SignupAsync causes EXC_BAD_ACCESS on iPhone On this situation, simply "SignupAsync" causes EXC_BAD_ACCESS on real device only.
On UnityEditor, SignupAsync can be finished without error.
On any case, Users can be created on Parse Server.
How can I avoid this?

It seems "connection.data" has no "bytes" in this case.(Existing no "bytes" variable causes exc_bad_access i think.)

Is it Parse SDK bug? Or not?
I have scheduled a release of my newest game in this week, so this problem annoy me... I need anyone help.


text:
Q: Do you use a PHP IDE? I've programmed for six years, and in that time, I've never used a PHP IDE. I feel perfectly fine using Vim, the Linux shell, MySQL command line and Subversion command line for my web application development. When I'm asked to work on other people's projects, or open source projects, I can generally find my way around after a quick system architecture overview.
Recently, I was curious about PHP IDEs. I downloaded NetBeans, but I lost patience debugging installation problems.
It makes me wonder, will my productivity increase substantially with the use of a good PHP IDE?  What percentage of LAMP/PHP developers use a PHP IDE?

A: I always use an IDE now, if it supports refactoring.  I may use it in addition to, or alongside, Vim or Emacs, but refactoring is now an integral part of my development style and having automated refactoring tools is essential.
If you're only going to use the editor features of whatever IDE you choose, you probably won't benefit much.  The benefit is when:

*

*the IDE can do for us something that would take us much longer, OR

*the IDE provides information that we would otherwise need to work to find

A: I have used NetBeans in the past for PHP projects and liked it a lot. The fact I liked it is just my opinion, but I don't remember having any install issues. NetBeans synced up great with my teams SVN server and things worked smoothly.

A: I use Eclipse.  It's bloated, unwieldy, slow and quirky, but I find that it has some features that make me a better/faster developer.  The two main things I like about developing PHP with Eclipse are:

*

*Function documentation tooltips.  Given that PHP lacks a standard parameter order for a lot of things, this is especially useful with the str family of functions.  I don't have to remember whether a particular function order is ($haystack,$needle) or ($needle,$haystack), I can just type the name of the function and hover over it.

*"Jump into" functionality.  Highlight a function and hit 'F3', and it will take you to the class or file where that function is defined.  This is extremely helpful.

There's other features that are useful as well, although not as profound.  Things like autocomplete and PHPDoc comment templates (type /** and it creates a basic block comment pre-filled with your parameters) tend to be handy.
Due to deficiencies with Eclipse, I tend to develop with multiple tools.  For example, I find UltraEdit's "Find in multiple files" functionality to be excellent (as well as "edit in Column mode" for batch SQL edits), and I usually have it running alongside Eclipse.
I've tried NetBeans several times, but each time I've installed it in the past, the internal PHP function documentation has been broken, so hovering over any built-in PHP function results in an intellisense box saying "PHPDoc Not Found".  I found that extremely aggravating, and each time have gone back to Eclipse.  I like the looks of it, but I need that functionality (a vague reference to it on some forum has one of the developers saying that the build script is broken so it's not linking the docs properly, but they had yet to fix it as of my last attempt).

A: I use NetBeans too. So far the best from what I've tried. Zend Studio is terrible and Eclipse is beyond any criticism (you cannot just double click php file to open it in Eclipse, for starters). There are several more free and commercial IDEs but most of them for Windows only.
Edit: tools I use most often are: method suggestion, refactoring, "go to declaration/defintion", "find usage", debuging (obviously, since it underlines erroneous statements).

A: I use Eclipse with a PHP plugin and have been pretty happy with it.

A: I've used Aptana Studio (Eclipse) for a few years and it had a decent PHP editor with code hinting built-in. However, the new version of Aptana Studio now uses PHP Development Tools (PDT) instead of Aptana's own editor. I never had good luck with PDT, but hopefully development will improve now that Aptana is involved in the project.

A: I use NetBeans (on Windows and Linux), and  I have used Eclipse in the past (on Windows and Linux) and phpDesigner (on Windows) which is a commercial tool.
All three have approximately the same feature set, and all three can be used to debug PHP code.
ATM, I prefer NetBeans.
Previously I used plain editors such as Notepad++ and TextPad, my efficiency coding increased using an IDE with code-completion and runtime debugging.

A: I am not a PHP person, but from my (probably similar) Perl perspective, I find that the following functions of IDE are useful/not (as far as what I perceive to be IDE functions at least)

*

*Code styling (syntax hihgliting) and block folding - Highly useful. But this is a feature of a high-end editor rather than IDE proper, to be honest (e.g. it is included in non-IDE editor UltraEdit, not only in IDE-proper superset of UltraEdit Studio). Ditto for other features that i'd consider programming editor rather than IDE - e.g. FTP/source code repository integration, block selection, regex support, etc...

*Code analysis - function lists, etc... Useful but not life-shattering. A good intelligent hints would be nice but again not "must have".

*Integration with tools: For Perl, since there's no building, projects, compilation etc... as separate complicated steps, I found the need for IDE (and thus the win from using one) to be negligible. Other people might disagree.

*Integrated debugging - I never heard of a good IDE with integrated Perl debugging (my ideal for such functionality would always lie with Borland's Turbo series of IDEs :) ). But I would probably find it very useful/helpful given the crappy Perl debugging GUI people use, if I ever found one.

A: IDEs speed up development so much, just autocomplete is so useful.
I use CodeLobster which is really great and free, but it is especially good if you can afford to shell out money (and acutally have use for) for their various extensions for popular open source applications like WordPress, Joomla, etc.

A: I've used almost every editor I can think of for Windows and Linux, and I'd have to say that if I use an IDE these days - I love Eclipse PHP Developer Tools  (PDT). For beginners, I'd recomment the all-in-one.
Eclipse is such a good development platform, and everyone seems to like making plugins for it (as it's completely cross-OS, too).  Google has made their Google Web Toolkit (GWT) and Android plugins for Eclipse over other IDEs. Flex, Zend Studio, and Aptana Studio are just glorified versions of Eclipse as well.
Additionally, there are cool tools like Subclipse and Outline view (shows all functions in PHP / JavaScript, classes and rules in CSS), File Search [/ and Replace] with regular expression support, and easy comparison to local or remote files. These tend to speed up my overall development time, as I think they would for you too.
NOTE: There's a bit of a learning curve with Eclipse, and it's harder to simply edit a file at a time (it's best if you make projects), so it's really a matter of preference. If you're a professional PHP developer and you spend a majority of time on larger projects, I'd really recommend at least trying it out.

A: I use Vim. I find it the easiest and cleanest.

A: I've used Eclipse + PDT and NetBeans. I much prefer Eclipse.
I think any productivity gains are going to vary depending on both the developer and the nature of the project. I use TextMate or Vim for small projects, while I reserve IDEs for larger/more complex projects or ones with underlying APIs I am not familiar with. Having a built-in API completion is a big help when a project or its underlying framework have so many methods you can't possibly learn and remember all their signatures and return types (at least for the duration of the iteration one is working on). Also debugger integration on complex projects can be a huge timesaver (especially if you're not using a testing suite).
Another thing to keep in mind is that to see a big gain in efficiency, you have to learn how to use the toolset of the IDE efficiently which will have a learning curve. In my experience that cure hasn't been major in either IDE I've used, but it is there.

A: I don't use an IDE but I also work on fairly small projects in PHP.  I use textmate which is a bit like a *nix editor on mac with nice shell integration.  For scripting languages in general I don't use IDEs.  Personally, the only time I really appreciate an IDE is when you must compile/link.  I've never been a fan of make etc.

A: Eclipse PDT seems to work for me.  I'm not a web developer, but took on revamping a website for a non-profit who had their web developer leave due to job relocation.  Without any documentation or system overview, I was able to find my way around and make changes simply using Eclipse's variable information pop-up box tool (I'm not sure what it is formally called, but I hope you get the picture).  From a productivity point of view, the auto-indent and variable/keyword auto-completion features is a great speed booster.

A: If you're using a Mac, I recommend Coda. It has a great feature set - integrated FTP, SVN, CSS editor, terminal, etc. and a slick interface. It's US$99, but it is well worth it.

A: I really like Komodo Edit by ActiveState. I use the lite version of the software, and it keeps project files together, has code complete, code hightlighting, the works.