text:
Q: How to "simulate" C99 in Visual Studio for variables declaration I'm using Visual Studio 2012 to develop simple Win32 C programs. I know that the VS compiler only supports C89, but I'd like to know if there is a way to override this limitation.
In particular I'd like to declare variables anywhere in my code, instead of only at the beginning of scope blocks (as C89 requires).
Thanks in advance.

A: This seems like a dated thread, but having landed here first while I was searching for the same question I thought I should post an update:
As of VS13, the Visual C++ compiler supports C99 style variable declarations. More details here:
http://blogs.msdn.com/b/vcblog/archive/2013/06/28/c-11-14-stl-features-fixes-and-breaking-changes-in-vs-2013.aspx

A: The choices I see:

*

*stick with MSVC and switch to C++

*stick with MSVC and use a precompiler that translates C99 to C90 (Comeau, c99-to-c89)

*switch to a toolchain that supports more recent revisions of the C language (Intel, MinGW, Clang, Pelles-C,...)

A: Build your app using the C++ compiler. This is the easiest way. You can still write C code just name the file *.cpp


text:
Q: React: Unterminated JSX I am relatively new to react. I was trying to split my code in App.js components. Now, I am getting an error.
  ./src/containers/App.js
Syntax error: Unterminated JSX contents (64:12)

  62 |           Toggler = {this.togglerPersonHandler} />
  63 |           {person}
> 64 |

     |             ^
  65 |      )
  66 |    }
  67 | }

Here is my cockpit.js file (inside src/components/cockpit/cockpit.js)
import React from 'react';
import classes from './cockpit.css';

const Ccockpit = (props) => {
  const assignedClasses = [];
  let btnClass = ''
  btnClass = cockpit.red;

  if (cocPersonState) {
      btnClass = cockpit.red;
  }

  if (props.cocperson.length <= 2) {
    assignedClasses.push(classes.red)
  }
  if (props.cocperson.length <= 1) {
    assignedClasses.push(classes.bold)
  }
  return(

 Hi I am react App

hey

      <button className={btnClass}
      onClick={props.Toggler}>Button</button>

  );
}

export default Ccockpit;

And this is what I am doing in App.js file (src/containers/app.js)
import React, { Component } from 'react';
import classes from './App.css';
import Cperson from '../components/person/person.js';
import Ccockpit from '../components/cockpit/cockpit.js';

class App extends Component {
(some code here)

render() {
(some code here)
return (

      <Ccockpit>
          cocPersonState = {this.state.showPerson}
          cocperson = {this.state.person}
          Toggler = {this.togglerPersonHandler} />
          {person}

     )
   }
}
export default App;

Any Idea what could be wrong here? and fixes for the same?

A: Try this:
<Ccockpit
          cocPersonState = {this.state.showPerson}
          cocperson = {this.state.person}
          Toggler = {this.togglerPersonHandler} />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I make a Slow Sliding Banner with jquery like tourradar.com? has anyone an idea how to make a slow sliding fullscreen banner with HTML Element -> like http://www.tourradar.com/ (see startpage section Everything You Want & More)
Is there any jquery plugin which can do this?
Thanks.


text:
Q: How to draw on screen using RealBasic, Visual basic? Where i have one default laptop screen and second monitor I have my laptop default screen and second screen. How can I write RealBasic, VisualBasic (Java not possible) application which can allow me to paint on desktop (both screen)?

A: Most likely you won't be able to draw directly to the screen, but you could potentially grab screenshots of each screen and then draw onto those. Depending on what exactly you're trying to do with your application, it would almost definitely be a more realistic goal to grab a screenshot of each screen and then simply display the screenshots in standard windows that take up the entire screen, letting you then edit and "draw" onto the screen there.
Another option would be to create a transparent window, and then intercept mouse clicks and present information on that window.
If you're using RB on a Mac, you can use the Monkeybread Software Plugin to create a NSWindowMBS and modify the alpha value or an OverlayWindowMBS. It looks like you're trying to do this on Windows, though, so this won't work.


text:
Q: Update categorical levels in bokeh patch chart Building off of the example provided on bokeh website gallery, I added a dropdown widget. The dropdown values map to different lists of categorical levels.
What I'd like the update_data_plot function to do is to update those levels and diplay the new distributions.
from numpy import linspace
from scipy.stats.kde import gaussian_kde

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, FixedTicker, PrintfTickFormatter
from bokeh.plotting import figure
from bokeh.sampledata.perceptions import probly
from bokeh.io import curdoc
from bokeh.layouts import row, widgetbox, column
from bokeh.models.widgets import Slider, TextInput, Dropdown

# widgets
menu = [('A','A'), ('B','B')]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)

def ridge(category, data, scale=20):
    return list(zip([category]*len(data), scale*data))

def update_data_plot(attrname, old, new):
    """Update the chart to show
    the new categorical levels and
    their distribution"""

cats1 = list(reversed(probly.keys()))[:5]
cats2 = list(reversed(probly.keys()))[5:]

x = linspace(-20,110, 500)

source = ColumnDataSource(data=dict(x=x))

p = figure(y_range=cats1, plot_width=900, x_range=(-5, 105), toolbar_location=None)

for i, cat in enumerate(reversed(cats1)):
    pdf = gaussian_kde(probly[cat])
    y = ridge(cat, pdf(x))
    source.add(y, cat)
    p.patch('x', cat, alpha=0.6, line_color="black", source=source)

p.outline_line_color = None
p.background_fill_color = "#efefef"

p.xaxis.ticker = FixedTicker(ticks=list(range(0, 101, 10)))
p.xaxis.formatter = PrintfTickFormatter(format="%d%%")

p.ygrid.grid_line_color = None
p.xgrid.grid_line_color = "#dddddd"
p.xgrid.ticker = p.xaxis[0].ticker

p.axis.minor_tick_line_color = None
p.axis.major_tick_line_color = None
p.axis.axis_line_color = None

p.y_range.range_padding = 0.12

dropdown.on_change('value',update_data)

curdoc().add_root(column(dropdown,
    p, width=50))
curdoc().title = "Sliders"

A: It's been a while since I did something like this. I did this on a local bokeh serve application, I don't think I ever got it working in a notebook. Looking at my old code, updating the source.data with the .data of a new ColumnDataSource worked.
def update_data_plot(attrname, old, new):
    new_value = dropdown.value
    # here make something that you can pass to construct a new ColumnDatasource with the new value
    # and put it into a variable called newdata
    source.data = ColumnDataSource(data=newdata).data


text:
Q: What is a good introductory textbook to Laser Safety? I was looking for a good textbook about Laser Safety (e.g. protection glasses design, distance of risk calculation, laser classification...). I can't find a complete book with these informations, could you recommend one for me?

A: There's ton of material on internet regarding laser safety. Most universities and organisation have work manuals that are almost same w.r.t measurement of hazards and safety regulations/procedures.
Here you can find some good resource from top universities

*

*https://ehs.princeton.edu/sites/ehs/files/media_files/Laser%20Training%20Guide%202007%2013-08.pdf

*Very detailed, also includes the examples of calculation. https://www.ucc.ie/en/media/training/workthings/UCCLaserSafetyGuidelines.pdf

*https://www.ehs.ucsb.edu/sites/default/files/docs/rs/lasersaftyman.pdf

*This one list the calculations in very simple and clear way. https://d3qi0qp55mx5f5.cloudfront.net/researchsafety/docs/Laser_Safety_Calculations.pdf?mtime=1610127144

*Most detailed, Military classified https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/49543/jsp390_military_laser_safety_2005edition.pdf


text:
Q: Force .ix to return a DataFrame in pandas When I use .ix with a DataFrame, is there any way to force pandas to always return a DataFrame?
For example, if I run the following lines,
import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(6).reshape(3, 2), index=[0, 0, 1])
x = df.ix[0]
y = df.ix[1]

then x will be a DataFrame, because 0 appears twice in the index, and y will be a Series, because 1 is unique in the index.  I want y to be a DataFrame too (because I'm using iterrows(), which isn't defined for Series, on the result).
I can check the type of whatever .ix returns and convert it to a DataFrame if needed, but I thought there'd be a better way.
Note: As of Pandas v0.20, .ix indexer is deprecated in favour of .iloc / .loc.

A: Yes, index it with a list:
> x = df.ix[[0]]
> y = df.ix[[1]]
> type(x)
pandas.core.frame.DataFrame
> type(y)
pandas.core.frame.DataFrame


text:
Q: How to run a php file on a specific date that's polled from database? I am trying to run a php file on a specific date that's polled from mysql database.
I know that I can use cron job but the problem is that the date is updated once in a while. so I don't have a fixed date that I could use to set up my cron job.The only way that I could get the date is from the database.
I know there is another option that I write code in my php file to check if today is the date, if it is, execute the code. If it is not, do nothing. Then set a cron job that runs everyday for this php file. But the problem will be that the interval between the date is usually 1 to 3 months. Would it be a very bad idea to check it everyday but only run it every 1 or 3 month?
I am trying to run the php file to update the data of a website. If I just put the php code in the code of the website to check the date, will that work?
Is there a better way of doing this?
Thank you.


text:
Q: Не находит файл по относительному пути Я делаю свой первый тестовый maven проект, в нем есть файл properties. Если я использую относительный путь к файлу следующим образом:
InputStream input = getClass().getResourceAsStream("src/resources/property.properties")

или так:
InputStream input = new FileInputStream(new File("src\\resources\\property.properties"))

то при запуске war на tomcat не считывает данные из файла, получается null.
При этом если задать абсолютный путь к файлу String path = "E:\\java\\Cinema\\src\\resources\\property.properties", все работает.
В чем может быть проблема?

A: Каталог Resources по умолчанию и так должен быть в ClassPath потому попробуйте написать просто:
InputStream input = getClass().getResourceAsStream("property.properties");

Если файл вне приложения тогда так:
 InputStream input = new FileInputStream(new File(".").getAbsoluteFile().getParentFile().getAbsolutePath() + System.getProperty("file.separator")+"тут относительный путь до файла (относительно файла запуска)/property.properties");

A: Может кому то будет полезна информация, maven почему то не видел папку с ресурсами, проблему решила добавлением в pom файл указания на папку с ресурсами
 <resources>
            <resource>
                <directory>src/resources</directory>
            </resource>
 </resources>

После этого стал работать вариант InputStream input = getClass().getResourceAsStream("property.properties");


text:
Q: use regex Matcher.group to copy words I'm interested in putting the numbers into a an array of String's but can't get the usage of regex and groups quite worked out.
code:
package regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {

    public static void main(String[] args) {
        String s = "A: 123/456  BC: 78/90  NEw: 105 E: 0  BK: 10 None: 0%";
        Pattern p = Pattern.compile("(\\w+): (\\d+)");
        Matcher m = p.matcher(s);
        String[] as = new String[7];
        as[2] = m.group();  //array list??
        for (int i = 2; i < 2; i++) {
            System.out.println(as[i]);
        }
    }
}

A: You need to change
Pattern p = Pattern.compile("(\\w+): (\\d+)");
into
Pattern p = Pattern.compile("(\\w+): (\\d+/{0,1}\\d*%{0,1})");

A: Matcher does not work the way you try to use it. The group() method returns last matched group. To actually tell the matcher to match something, you need to call find() first. find() returns a boolean that tells whether or not the matcher managed to find the next match, so that you can loop through all the matches like this:
while (m.find()) {
    String text = m.group();
    // ...
}

A: You can try the regular expression:
(\w+): +(\S+)

e.g.:
private static final Pattern REGEX_PATTERN =
        Pattern.compile("(\\w+): +(\\S+)");

public static void main(String[] args) {
    String input = "A: 123/456  BC: 78/90  NEw: 105 E: 0  BK: 10 None: 0%";
    Matcher matcher = REGEX_PATTERN.matcher(input);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

Output:
A: 123/456
BC: 78/90
NEw: 105
E: 0
BK: 10
None: 0%

If you want to get the name, matcher.group(1), or the number, with matcher.group(2).
private static final Pattern REGEX_PATTERN =
        Pattern.compile("(\\w+): +(\\S+)");

public static void main(String[] args) {
    String input = "A: 123/456  BC: 78/90  NEw: 105 E: 0  BK: 10 None: 0%";
    Matcher matcher = REGEX_PATTERN.matcher(input);
    while (matcher.find()) {
        System.out.println("Name: " + matcher.group(1));
        System.out.println("Number: " + matcher.group(2));
    }
}

Output:
Name: A
Number: 123/456
Name: BC
Number: 78/90
Name: NEw
Number: 105
Name: E
Number: 0
Name: BK
Number: 10
Name: None
Number: 0%

A: just thought I'd throw this out there for a reaction:
package regex;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {

    public static void main(String[] args) {
        List<Map.Entry> l = new ArrayList<>();
        String monitor = "A: 123/456  BC: 78/90  NEw: 105 E: 0  BK: 10 None: 0%";
        Pattern outerPattern = Pattern.compile("(\\w+): (\\d+)");
        Matcher outerMatcher = outerPattern.matcher(monitor);
        String outerGroup = null;
        int i = 0;
        Pattern innerPattern;
        Matcher innerMatcher;
        String innerGroup = null;
        while (outerMatcher.find()) {
            outerGroup = outerMatcher.group();
            System.out.println(outerGroup);
            innerPattern = Pattern.compile("(\\w+): (\\d+)");
            innerMatcher = innerPattern.matcher(outerGroup);
            while (innerMatcher.find()) {
                innerGroup = innerMatcher.group();
                System.out.println(innerGroup);
                Map.Entry<String, Integer> entr = new AbstractMap.SimpleEntry<>("exmpleString", 42);
                l.add(entr);
            }
        }
    }
}


text:
Q: python requests issue 429 bad request Why when I call a website with curl it works, but when call with python always return 429? I tried to set a lot different user-agent, cookies...
curl call:
curl "https://query2.finance.yahoo.com/v10/finance/quoteSummary/GLW?formatted=true&crumb=8ldhetOu7RJ&lang=en-US&region=US&modules=summaryDetail&corsDomain=finance.yahoo.com"

response: {"quoteSummary":{"result":[{"summaryDetail":{"maxAge":1,"priceHint":{"raw":2,"fmt":"2","longFmt":"2"},"previousClose":{"raw":37.12,"fmt":"37.12"},"open":{"raw":37.19,"fmt":"37.19"},"dayLow":{"raw":37.12,"fmt":"37.12"},"dayHigh":{"raw":37.95,"fmt":"37.95"},"regularMarketPreviousClose":{"raw":37.12,"fmt":"37.12"},"regularMarketOpen":{"raw":37.19,"fmt":"37.19"},"regularMarketDayLow":{"raw":37.12,"fmt":"37.12"},"regularMarketDayHigh":{"raw":37.95,"fmt":"37.95"},"dividendRate":{"raw":0.88,"fmt":"0.88"},"dividendYield":{"raw":0.0232,"fmt":"2.32%"},"exDividendDate":{"raw":1605139200,"fmt":"2020-11-12"},"payoutRatio":{"raw":3.3077,"fmt":"330.77%"},"fiveYearAvgDividendYield":{"raw":2.43,"fmt":"2.43"},"beta":{"raw":1.173753,"fmt":"1.17"},"trailingPE":{"raw":148.82353,"fmt":"148.82"},"forwardPE":{"raw":20.294119,"fmt":"20.29"},"volume":{"raw":3372416,"fmt":"3.37M","longFmt":"3,372,416"},"regularMarketVolume":{"raw":3372416,"fmt":"3.37M","longFmt":"3,372,416"},"averageVolume":{"raw":4245485,"fmt":"4.25M","longFmt":"4,245,485"},"averageVolume10days":{"raw":3351485,"fmt":"3.35M","longFmt":"3,351,485"},"averageDailyVolume10Day":{"raw":3351485,"fmt":"3.35M","longFmt":"3,351,485"},"bid":{"raw":37.88,"fmt":"37.88"},"ask":{"raw":37.89,"fmt":"37.89"},"bidSize":{"raw":1100,"fmt":"1.1k","longFmt":"1,100"},"askSize":{"raw":800,"fmt":"800","longFmt":"800"},"marketCap":{"raw":28994179072,"fmt":"28.99B","longFmt":"28,994,179,072"},"yield":{},"ytdReturn":{},"totalAssets":{},"expireDate":{},"strikePrice":{},"openInterest":{},"fiftyTwoWeekLow":{"raw":17.44,"fmt":"17.44"},"fiftyTwoWeekHigh":{"raw":37.95,"fmt":"37.95"},"priceToSalesTrailing12Months":{"raw":2.6921244,"fmt":"2.69"},"fiftyDayAverage":{"raw":35.406857,"fmt":"35.41"},"twoHundredDayAverage":{"raw":31.052786,"fmt":"31.05"},"trailingAnnualDividendRate":{"raw":0.86,"fmt":"0.86"},"trailingAnnualDividendYield":{"raw":0.023168104,"fmt":"2.32%"},"navPrice":{},"currency":"USD","fromCurrency":null,"toCurrency":null,"lastMarket":null,"volume24Hr":{},"volumeAllCurrencies":{},"circulatingSupply":{},"algorithm":null,"maxSupply":{},"startDate":{},"tradeable":false}}],"error":null}}
with python:
import requests
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}
result = requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/GLW?formatted=true&crumb=8ldhetOu7RJ&lang=en-US&region=US&modules=summaryDetail&corsDomain=finance.yahoo.com', headers=headers)
print result.content

response:
Traceback (most recent call last):
  File "a.py", line 35, in <module>
    response = urllib.request.urlopen(req, jsondataasbytes)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 531, in open
    response = meth(req, response)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 569, in error
    return self._call_chain(*args)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 503, in _call_chain
    result = func(*args)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 429: Too Many Requests

A: Ok, ok, solved by passing get parameters via params:
import requests
payload = {"modules": "summaryDetail"}
response = requests.get("https://query2.finance.yahoo.com/v10/finance/quoteSummary/GLW", params=payload)
print(response.json())


text:
Q: Is there a simple characterization of the functions for which the Fourier inversion theorem holds identically? I was thinking a little more about my previous quesion about whether there is a natural section of canonical representatives of the quotient map from the space $\mathcal{L}^2(\mathbb{R})$ of square-integrable functions to the Hilbert space $L^2(\mathbb{R})$ (in which we mod out the kernel of the $L^2$ norm). Another possibility occurs to me, which is manifestly basis-independent.
The Fourier transform is a unitary operator on the Hilbert space $L^2(\mathbb{R})$. The Fourier inversion theorem holds almost everywhere for functions $f \in \mathcal{L}^2$; that is, $\mathcal{F}^{-1}(\mathcal{F}f)(x)$ and $\mathcal{F}(\mathcal{F}^{-1}f)(x)$ both agree with $f(x)$ almost everywhere. Since modding out by the kernel eliminates the "almost everywhere" subtlety, we have that $\mathcal{F} \mathcal{F}^{-1}$ and $\mathcal{F}^{-1}\mathcal{F}$ both equal the identity on the Hilbert space $L^2(\mathbb{R})$.
I think, although I'm not positive, that the transform $\mathcal{F} \mathcal{F}^{-1}$ and/or $\mathcal{F}^{-1}\mathcal{F}$ actually implements the quotient map, in the sense that these transformations take all the functions in each equivalence class in $L^2(\mathbb{R})$ to a single canonical representative. In this case, a natural section of the quotient map would be the set of functions $f \in \mathcal{L}^2$ for which the Fourier inversion theorem holds everywhere, rather than almost everywhere. Is this correct?

A: You don't necessarily get convergence everywhere for $\mathcal{F}^{-1}\mathcal{F}f$. So your choice of $f$ would not be defined everywhere using this methodology. It is true that $\mathcal{F}f$ and $\mathcal{F}g$ are identical if $f=g$ a.e. because these are defined through limits of integrals. So that means you're generally not going to be able to find an $f$ in the equivalence class for which $\mathcal{F}^{-1}\mathcal{F}f$ converges everywhere.


text:
Q: Is the Game of the Year version of Fable 2 as buggy as the standard version? I had Fable 2 for XBOX360 (PAL version, i.e. Europe/Australia) and it was buggy as hell. If I was married, my wife would go from totally happy to leaving me in an instant. There were several other minor glitches that annoyed me. I traded in the game because I got sick of the bugs.
Does anyone know if the GOTY version does anything to fix these annoyances? If so I might pick it up on the cheap to tide me over until fable 3...

A: That's probably just the PAL version. I've played through the NTSC one, and saw no problems at all - nor have I heard of any problems from others who have played it.
Chances are you're going to see the same types of bugs between the original edition and the GotY edition, simply due to the fact that GotY will only include the new/downloadable content that's been made available since the original's release.
If you can't play using another region code, then you could try the game on a different console, and see if the bugs propagate.

A: I have the GOTY version (PAL) and I havent faced any issues so far. I have completed the main quest and now working on some side quests. My wife did leave me (and my child was taken away by some agency) but that's because I was too busy buying and selling real estate.


text:
Q: Why does scrollTo work in my ClickListener but not in AfterViewInit? I am wondering why the following works:
scroll(){
    window.scrollTo(0, this.ypos); // works perfectly fine
}

And in my html.component:
<button (click)="scroll()">Scroll</button>

but the following won't work:
ngAfterViewInit(){
    console.log(this.ypos); // is perfectly defined
    window.scrollTo(0, this.ypos); // won't work
}

Do anyone know why it does not work? window.scrollTo() does also not work for ngOnInit but why?

A: Instead of using window object, use angular Viewportscroller service to scrolls to a specified position.
component.ts
   import { ViewportScroller } from '@angular/common';

   constructor(private viewportScroller: ViewportScroller) {}

   ngAfterViewInit(){
    this.viewportScroller.scrollToPosition([0,this.ypos]);
   }


text:
Q: Single MOSFET motor driver with oscillation on output I'm trying to drive a small DC motor with a PWM with the circuit below, where I'm using a TIL111 optocoupler and a IRF510N MOSFET. The PWM (50% duty cycle) is generated by a MCU STM32F103C8T6, the +3.3V source comes from this MCU and the +5V source is another one.

The motor drives, but the waveform over the motor looks like the one below (sorry for my oscilloscope). The image isn't clear but what happens is that this output have some waves (resembling coil discharging waves) when it should be off, or 0V (the ON semi-period is working ok). Since I have a +5V source and a 50% duty PWM, I should measure 2.5V over the motor, but, with this signal, I'm measuring 3.55V.

If I remove the motor and put some 120 ohm resistor in its place, I can visualize the correct waveform below. I also verified the waveform over the opto and over the MOSFET's gate, and it's working fine (with or without the motor).

I'm using this dummy dc motor below, but I have tested with other two dummy motors and having the same result. Actually, I tried to drive these motors with a TIP before, using a similar circuit; that time, I changed pretty much all the components (TIPs, resistors, diodes, motors, protoboards) and I still ended with this same result. If someone could tell me some tip about why I'm having this behavior, I would be grateful.

A: It would be more illuminating if you trigger your oscilloscope off of FET gate -- that should be a cleaner signal.
What's happening is that the circuit will push current into the motor, but it won't pull it out.  So when the FET is on, if the motor is spinning any slower than it's no-load speed with 5V applied, the motor will speed up.  When the FET is off, the motor will coast along, generating a voltage proportional to its speed.  Because the system is lossy, the motor isn't spinning quite fast enough to generate 5V -- but it's pretty close to it.  You're reading the average of 5V and whatever the motor generates as it's coasting.


text:
Q: Can we Convert Anonymous Type to List  using Linq to entity in C#? I have a table with three columns i want to use self join and retrieve the columns with alias name.
Table:Material(ID,Name,MaterialParentID)
public List<Material> GetMaterialList()
{
    List<Material> materilaList = new List<Material>();
    var query = (from c1 in db.Materials
                 join c2 in db.Materials on c1.ID equals c2.MaterialParentID
                 select c2);

    return query.ToList();
}

I want to add following to exisiting query and return the List
select new { c2.ID, c2.MaterialParentID, c2.Name, ParentName = c1.Name })

A: Just use the actual concrete type instead of an anonymous one:
select new Material {
    ID = c2.ID,
    MaterialParentID = c2.MaterialParentID,
    Name = c2.Name,
    ParentName = c1.Name
}

A: foreach(var row in query)
{
    material mat =new material();
    mat.id=row.ID;
    mat.name=row.Name;

    materilaList.add(mat);
}

return materiList;


text:
Q: Various Query Builder I'm creating a framework MVC to build my applications. In my application I need to use several DBMS s and I need be prepared for that.
I'm thinking in to use Active Record pattern and it have the "connection" (abstract) associated. The Active Record don't know which DBMS to be used. So, I use Factory Method for have abstract which DBMS been used.
How will I build various queries (CRUD) ? Because each DBMS will need specific query.
I'm think that creating various classes "QueryBuilder" it will can to resolve (one class for each DBMS ).
What's think?

A: To resolve this issue, you can use DAO Layer Pattern. This pattern hides the database specific details from the client. You can define the interface for CRUD operation which your DAO will implement.
In this way, even your DB changes in future, client of DAO layer don't have to worry about the changes.
Refer below wiki page for more details about this pattern.
http://en.wikipedia.org/wiki/Data_access_object

A: I assume the intent is to insulate the various ActiveRecord objects from the SQL syntax variances between the DBs?
You didn't define what you exacty intended with a design for your query bulder, but I've done once with methods like AddSelection(colName), AddCriteria(colName, ComparisonEnum, value), etc.  If that is your approach then if your queries are small/simple enough then a query builder would work.  BUT as soon as you need the ability to build complex joins or inner subqueries then you may hit a wall with that approach.
If you need to handle arbitrarily difficult queries then another option is to create a converter or translator.  If you were to define a canonical query format, then each DBMS-specific convert would know how to convert from that canonical format to the DB-specific syntax.  You've really got to need this functionality to make it worth the effort though.
And finally, your other appraoch is to subclass the ActiveRecord for each DB.  So if you have an EmployeeRecord class you can subclass it with OracleEmployeeRecord, MySqlEmployeeRecord, MsSqlServerEmployeeRecord, and the like.  Then use an abstract factory to create the appropriate ActiveRecord objects.


text:
Q: Pgfplots does not load data table I am relatively new to LaTeX, and I am trying to include plots with the help of pgfplots. The problem I have is very basic, and therefore very confusing for me.
Plotting a simple graph from a table included in the .tex file works:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.14}
\begin{document}

\begin{tikzpicture}
\begin{axis}

\pgfplotstableread{
1   1   2
2   2   4
3   3   8
}\datatable

\addplot table[y index = 2] from \datatable ;
\addplot table[y index = 1] from \datatable ;

\end{axis}
\end{tikzpicture}

\end{document}

But If I copy/paste the table into a data.dat file in the same folder as the .tex file, and change the code to
\pgfplotstableread{data.dat}\datatable

I get an error message:
    Could not read table file 'data.dat' in 'search path=.'.
I have no idea where the mistake is, and I would be very grateful for any tips and help!

A: It works for me when I use your example. I changed your \pgfplotsset{compat=1.14} to \pgfplotsset{compat=newest} but that should not make a difference.
Make sure that you actually save the file as a data.dat and not data.dat.txt.


text:
Q: Getting the destination IP of incoming UDP packet in C++ I found the function: GetTcpTable in C++. In the header: iphlpapi.h. That gives me the destination IP of TCP packet and I was wondering if there's a function from the same header that would give me the destination IP of UDP packet... I tried the function: GetUdpTable but it gives only the local IP and port. I will be more than happy if that function has also code example in  C++ of course. Thank you anyway!
EDIT:
I using pcap.h now and i still don't know how to catch UDP packets and take from them the ip. There is a code that i can use?

A: GetTcpTable() does not give you the destination IP of TCP packets.  It merely gives you a list of currently listening TCP ports and active TCP connections.
GetUdpTable() can give you the list of currently listening UDP ports, where UDP packets can be sent to.  There are no connections in UDP.
But, if you want to know the actual destination IP for each UDP packet received, and without having to use a low-level capture library like WinPCap, then you can use the WSARecvMsg() function to receive your UDP packets, rather than using the recvfrom() or even recv() function.
WSARecvMsg() can report metadata about each packet, most notably the IP_PKTINFO (IPv4) and IPV6_PKTINFO (IPv6) control blocks, which specify the destination IP of the packet and the index of the network interface that received the packet.
You need to use WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) to obtain a pointer to the WSARecvMsg() function (see Why is the WSARecvMsg function implemented as a function pointer and can this pointer be reused? for the reason why), and use setsockopt() to enable the IP_PKTINFO/IPV6_PKTINFO socket option, before you start calling WSARecvMsg() to receive packets.
See Function to retrieve the header destination address from a packet in windows XP for an example.


text:
Q: Cakephp 2.0, controller doesn't see model I'm busy upgrading a site for a client of mine. It's my first time working with CakePHP and I'm running into issues.
I created a table named banners inside my database, and I made the following files:
Model/Banner.php
Controllers/BannersController.php
View/Banners/admin_index.ctp

It seems like my controller can't find the model. Whenever I try to load the page admin_index.ctp I get the following message: Error: An Internal Error Has Occurred.
If i replace the contents of my public admin_index() and make it echo text, it does work.
I also tried adding a form to my admin_index.ctp by doing this
echo $this->Form->create('Banner');

This gives me another Error: An Internal Error Has Occurred.
I have set up my model, controller, view and database exactly the way the others for posts, pages, etc are set up and i just can't seem to get it to work. Does anyone have any idea on how to fix this?
Kind Regards,
Nick
<?php
class Banner extends AppModel {

}
?>

<?php
class BannersController extends AppController {
public $helpers = array('Html', 'Form');

public function admin_index(){
    $banners = $this->Banner->find('all');
    $this->set('banners', $banners);
}
?>

Stack Trace:
#0 /srv/nkuchiki/www/www.kuchiki.nl/app/webroot/index.php(111): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
#1 {main}
2015-04-10 17:29:43 Error: [MissingTableException] Table banners for model Banner was not found in datasource default.
Exception Attributes: array (
  'table' => 'banners',
  'class' => 'Banner',
  'ds' => 'default',
)

Request URL: /admin/banners
Stack Trace:
#0 /srv/nkuchiki/www/www.kuchiki.nl/lib/Cake/Model/Model.php(3501): Model->setSource('banners')
#1 /srv/nkuchiki/www/www.kuchiki.nl/lib/Cake/Model/Model.php(2905): Model->getDataSource()
#2 /srv/nkuchiki/www/www.kuchiki.nl/lib/Cake/Model/Model.php(2877): Model->_readDataSource('all', Array)
#3 /srv/nkuchiki/www/www.kuchiki.nl/app/Controller/BannersController.php(7): Model->find('all')
#4 [internal function]: BannersController->admin_index()
#5 /srv/nkuchiki/www/www.kuchiki.nl/lib/Cake/Controller/Controller.php(490): ReflectionMethod->invokeArgs(Object(BannersController), Array)
#6 /srv/nkuchiki/www/www.kuchiki.nl/lib/Cake/Routing/Dispatcher.php(191): Controller->invokeAction(Object(CakeRequest))
#7 /srv/nkuchiki/www/www.kuchiki.nl/lib/Cake/Routing/Dispatcher.php(165): Dispatcher->_invoke(Object(BannersController), Object(CakeRequest))
#8 /srv/nkuchiki/www/www.kuchiki.nl/app/webroot/index.php(111): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
#9 {main}

A: Thanks for all the advice guys. Based on the extended error message i did some research on google and found some other threads on stackoverflow.
i removed the files in my tmp/cache/models, and tmp/cache/persistent and the problem was resolved :-).
It can be really difficult to find a problem when everything seems to be programmed right.


text:
Q: How can i randomly call a movieclip do something? My stage have 3 movieclip that is mc1,mc2 and mc3.
each of them are now alpha=0.
I have a button on stage too and when click on it, 1 of the movieclip will be change to alpha=1.
here is my script:
var mcArray:Array = [mc1,mc2,mc3];
for (var j:int = 0; j < hotSpot.length; j++)
{
    mcArray[j].alpha=0;
}

revealBtn.buttonMode = true;
    revealBtn.useHandCursor = false;
    revealBtn.addEventListener(MouseEvent.CLICK, revealClick);
function revealClick(event:MouseEvent):void
{
//what i need to write here?
}

A: Here is an example showing how to show a random display object after clicking the stage:
Main.as(document class):
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class Main extends Sprite
    {
        private var _sprites:Vector.<Sprite>;

        public function Main():void
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);

        }// end function

        private function init(e:Event = null):void
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            _sprites = new Vector.<Sprite>();

            for (var i:int = 0; i < 3; i++)
            {
                var sprite:Sprite = new Sprite();
                sprite.graphics.beginFill(0xFF0000);
                sprite.graphics.drawRect(0, 0, 100, 100);
                sprite.graphics.endFill();
                sprite.x = ((sprite.width + 50) * i);
                sprite.y = 0;
                addChild(sprite);

                _sprites.push(sprite);

            }// end for

            hideSprites();

            stage.addEventListener(MouseEvent.CLICK, onClick);

        }// end function

        private function onClick(e:MouseEvent):void
        {
            showSprite();

        }// end function

        private function showSprite():void
        {
            hideSprites();

            (_sprites[random(0, 2)] as Sprite).alpha = 1;

        }// end function

        private function hideSprites():void
        {
            for each(var sprite:Sprite in _sprites)
            {
                sprite.alpha = 0;

            }// end for each

        }// end function

        private function random(min:int, max:int):int
        {
            return (Math.floor(Math.random() * (1 + max - min)) +min);

        }// end function

    }// end class

}// end package

Simply put, you use Math.round() to get a random index for your display object array, in this example that happens here:
(_sprites[random(0, 2)] as Sprite).alpha = 1;

private function random(min:int, max:int):int
{
    return (Math.floor(Math.random() * (1 + max - min)) +min);

}// end function

You can also replace the value for the random() method's max argument with _sprites.length - 1 which will also return 2.

A: Extending my comment to the question, here's what you would do step by step:
//Generate random number (integer) between 0 and mcArray.length
var i:Number=Math.floor(Math.random() * mcArray.length);

//Select ith element of mcArray
var movieClipToEdit:MovieClip=mcArray[i] as MovieClip;

//Change its alpha to 1
movieClipToEdit.alpha=1;

If you want to hide all other movie clips, add this:
for (var j:int = 0; j < mcArray.length; j++) {
    mcArray[j].alpha=0;
}


text:
Q: JsonMappingException$Reference not found when calling a RESTful web service using JBoss 7 and RESTeasy I have created a RESTful web service producing JSON content with JAX-RS, it uses some JPA entities, it runs on JBoss 7.1.3.
I get the following error message when calling this web service:

13:23:11,834 ERROR
  [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/*****WebServices].[com.******.******.rest.config.ApplicationConfig]]
  (http-/127.0.0.1:8080-2) "Servlet.service()" for the servlet
  com.******.******.rest.config.ApplicationConfig threw an
  exception: java.lang.ClassNotFoundException:
  org.codehaus.jackson.map.JsonMappingException$Reference from [Module
  "org.codehaus.jackson.jackson-mapper-asl:main" from local module
  loader @6514af16 (roots:
  C:**********\jboss-as-7.1.3.Final-bundled4STR\modules)]  at
  org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
    at
  org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
    at
  org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
    at
  org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    at
  org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
    at
  org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:166)
    at
  org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    at
  org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
    at
  org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
    at
  org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)

Before trying this solution, I replaced modules\org\codehaus\jackson\jackson-mapper-asl\main\jackson-mapper-asl-1.9.2.jar by a more recent version, I tried with the version 1.9.3 and with the version 1.9.7. It didn't help.
I added org.codehaus.jackson.jackson-mapper-asl into jboss-deployment-structure.xml but it didn't solve my problem.
I know that JBoss includes RESTeasy since its seventh version, at least one provider uses jackson: org.jboss.resteasy.resteasy-jackson-provider.
This kind of error can happen when different versions of the same libraries are used to compile and to run a project but I don't find the culprit. I don't use jackson in my own code.
Does this bug come from JBoss? Is it fixed in a later version? Switching to WildFly isn't an option.

A: I switched to Wildfly in the meantime for some projects (currently Wildfly 27). I can't confirm whether it's still reproducible with a more recent version of JBoss.


text:
Q: Show that the field $L = \mathbb F_3[X]/\langle X^5 - X + 1\rangle$ consists of $243$ elements and that $[X][f] = [1]$ for some $[f] \in L$.
Show that the field $L = \mathbb F_3[X]/\langle X^5 - X + 1\rangle$ consists of $243$ elements and that $[X][f] = [1]$ for some $[f] \in L$.

I know that $L$ is a ring, so it is also a group with respect to $+$. However I how no idea how to calculate the size of $L$ or finding $[f]$ such that $[X][f] = [1]$ other than by brute-force, which is a terrible approach to solving a problem of this size.
Also I've proven that $\langle X^5 - X + 1\rangle$ is a maximal ideal and that $X^5 - X + 1$ is irreducible.
Could someone give me a hint or help to fit the "loose ends" here ?


text:
Q: Installing Parse Server Generic Email Adapter I use parse-server with AWS elastic beanstalk.
There was the mailgun email adapter installed as default, but I want to install the generic email adapter so I can send e-mails with a gmail account. I want to install the plugin below but I do not now how to.
The Parse Server Generic Email Adapter
The command to install is as below:
$ npm install --save parse-server-generic-email-adapter

But I am not very professional in server side. Generally what I do is open terminal from my mac computer and write eb init then make changes in the index and cloud code file and write eb deploy.
I don't know where and how to run the command above to install the email adapter. First I run eb init, then eb labs download and in the location where the sever files are downloaded; I try to run the command above from terminal and I get the messages as below:
usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 file2
       install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 ... fileN directory
       install -d [-v] [-g group] [-m mode] [-o owner] directory ...

Any help would be great.

A: Ok,
I found how to do it, if you use elastic beanstalk with parse-server, and want to use generic mail adapter;
1) in your package.json file dependencies add:
"parse-server-generic-email-adapter": "0.0.4"

2) in your index.js file - email adapter part, add:
module: 'parse-server-generic-email-adapter',
 options: {
  service: 'Gmail',
  email: 'xxxxxxx@gmail.com',
  password: 'xxxxxxx',
}

And deploy your files to your elastic beanstalk server with eb deploy.


text:
Q: Android Linkify makes not phone number clickable I am trying to make clickable phone number 0900-123 4567 in textview with simple code. On some phones and android versions it works, on some not. Mostly only 0900-123 is clickable, 4567 is not added. Sometimes on the same phone number is clickable when phone language is english but not clickable when language is french. Any idea how it can be fixed to work everywhere ?
acceptMatch procedure is hit and returns true always
TextView tv = (TextView) findViewById(R.id.test);
    Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{3} [0-9]{4}");

    Linkify.MatchFilter matchFilter = new Linkify.MatchFilter() {
        @Override
        public final boolean acceptMatch(CharSequence s, int start, int end) {
            if (s != null && s.subSequence(start,end).toString().equals("0900-123 4567"))
                return true;
            else
                return false;
        }
    };

    Linkify.addLinks(tv, pattern, "tel:", matchFilter, null);

<TextView
    android:id="@+id/test"
    android:clickable="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="phone"
    android:text="Hello 0900-123 456 (some other text)."/>


text:
Q: Excel: Userform Textbox match function I'm trying to get the userform to update other fields when I update a textbox.
My problem is that even though I write TextBox1.Value it still treats my input as text and thus only finds a match if I format my numbers in the table as text.
Below is my current code:
Private Sub TextBox1_Change()
On Error Resume Next
ComboBox2.Value = Application.WorksheetFunction.Index(Sheets("Projekt").Range("Projektnamn"), Application.WorksheetFunction.Match(TextBox1.Value, Sheets("Projekt").Range("Projektnr"), 0), 1)

End Sub
This code works but is not connected to the userform.
(I put in a number (155001) that the range:"Projektnr" contains)
So it is the first part of the Match function that doesn't work.
    Private Sub TextBox1_Change()
On Error Resume Next
ComboBox1.Value = Application.WorksheetFunction.Index(Sheets("Projekt").Range("Projektnamn"), Application.WorksheetFunction.Match(155001, Sheets("Projekt").Range("Projektnr"), 0), 1)

End Sub
I tried gizlmeiers suggestion and it still refuses to find a match.
I attatch that code as well:
    Private Sub TextBox1_Change()
On Error Resume Next
Test = CInt(TextBox1.Value)
ComboBox1.Value = Application.WorksheetFunction.Index(Sheets("Projekt").Range("Projektnamn"), Application.WorksheetFunction.Match(Test, Sheets("Projekt").Range("Projektnr"), 0), 1)

A: So you are trying to compare two numbers, but the one in the textbox is interpreted as a string?
You can tell vba to interpret it as a number by using CINT()
CINT(TextBox1.Value)


text:
Q: C++ erasing section of vector with a size_t as start point I want to erase a section of a std::vector e.g ith element through end. Where i is a std::size_t that is calculated beforehand.
auto i = vec.size();

for (auto pos = vec.size(); pos > 0; --pos) {
  auto& elem = vec.at(pos - 1);

  if (*magic_condition*) {
    --i;
  }
}

vec.erase(vec.begin() + i, vec.end());

I get a Conversion may change the sign of the result warning
I tried using std::next but that still results in the same warning
The only why I found that gets rid of the warning, but I think is very unelegant is
const auto begin = typename decltype(vec)::const_iterator{vec.data() + i};

vec.erase(begin, vec.end());

Is there any good solution to get rid if this warning?
EDIT:
void update(const delta_type delta) {
  auto size = handlers.size();

  for(auto itr = handlers.rbegin(); itr != handlers.rend(); ++itr) {
    auto& handler = *itr;

    if(const auto dead = handler.update(handler, delta); dead) {
      std::swap(handler, handlers.at(--size));
    }
  }

  handlers.erase(handlers.begin() + size, handlers.end());
}

Results in following error
../ecs/scheduler.hpp: In instantiation of 'void sbx::scheduler<Delta>::update(sbx::scheduler<Delta>::delta_type) [with Delta = float; sbx::scheduler<Delta>::delta_type = float]':
/home/kabelitzj/Dev/sandbox/sandbox/core/engine.cpp:39:29:   required from here
../ecs/scheduler.hpp:64:39: warning: conversion to '__gnu_cxx::__normal_iterator<sbx::scheduler<float>::process_handler*, std::vector<sbx::scheduler<float>::process_handler, std::allocator<sbx::scheduler<float>::process_handler> > >::difference_type' {aka 'long int'} from 'long unsigned int' may change the sign of the result [-Wsign-conversion]
   64 |     handlers.erase(handlers.begin() + size, handlers.end());
      |

Compiled with g++ version 9.3.0 and c++17

A: The code shown is perfectly fine, AFAICS.  The warning implies that the vector's implementation is in the wrong, not you.  A vector::iterator can be incremented by an index, and your index variable is the same type that vector uses for its indexes.  So there should be no conversion.  But there is, because the difference_type of the iterator is not the same type as the size_type of the vector.
In any case, this kind of code is unnecessary anyway.  You could just use the Erase-Remove idiom via std::remove_if()+vector::erase(), or std::erase_if() in C++20. Then there would be no need to handle these kinds of loops and swaps manually at all.  For example:
vec.erase(
    std::remove_if(vec.begin, vec.end(),
        [](auto &elem){ return *magic_condition*; }
    ),
    vec.end()
);

std::erase_if(vec, [](auto &elem){ return *magic_condition*; });

void update(const delta_type delta) {
  handlers.erase(
    std::remove_if(handlers.begin(), handlers.end(),
      [&](auto &handler){ return (bool) handler.update(handler, delta); }
    ),
    handlers.end()
  );
}

void update(const delta_type delta) {
  std::erase_if(handlers, [&](auto &handler){ return (bool) handler.update(handler, delta); });
}


text:
Q: Custom cell not showing up in tableView I have a custom cell with identifyer 'tweetCell' I have imported this into my tableviewcontroller.h file. I have linked the class to the prototype cell in storyboard. All the UILabels are wired up to the cell but I cannot get the tableview to display the custom cell. It did work? Then overnight stopped?!! I understand that class files need to start with an upper case letter, I have changed this but to no avail. Can anyone spot my error here? Thanks in advance......
- (void)fetchTweets
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: @"http://search.twitter.com/search.json?q=%23mysearchhashtag"]];

        NSError* error;

        tweets = [NSJSONSerialization JSONObjectWithData:data
                                                 options:kNilOptions
                                                   error:&error];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tweets.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"tweetCell";

    customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];

    NSString *tweetText = [tweet valueForKey:@"text"];

    NSArray *tweetComponents = [tweetText componentsSeparatedByString:@":"];

    cell.firstDetail.text = [tweetComponents objectAtIndex:0];
    cell.secondDetail.text = [tweetComponents objectAtIndex:1];
    cell.thirdDetail.text = [tweetComponents objectAtIndex:2];

    return cell;
}

A: Did you write this method - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView? Try like this.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;

    }


text:
Q: How do I connect non-I2C devices to an I2C bus? I'm quite new to electronics and just trying to do my first Raspberry Pi based system: one diode, one pressure sensor and LCD 1602 with keypad shield (the one for an Arduino board). The way I'd like to connect all the devices is using I2C (the Raspberry Pi doesn't have much GPIO).
And here  comes the question: How can I possibly connect non-I2C devices to the I2C bus? I heard about different expanders, like the MCP23017, will that solve the problem?

A: It is possible that the question represents a misunderstanding or miscommunication of the kind of connection desired: Not something to be connected to the I2C bus itself, but to be controlled via some intermediary I2C to GPIO device, which further is connected on the I2C bus.
The idea of non-I2C devices being connected to an I2C bus is meaningless. The I2C protocol has specific requirements, for the I2C master to address the slave device, and for communicating data in either direction.
The LCD mentioned in the question, for instance, works on a different set of communication protocols, using multiple GPIO pins, and (from the description) most likely does not recognize I2C. There are however I2C LCD modules available, which incorporate I2C slave functionality on board - either through an LCD controller or a dedicated microcontroller with I2C slave communication code. Instead of the basic LCD module mentioned, such an I2C display module would be required for use on an I2C bus.
I2C bus expanders cannot magically create I2C functionality on a connected device. What I2C bus expanders can do, however, is provide additional GPIO pins, which are then controlled by code from the Raspberry Pi or microcontroller through the expander, which itself responds to I2C commands.
Perhaps that is what is desired - in which case, sure, it will work but not as described: A GPIO-driven device such as the LCD module or an LED can be wired up to the expander's GPIO pins, and the expander is the device that is connected to the I2C bus.


text:
Q: Windows Mobile debug on Visual Studio 2008 shows "Operation could not be completed" and "Default output location on device" empty list in Device Tools When I want to debug a Mobile Application with Visual Studio 2008. It shows "Operation could not be completed" and do nothing more.
After a little search, I noticed that the list of "Default output location on device" in Options > Tool > Device tools > Devices > Properties and this, for all the devices.

Does anyone know how to solve that problem?
Thank you in advance.

A: The solution for me was to reinstall VS 2008. Please take a look at my comment below the root question.


text:
Q: remove the duplicate entry for the value in laravel view file I have the response from the data as $am_details and I want to get the unique geo value in sect box dropdown  in view files
I have tries as
<select name="geo" class="ui fluid dropdown" id="geo" multiple="" >
    @foreach($am_details as $summary)
        <option value="{{$summary->Geography}}">{{$summary->Geography}}</option>
    @endforeach
</select>

But displaying with duplicate geo value I want to remove the duplicate entry in laravel view selectbx option.
$am_details response in as below
Array ( [0] => stdClass Object ( [AccountManager] => jigar.lohia  [CustomerCode] => UAE_0068 [Geography] => ME  )
 [1] => stdClass Object ( [AccountManager] => jigar.lohia  [CustomerCode] => UAE_0068 [Geography] => ME )
 [2] => stdClass Object ( [AccountManager] => jigar.lohia [CustomerCode] => UAE_0068 [Geography] => ME )
 )

A:
In controller

$unique = $am_detials->unique();

Then u give unique data. Check the documenting
https://laravel.com/docs/master/collections#method-unique

A: You should set your geography field as unique in your migration.
$table->string('geography')->unique();

A: Try groupBy() in your controller.
For example:
$am_details = Model::groupBy('geo')->get();

It will group all the duplicates


text:
Q: Inline assembler execution time I would like to know how to count execution time of c++ inline assembler?
My problem is that the difference of Tickcounts is 0.
Here is my cpp code:
const int N = 100000;
short x[4*N];

short a[4*N];
    for (int j=0;j<4*N;j++) {
        x[j] = rand() % 1000;
        a[j] = rand() % 5000;
    }
DWORD dwAStart = GetTickCount();

__asm {

    xor eax,eax

        mov ecx,N
    xor esi,esi

a1:
        emms
    movq        mm1,qword ptr x[esi]
    movq        mm2,mm1
    punpcklwd   mm1,mm6
    punpckhwd   mm2,mm6
    movq        mm0,qword ptr a[esi]
    movq        mm3,mm0
    punpcklwd   mm0,mm6
    punpckhwd   mm3,mm6
    pmullw      mm0,mm1

    paddsw      mm0,mm3

    add esi , 8
    loop a1
};
DWORD dwAInterval = GetTickCount() - dwAStart;
printf("Operation is completed through %d ms (Assembler)!\n", (int)dwAInterval);

A: ticks, as counted by GetTickCount(), are too coarse to capture time differences from such short sequences of assembly code. You will have to use the x86 Time Stamp Counter to see the time; the instruction mnemonic is usually RDTSC in assembly. All caveats apply, such as: your process may get interrupted (this will invalidate the counts), the clock frequency may actually change, activity in other cores may affect the timing of your core, ....

A: As GregS points out, GetTickCount is far too coarse to use for timing short sequences of code.  And the Time Stamp Counter found on x86 processors has limitations that make it very unreliable on multi-core processors.  The most reliable solution is the QueryPerformanceCounter and QueryPerformanceFrequency functions.  On *nix platforms, the POSIX function clock_gettime() serves a similar purpose.

A: I used:

#include <iostream>
using namespace std;
typedef std::chrono::high_resolution_clock Clock;
int main()
{
  int X4,sum,avg;
  auto t1 = Clock::now();
  auto t2 = Clock::now();
  sum=avg=0;
  for( int i=0; i<TRIALS; i++ )
    {
      X4=17;
      t1 = Clock::now();
      asm  (
     "movl %0, %%eax;" // X->ax
     "movl $0x0A, %%ebx;" // 10->bx
     "mul %%ebx;" // 10*ax->ax
     : "=a" (X4)
     : "a" (X4)
     : "%ebx"
     );
      t2 = Clock::now();
      sum+=chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
    }
  avg=sum/TRIALS;
  cout << "| Product:  " << X4<< "  "<< avg << " nanoseconds |" << endl;
}


text:
Q: Apache won't redirect HTTP to HTTPS When I enter my website's non-SSL URL "cms00.example.com" into my browser, it won't redirect to https://cms00.example.com.  If I enter the HTTP address, I can see the site and if I enter the HTTPS address, I can see the site.  I just can't get the redirect from http to https to work.  I've read numerous articles on how to do this and tried all the suggestions but my configuration still isn't working.  I'm running Apache 2.4.10 on Debian 8, and this is my first time working with Apache.
I've run these two commands and verifed that the rewrite and ssl modules have been loaded:
sudo a2emod rewrite   # <- already enabled
sudo a2emod ssl       # <- already enabled

I haven't made any modifications to /etc/apache2/apache2.conf and I haven't created any additional .htaccess files.
Here is my configuration file:
# /etc/apache2/sites-available/vhosts.conf
DirectoryIndex index.php index.html

<VirtualHost *:80>
  ServerName cms00.example.com
  DocumentRoot "/var/www/html"
  Redirect permanent / https://cms00.example.com
</VirtualHost>

<VirtualHost *:443>
  ServerName cms00.example.com
  DocumentRoot "/var/www/html"

  SSLEngine on
  SSLCipherSuite AES256+EECDH:AES256+EDH
  SSLProtocol All -SSLv2 -SSLv3
  SSLHonorCipherOrder On
  SSLCompression off
  SSLCertificateFile /etc/apache2/ssl/example.com.crt
  SSLCertificateKeyFile /etc/apache2/ssl/private/example.com.key

  <Directory "/var/www/html">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
  </Directory>
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

A: I've solved the problem.  Here's what's going on.  /etc/apache2/apache2.conf includes a call to any config files that have symlinks in /etc/apache2/sites-enabled.  Since there was a symlink in that directory pointing to /etc/apache2/sites-available/000-default.conf, that latter config file was being loaded and it was over-riding the blocks and directives in my vhosts.conf file.  Once I deleted that symlink, my vhosts.conf settings were able to take effect.  The lesson for me was that any file that has a symlink in sites-enabled will be enabled.


text:
Q: get active window of other programs using java I am trying to make a Java application that can get the information from other active window program such as information bar, or even screenshot of other active window.
Is JNI the only option in this case?
Thanks.

A: These things are not possible using pure Java.
Your options are using native libraries via JNI / JNI, or calling some external application using Runtime.exec(...).

A: Getting information about other items withing the Operating System needs to be done with OS Specific means. You might be able to launch some scripts from inside your program and get some info be reading the output of those scripts ?
Otherwise JNI is the way to go. The whole idea behind Java is to be platform independent, this is accomplished by hiding the OS.
Screenshots are possible
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class RobotExp {

    public static void main(String[] args) {

        try {

            Robot robot = new Robot();
            // Capture the screen shot of the area of the screen defined by the rectangle
            BufferedImage bi=robot.createScreenCapture(new Rectangle(100,100));
            ImageIO.write(bi, "jpg", new File("C:/imageTest.jpg"));

        } catch (AWTException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

A: You can use the following code and able to retrieve the screenshot of the activated window.
Furthermore,
To capture the better-cropped image of the window, please adjust the following variables as your need
private static int adjustLeft = 6;
private static int fineCutterX = 6;
private static int fineCutterY = 6;

public void getActiveWindowImage() {
    char[] buffer = new char[MAX_TITLE_LENGTH * 2];
    HWND hwnd = User32.INSTANCE.GetForegroundWindow();
    User32.INSTANCE.GetWindowText(hwnd, buffer, MAX_TITLE_LENGTH);
    System.out.println("Active window title: " + Native.toString(buffer));
    RECT rect = new RECT();
    User32.INSTANCE.GetWindowRect(hwnd, rect);
    int x = rect.left + adgustLeft;
    int y = rect.top;
    int width = rect.right - x - fineCutterX;
    int hieght = rect.bottom - y - fineCutterY;
    System.out.println(x + "," + y + "," + width + "," + hieght);
    System.out.println("rect = " + rect);

    Robot robot = null;
    try {
        robot = new Robot();
    } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // Capture the screen shot of the area of the screen defined by the rectangle
    BufferedImage bi = robot.createScreenCapture(new Rectangle(x, y, width, hieght));
    try {
        ImageIO.write(bi, "jpg", new File("<File Path you need to save>"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


text:
Q: Need help searching if a line in a csv file contains a word I am writing some code. I would like to have an if statement that if a row in the CSV file contains what you input (a single word) then it does something.
I have tried doing if row = input then do this but it doesn't work as the whole row does not = the input only part of it does.
for row in reader:
    if row == input1:
        # Whatever I want

It does nothing, as the entire row does not equal input1.

A: You could use if input1 in row:

A: You can use
if row[0]==input1:

This will check if the first element in the row is equal to input1.

A: Maybe something like the following.
with open('country.csv', 'r', encoding="utf-8") as myfile:
    data=myfile.readlines()

for line in data:
    if "Switzerland" in line:
        print(line)


text:
Q: User mapping lost after manual failover I have two Microsoft SQL Server instances set up for mirroring each with a number of databases. There are a number of logins and for each database one or more user/login mappings.
When I restore a backup of database I always have to redo the login/user mappings. I understand this because the logins are per database server. So after restoring the databases on the pricipal I redid the login/user mappings. This was not possible for the mirror because the databases were 'restoring'.
After a manual failover I could not use the databases because user credentials were missing. This was not unexpected, so I did the login/user mapping again.
I did a manual failover again to make the initial pricipal, which was now the mirror, principal again. To my surprise I could not use the databases because the login/user mappings were gone.
Is this the expected behaviour?

A: Are these SQL logins?  If so, then chances are that the mapping between SQL logins and database users is out-of-sync between the principal and mirror.
I've had issues with this myself in the past though I've been lucky enough that I only ever cared about one specific user.
You should try the following function on the mirror:
EXEC sp_change_users_login 'update_one', @login, @login

To reset the mapping between login @login and database user @login.
If this doesn't work, try the 'Auto_fix' approach:
EXEC sp_change_users_login 'Auto_Fix', @login, NULL, @password

This should create the database user and map it accordingly if it doesn't already exist.
This happens with SQL logins because the the database server will generate SIDs for these logins.  These SIDs are what tie a database user to a login.  Even though the same login may exist on two different servers, their SIDs may be different, and thus you experience "lost" credentials, if you will.  This does not happen for windows accounts, because SQL Server will use the Windows SID of the account itself when creating the associated login.

A: On my DBs I usually use these commands:
EXEC sp_change_users_login 'Report'
EXEC sp_change_users_login 'Auto_Fix', 'username'
EXEC sp_change_users_login 'Report'

where username is the user name you want to fix.

A: Running sp_change_users_login is fine as a work-around, but I like to fix this (common) problem with the following steps:

*

*Identify the SQL Server logins that you are having trouble with. You should be able to ignore domain logins. It would be best to ignore any SQL Server logins that you app does not use, the best example being "sa".

*Choose a server that will be your "known good" system. The current primary is probably the best choice.

*Use sp_help_revlogin to reverse engineer (from the primary) a TSQL script to create the problematic logins. sp_help_revlogin is maintained by Microsoft at this page. When run on the secondary, the TSQL script will preserve the "SID" that SQL Server uses to identify logins and link them to the users in each database.

*On the secondary, drop the problematic login and run the TSQL script you generated. When the login is recreated, it's SID will match that of the primary server. The next time you fail over or restore a database from the primary to the secondary, the SIDs should match and you should not have to run the sp_change_users_login procedure to 'fix things'.
Until you are familiar with this process, it's best to do one login at a time.
Be wary: Running that TSQL script will also sync the password on the secondary with that of the primary. If you have different passwords on the two servers (maybe one is a development server and one is a production server), you may have to go back in change the password on the secondary back to whatever it is supposed to be. If you don't know what those passwords are, or can't get someone to tell you, this can be a problem.

*After running the script on the secondary, you should double check any databases on the secondary that are not part of your app and fix the user-to-login mapping in those. For example, perhaps you have AdventureWorks on that system. When you drop the login, the user-to-login mapping will be broken and will have to be recreated.


text:
Q: Proving two norms are not equivalent. Counterexamples. $V = C([0,1])$, $||f||_{\infty} = max |f(x)|$, $||f||_{*} = max |xf(x)|$. $V = C([0,1])$, $||f||_{\infty} = max |f(x)|$, $||f||_{*} = max |xf(x)|$.
The question asks: if the two norms are equivalent? And if not, why?
How do I deduce whether the two norms are equivalent or not? And if not, how do I go about constructing a counterexample? I'm more interested in the thought process when trying to construct counterexamples rather than the actual counterexamples themselves as I often find it difficult to come up with them on my own.
Thanks!


text:
Q: How do I get a tooltip on hovering over an SVG circle I'm trying to get a tooltip while hovering over my svg nodes on d3. I have tried different ways to code it but it doesn't seem to be working. I'm also a little confused since I have already used the mouseover function for highlighting the circles. I've added a snippet from my code here
var tooltip = d3.select("body")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden")
    .style("background", "white")
    .text("a simple tooltip");

var svg = d3.select('body').append('svg')
  .attr('height',h)
  .attr('width',w)

var circles = svg.selectAll('circle')
    .data(data.nodes)
    .enter()
  .append('circle')
    .attr('cx', function (d) { return d.x })
    .attr('cy', function (d) { return d.y })
    .attr('r', function (d) { return d.amount/50 })
    .attr('fill', function (d) { return "blue" })
    .attr('stroke','yellow')
    .attr('stroke-width',0)
      .on('mouseover',function() {
        d3.select(this)
          .transition()
          .duration(1000)
          .attr('stroke-width',5)
          .attr('opacity',1)
          svg.selectAll('circle')
          .attr('opacity',0);
          svg.selectAll('line')
          .attr('opacity',0)
      })

      .on('mouseout',function () {
        d3.select(this)
          .transition()
          .duration(1000)
          .attr('stroke-width',0)
          svg.selectAll("circle") .attr("opacity", 1)
          svg.selectAll('line')
          .attr('opacity',1)
      })

d3.select("body")
    .selectAll('div')
          .on("mouseover", function(d){tooltip.text(d); return tooltip.style("visibility", "visible");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})

A: Here's one I made earlier ;) The tooltip style in this instance is defined in css (saves defining it in javascript!) Here's a fiddle (The graph shows a rectangle with multiple circles, each one showing a tooltip on hover)

var width = 1000;
var height = 500;
var range = 100;
var cntPoints = 50;
var padding = {
  x: 50,
  y: 20
};

var points = d3.range(cntPoints).map(function() {
  return [Math.random() * range, Math.random() * range, Math.random() * 5];
})
var scaleX = d3.scale.linear().domain([0, range]).range([0, width - 20]);
var scaleY = d3.scale.linear().domain([0, range]).range([height - padding.y, 0]);
var scaleColor = d3.scale.linear().domain([0, 5]).range(["red", "green"]);

var axisX = d3.svg.axis();
axisX.scale(scaleX).orient('bottom');

var axisY = d3.svg.axis()
  .scale(scaleY)
  .orient('left')
  .ticks(3);

var drag = d3.behavior.drag()
  .on("dragstart", dragstarted)
  .on("drag", dragged)
  .on("dragend", dragended);

svg = d3.select('body')
  .append('svg')
  .attr('width', width)
  .attr('height', height)
  .style('padding-top', padding.y)
  .style('padding-left', padding.x);

svg.append("clipPath")
  .attr("id", "chart-area")
  .append("rect")
  .attr("x", 0)
  .attr("y", 0)
  .attr("width", width)
  .attr("height", height - padding.y);

rect = svg
  .append('rect')
  .attr('width', width)
  .attr('height', height)
  .attr('class', 'invisible')
  .on('click', function() {
    svg.selectAll('circle[fill="blue"]')
      .transition()
      .delay(function(d, i) {
        return i * 300;
      })
      .duration(1000)
      .attr('cx', function(d) {
        return scaleX(d[0]);
      })
      .attr('cy', function(d) {
        return scaleY(d[1]);
      })
      .attr('fill', function(d) {
        return scaleColor(d[2]);
      })

  });

svg.append('g')
  .attr('class', 'axis')
  .attr('transform', 'translate(0, ' + (height - padding.y) + ')')
  .call(axisX);

svg.append('g')
  .attr('class', 'axis')
  .call(axisY);

circles = svg
  .append('g')
  .attr('id', 'main-container')
  .attr('clip-path', 'url(#chart-area)')
  .selectAll('circle')
  .data(points)
  .enter()
  .append('circle')
  .attr('r', 14)
  .attr('cx', function(d) {
    return scaleX(d[0]);
  })
  .attr('cy', function(d) {
    return scaleY(d[1]);
  })
  .attr('fill', function(d) {
    return scaleColor(d[2]);
  })
  .attr("fill-opacity", 0.5)
  .attr("stroke-opacity", 0.8)
  .call(drag);

circles
  .on('mouseover', function(d) {
    coordinates = d3.mouse(this);

    d3.select("#tooltip")
      .style("left", coordinates[0] + padding.x + "px")
      .style("top", coordinates[1] + padding.y + "px")
      .select("#info")
      .text(tooltipText(d));

    d3.select("#tooltip").classed("hidden", false);
  })
  .on("mouseout", function() {
    d3.select("#tooltip").classed("hidden", true);
  })

function dragstarted(d) {
  d3.event.sourceEvent.stopPropagation();
  d3.select(this).classed("dragging", true);
}

function dragged(d) {
  d3.select(this)
    .attr("cx", d.x = d3.event.x)
    .attr("cy", d.y = d3.event.y);
}

function dragended(d) {
  d3.select(this).classed("dragging", false).attr('fill', 'blue');
}

function tooltipText(d) {
  return 'Color base: ' + Math.round(d[2] * 100) / 100 + ', Position: ' + Math.round(d[0] * 100) / 100 + ';' + Math.round(d[1] * 100) / 100;
}
#tooltip {
  position: absolute;
  width: 200px;
  height: auto;
  padding: 10px;
  background-color: rgba(128, 128, 128, 0.4);
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  -webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
  -moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
  box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
  pointer-events: none;
}

Circle information

Hope this helps


text:
Q: cURL error 35: SSL connect error with wp_remote_get() in third party API call not working I am working on gravity form add-on for our CRM product in wordpress. I have used following code. I don't know why this response is occurring and tried a lot but no getting any hope for it. So, Please look at following output.
CODE
<?php

$request = array(
    'headers' => $headers,
    'method'  => $method,
        'sslverify'=>false,
        'httpversion'=>'1.0',
        'AppAccessKey'=>'MyAccessKey ',
        'AppPrivateKey'=>'MyPrivateKey',
        'sessiontoken'=>'Mysessiontoken'
);

$response = wp_remote_get($apiUrl, $request );

print_r($response);

?>

But i m getting following OUTPUT in response.
OUTPUT
WP_Error Object
(
    [errors] => Array
        (
            [http_request_failed] => Array
                (
                    [0] => cURL error 35: SSL connect error
                )

        )

    [error_data] => Array
        (
        )

)


text:
Q: How to inject a zero-noise signal compact binary coalescence signal Is it possible to inject a signal by itself with no coloured Gaussian noise?
Question asked by Arunava Mukherjee via email

A: Yes. There are two easy ways to do this.
1) Use the existing helper functions
When generating an interferometer object, bilby provides several helper routines denoted by bilby.gw.detector.get_interferometer_with.... In this case, you'll want to use this function (I've truncated the doctring)
bilby.gw.detector.get_interferometer_with_fake_noise_and_injection(
    name, injection_parameters, injection_polarizations=None,
    waveform_generator=None, sampling_frequency=4096, duration=4,
    start_time=None, outdir='outdir', label=None, plot=True, save=True,
    zero_noise=False)
Docstring:
Helper function to obtain an Interferometer instance with appropriate
power spectral density and data, given an center_time.

Note: by default this generates an Interferometer with a power spectral
density based on advanced LIGO.

Parameters
----------
    name: str
        Detector name, e.g., 'H1'.

...

    zero_noise: bool
        If true, set noise to zero.

So you just pass the flag in and it will create an interferometer with just the injection signal (you'll then need to make one for each interferometer you want in the list of interferometers passed in to the likelihood.
2) Use the low level set strain data methods
Alternatively, you may instead wish to use the low level methods themselves. As a general rule of thumb, you can always look at the source code for the generic helper functions to figure out how this should be done. Here, we create a H1 interferometer set the strain data with zero noise and inject a signal:

interferometer = get_empty_interferometer("H1")
interferometer.power_spectral_density = PowerSpectralDensity.from_aligo()

interferometer.set_strain_data_from_zero_noise(
    sampling_frequency=sampling_frequency, duration=duration,
    start_time=start_time)

injection_polarizations = interferometer.inject_signal(
    parameters=injection_parameters,
    waveform_generator=waveform_generator)

Information correct as of v.0.3.5


text:
Q: Where can I find ServerResponse object's properties in node.js? Recently I am following the book Node.js In Action,
In chapter 9 there is a message module, and the following is a function in this module,
I am very confused about what 'this' object is when the res.message is get called,
so I print out 'this' object's name
//in lib/messages.js

var express = require('express');
 var res = express.response;
 console.log(res.constructor.name); //ServerResponse
res.message = function (msg, type){
  var sess = this.req.session;  //what will be the this object?
  console.log(this.constructor.name); //ServerResponse
  console.log(this.req.constructor.name); //IncomingMessage

  ...
}

When the message module is called in app.js,
It seems that 'this' is a ServerResponse object, but I checked node.js manual, I can't find that the ServerResponse object has its own 'req' property, so it must be its prototype's property then.
My question is, how do I know 'ServerResponse' has a 'req' property so I can use it?

A: Express takes the ServerResponse and adds extra data, which is where the .req attribute comes from.  If, in general, you want to check if an object has an attribute in node.js, you can just do:
if (obj.attribute !== undefined) { ... do stuff ... }


text:
Q: How to find out where performance of an ASP.NET 1.1 webserver leaks to (outside of page renderings) I got a problem with a system running on ASP.NET 1.1. It's a topic right now, but actually it's a recurring issue: Sometimes, the system will become extremely slow, and I wonder if there's a tool to find out what's going on. I know that sounds vague, but that's exactly what my problem is about.
The thing is, I can time of course my scripts as soon as the page has started loading. However, the issues seem to take place before the page code starts - the delay is in the start of processing the page. This renders me blind with respect to coding anything to detect what's going on.
So, can someone help me out with an idea of how to track system resources independently of page calls being served? As I'm writing this, I realize I don't even know which resources I'm looking for exactly, so any info on that would be great, too!
Some background info:

*

*System is live 500-1000 unique visitors per day and around 5000 hits on the main (database-heavy) website

*Performance drops seem to occur independently of traffic

*As said, system is running on ASP.NET 1.1. Upgrading may be an option, but any info on whether such issues can be expected to improve with such an upgrade would be greatly appreciated (I'm aware it's hard to tell what the issue is, so this is more of a side question)

*System has an Access backend for historic reasons. I know this can be a problem, but again, the question would be, how can I quantify that if the delay isn't coming from the actual queries?

A: There are tools for profiling ASP.NET applications, however, I doubt they still support .NET 1.1. See Profiling tools for .NET for a list - maybe one of them still has a version that supports .NET 1.1.


text:
Q: Scroll Snap animation not working on safari & mozilla I am trying to implement a Carousel with only CSS (scroll-snap-align methods).
This is my code : https://codepen.io/kushul/pen/NWRjZLq?editors=1100
Parts of the code:
@keyframes snap {
  96% {
    scroll-snap-align: center;
  }
  97% {
    scroll-snap-align: none;
  }
  99% {
    scroll-snap-align: none;
  }
  100% {
    scroll-snap-align: center;
  }
}

@media (hover: hover) {
  carousel__snapper {
    animation-name: tonext, snap;
    animation-timing-function: ease;
    animation-duration: 4s;
    animation-iteration-count: infinite;
  }

  .carousel__slide:last-child .carousel__snapper {
    animation-name: tostart, snap;
  }
}

This has been implemented from this example : https://css-tricks.com/css-only-carousel/
It's working fine on Chrome but not working on Safari & Mozilla.
Can you please help me to fix this issue?
Thanks.


text:
Q: Does the inverse of a infinitely many times differentiable transition map also infinitely many times differentiable? If a transition map between two charts is infinitely many times differentiable, then is it true that its inverse is also infinitely many times differentiable?
My intuition is that it's true, but I have no idea how to prove it.
If it is not true, can anyone give me a counterexample?
Any help will be appreciated, thanks!

A: Without further assumptions, it's not true. For example, here are two charts for $\mathbb R$: the maps $\phi,\psi$ both have domain $\mathbb R$ and codomain $\mathbb R$, and they are given by the formulas
$$
\phi(x) = x, \qquad \psi(x) = x^3.
$$
(Note that both are homeomorphisms from $\mathbb R$ to $\mathbb R$.)
The transition map $\psi\circ\phi^{-1}$ is $x\mapsto x^3$, which is infinitely differentiable. But the inverse is $x\mapsto x^{1/3}$, which is not even once differentiable at the origin.
What's true is that if the transition map is infinitely differentiable and has nonsingular differential everywhere, then its inverse is infinitely differentiable. (The existence of the first derivative follows from the inverse function theorem, and the existence of higher derivatives from the chain rule and induction.)
Alternatively, you can assume that the transition map is infinitely differentiable and its inverse is once differentiable everywhere, and then the existence of higher derivatives follows as above from the chain rule.


text:
Q: Which functions are continuous but nowhere Holder continuous for 0Can somebody provide an example of a function that is continuous on [0,1] but nowhere Holder continuous with degree $\alpha$? Why is the function continuous but nowhere Holder continuous?
By nowhere Holder continuous, I mean that
$\frac{|f(x + t_n) - f(x)|}{|t_n|^\alpha} \rightarrow +\infty$ where $t_n$ is a sequence which $\rightarrow 0 $ as $n\rightarrow +\infty$.

A: I'll denote $C([0,1])$ by $C.$ For $j,k,l \in \mathbb N,$ let $E_{jkl}$ denote the set of functions $f\in C$ for which there exists $a\in [0,1]$ such that $|f(x)-f(a)| \le j|x-a|^{1/k}$ in the neighborhood $(a-1/l,(a+1/l) \cap [0,1].$
Claim: Each $E_{jkl}$ is closed and nowhere dense in $C.$
If the claim is proved, then because $C$ is a complete metric space, Baire shows there are functions $g\in C$ that belong to no $E_{jkl}.$ For any such $g,$ the following is true: If $\alpha> 0,$ $a\in [0,1],$ $C>0,$ and $U$ is a neighborhood of $a$ relative to $[0,1],$ then
$$|g(x)- g(a)| \le C|x-a|^\alpha$$
fails to hold for some $x\in U.$ This $g$ is thus "nowhere Holder" in a very strong sense. (You never defined "nowhere Holder", btw.)
So you have the claim left to verify.


text:
Q: Swift: JSONDecoder + Codable I have three classes whom I want to parse from json which I receive from a server. the json structure is currenct.
those classes are:
public class HmoModel: Codable {
    private var Id: Int
    private var Name: String
}

public class SplashModel: Codable {
    public var Hmos: [HmoModel]!
}

public class PatientSplashModel: SplashModel {
    public var StressorsAnswers: [StressorsAnswerModel]!
}

I'm trying to parse a json this way:
do {
    let patientSplash = try self.decoder.decode(PatientSplashModel.self, from: response.data)
} catch {
    listener.onException(error)
}

but in patientSplash everything is nil.
I'm receiving the json using SwiftHTTP like this
HTTP.GET(ServerPatientApi.SPLASH, parameters: nil) { response in
            if let error = response.error {
                listener.onException(error)
                return;
            }

            DispatchQueue.main.async (execute: {
                do {
                    listener.onSplashLoaded(try self.decoder.decode(PatientSplashModel.self, from: response.data))
                } catch {
                    listener.onException(error)
                }
            })
        }

How to fix it? Hot to make a decoder parse json?
Thanks!

A: please add Codingkeys enum to your codable classes so codable could get objects by key for example
public class HmoModel: Codable {
    private var Id: Int
    private var Name: String
    private enum CodingKeys: String, CodingKey {
       case Id="id"
       case Name="name"
    }
}


text:
Q: how to add rules to ESLint in Create React App I can't add rules or edit ESLint in a Create React App.
before version  4.0. all was ok- i had .eslintrc.js file with rules.
i moved to 4.0.2 and - the app stopped compiling. so i removed .eslintrc.js, and got completion back.
ok.
but now, i can't add or edit anything regarding ESLlint.
i can't add a new .eslintrc.js, use the old one, or config the lint in the package.json file like the documentation solution - all returning to completion problem.
tried to add .env file with ESLINT_NO_DEV_ERRORS=true but still the same problem.
how can you extend or Edit ESLint ?

A: one solution is to use to edit the rules in the package.json :
for example :
  "eslintConfig": {
    "extends": ["react-app"],
    "rules": {
      "no-unused-vars": "warn"
    },
    "overrides": [
      {
        "files": ["**/*.ts?(x)"],
        "rules": {
          "max-len": "warn"
        }
      }
    ]
  },


text:
Q: Can a manifold be reconstructed from its charts? I'm learning special relativity and I am having a confusion on this mathematical point. Whenever any sort of motion or non motion happens in the world, it can only be perceived by the scientist in a chart (inertial frame). But, we say there exists a common manifold which is being charted by different observers when doing observation.
How can one from just seeing the charts with transition maps and metric (spacetime - metric) know the existence of a manifold?
In a more simplistic sense, could I reconstruct how the earth sits in space just from seeing pages the world map (with marked distances)?

A: Here are some thoughts on mathematical aspects of the question:
Can a smooth manifold be reconstructed from a collection of charts?
YES
Assume you're given open sets $U_k\subset\mathbb{R}^d$ $(k=1,\dots, N)$ (think: pages in an atlas of the earth) and diffeomorphisms $\psi_{kl}\colon \operatorname{Domain}(\psi_{kl})\supset U_k\rightarrow U_l$ satisfying the obvious consistency condition (think: you keep track of certain locations on the earth appearing on different pages of the atlas). Then you can build from this a space $X=\coprod U_k/\sim$ by gluing the sets $U_k$ along the overlaps (think: you tear out the pages of the atlas and glue them together such the overlaps match up).  Then there's a natural way to turn $X$ into a smooth manifold.
For any smooth manifold $X$ one could first consider an atlas (in the geometry sense), which gives rise to chart domains $U_k$ and transition functions $\psi_{kl}$ as above and then the preceding construction again yields $X$ (think: if you follow the instructions from above for an actual atlas of the earth, say with strechable paper such that you can nicely glue everything, then you end up with a sphere)
Can a Riemannian manifold be reconstructed from a collection of charts and marked distances?
YES
Say in the setting above each chart domain $U_k$ comes with a distance function $d_k\colon U_k\times U_k\rightarrow [0,\infty)$, again being compatible with each other (think: the distance between Paris and London is the same no matter on which page of the atlas you measure it). Then on $X$ you get a function $d\colon \mathcal{D}\subset X\times X\rightarrow [0,\infty)$, defined on some neighbourhood $\mathcal D$ of the diagonal in $X\times X$ such that $d(x,y)=d_k(x,y)$ if $x,y\in U_k.
$

*

*Can $d$ be extended to all of $X\times X$? (think: there might be no page in the atlas in which you can measure the distance between Paris and Tokyo - can you still compute how far they are away from each other?) If you're able to comptue $d$ for points that are close to each other, you can define the length of a curve in $X$ (by marking $M$ points, very close to each other, adding up their distances and then taking the limit $M\rightarrow \infty$). If you can measure lenghts of curves, then you can measure the distance between any two points $x,y\in X$ by taking the infimum over the length of all curves between $x$ and $y$. This should give a metric $d^*$ on $X$ and if the metrics $d_k$ you started with were reasonable nice, it should be true  that $d^*=d$ whenever the latter was already defined. Checking these claims should be possible after reading a bit about length spaces.

*Next, if the original manifold $X$ that was mapped out in the atlas came with a Riemannian metric $g$, is it possible to recover this from $d$? (think: if you do this, then you can not only compute distance but also other intrinsic metric quantities, like the Gaussian curvature of the earth) The answer to this is yes, see here.
Can we reconstruct how the earth sits in space?
This question is of course a bit vague -- with the data available in a common atlas and specified above ($U_k,\psi_{kl},d_k$) -- the answer is no. From a mathematical point of view this is just saying that you only get the intrinsic geometry but no extrinsic features that depend on the precise embedding of $(X,g)$ in an ambient manifold. But for the earth this should be obvious -- after all, by looking at an atlas, how would you figure out the distance to the sun?
One reasonable question would be the following: Assume we are not given the intrinsic distances $d_k$, but the extrinsic distances $\tilde d_k$ (think:  the direct line by going through the earth) - can we determine some geometric features beyond what is said above? This is related to the famous boundary rigidity problem, see e.g. here. Having this data and using the (very recent) theorem from the previous link, one could e.g. say that in a $3$-dimensional layer below the earth's surface the space has zero curvature.

A: It may depend on your philosophical standing, but most of us would probably agree that space-time is the manifold, regardless of whether any scientist has used a chart to measure anything. Charts came after the existence of the manifold.
In pure math, there are at least two different ways to define a manifold. One can start with a topological space, and then insists it has some nice properties including admitting a maximal family of compatible charts. We may also starts with a family of charts $U\subset\mathbb R^n$ and transition maps $\rho_{UV}$ that satisfy the compatibility property, then we glue the charts together and define the manifold to be $\bigsqcup U /\sim$ where $\sim$ is the equivalence relation induced by $\rho_{UV}$'s in the obvious way. The second approach seems closer to how science is developed from measurement, but the first approach is argubly better, for example, it's much harder to address Hausdorff-ness in the second definition. And from the point of view of algebraic geometry, the underlying topological space is essential and charts are just sections of the smooth function sheaf over the space. A chart/measure is just a function, a way to assgin numbers to events.
Put in another way, scientists use their local charts to understand the world around themselves. All the observers can patch together their charts to gain a global understanding, and the way they patch is to assume the world itself is a consistent manifold (whatever this means).
You have to be more specific about "how the earth sits in space" means, but basically if different observations are combined, we can recover the manifold through the second definition.

A: To my mind there are two ways to answer this question. From a mathematical point of view, a variety is a set with a set of maps which are bijections with open sets of $R^n$, subject to some conditions. So in principle, from the definition, we know what is the variety. From another point of view, we can also start from a set of charts and try to put two by two pieces together, as we do with road maps, or with an atlas. It is more intuitive, but it is not the usual definition.


text:
Q: Не отображаются картинки на странице JSP Добрый день, есть страничка test.jsp, в ней есть код html получающий картинку стандартным тегом:

Проблема в том, что если я использую любое другое изображение, то оно не отображается,

Изображения одинаковые по размеру и по расширению (png). В корень приложения кидать пробовал, не помогает.
    Сервер TomCat 9.0 IDE Eclipse (на всякий)
        В Web.xml есть строчки для png
    <mime-mapping>
            <extension>png</extension>
            <mime-type>image/png</mime-type>
    </mime-mapping>

A: Если кому вдруг поможет, проблема была в том что страничка не поддерживала цветовую гамму картинки, выход: Конвертировать цветовую гамму


text:
Q: How to keep updating and displaying excel information? I need to have a copy of a worksheet updated every time the original is modified.  The copy ws needs to be opened at all times so everyone can see when it is updated.  So far without working on the code to detect file modification yet, I am just working on being able to update the worksheet.  I have found two ways of doing it, they are below:
1) The first way is using openpyxl.  Doing it this way I think I will have to write data to Todolist2 first then open the file in the excel application.  Then when the original is modified, it will have to close excel before writing updated data back in. Then reopen it.  Below is what I have so far.  Using sleep(10) allows me the chance to update example.xlsx so as to simulate writing new data to Todolist2.  As long as i close Todolist2 after it writes update data to it, it's good, it will not throw permission denied.  (A) However it won't update new data after the first pass.  (B) Is there anyway to have the file open in excel so I can just keep writing updated data to it, instead of closing it out first (file does not need to be saved) ? (second way below allows me to do that).
import openpyxl as xl
from copy import copy
import time, os

path1 = 'C:\\example.xlsx'
path2 = 'C:\\Todolist2.xlsx'

wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]

wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.worksheets[0]

while True:
    for row in ws1:
        for cell in row:
            ws2[cell.coordinate].value = cell.value
            if cell.has_style:
                ws2[cell.coordinate].font = copy(cell.font)
                ws2[cell.coordinate].border = copy(cell.border)
                ws2[cell.coordinate].fill = copy(cell.fill)
                ws2[cell.coordinate].number_format =
                copy(cell.number_format)
                ws2[cell.coordinate].protection = copy(cell.protection)
                ws2[cell.coordinate].alignment = copy(cell.alignment)
    wb2.save(path2)
    os.startfile('C:\\Todolist2.xlsx')
    #I will need something here to close out excel to allow python to
    #write to it again, otherwise it will throw permission denied.
    time.sleep(10)     #during this time I will modify example.xlsx and
                       #save, so on the next go around it rewrites the
                       #new data to Todolist1.xlsx.  However, it does not
                       #update to Todolist2.

(2) The second way I'm trying to solve this is with win32com.  This allows me to keep Todolist2 open in excel in windows while it writes to it from example, example1, then example2.  But the problem is, it does not write on the activesheet, it keeps adding additional sheets.  So on this one, If I can find a way to keep rewriting over the active sheet in Todolist2 or after it adds the additional sheet, and I can delete an older sheet that would work too.  (A) whats the function to keep deleting an older sheet?
import time, os.path, os
from win32com.client import Dispatch

path1 = 'C:\\example.xlsx'
path2 = 'C:\\Todolist2.xlsx'
path3 = 'C:\\example2.xlsx'
path4 = 'C:\\example3.xlsx'

xl = Dispatch("Excel.Application")
xl.Visible = True

wb1= xl.Workbooks.Open(Filename=path1)
wb2= xl.Workbooks.Open(Filename=path2)

ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))

time.sleep(5)

wb3= xl.Workbooks.Open(Filename=path3)
ws3 = wb3.Worksheets(1)

ws2 = wb2.Worksheets(3)      #it seems by using (3) is the only way it
                             #allows me to delete one sheet before it
                             #adds another.
ws2.Delete()
ws3.Copy(Before=wb2.Worksheets(1))

time.sleep(5)

wb4= xl.Workbooks.Open(Filename=path4)
ws4 = wb4.Worksheets(1)

ws2.Delete()            #I got into trouble here, and throws error even
                        #though it does the delete and copy
ws4.Copy(Before=wb2.Worksheets(1))