Q:

Atmega 328 uart program: compiler error on undeclared variable on register name ending with "n"

I'm trying to get the atmega328 to communicate over serial port with my pc. I'm using hyperterminal to echo back the keyboard character entries. I'm using the max3232 chip to do the communicated with the computer.
When I try to compile it gives and error and says that the variables in this function are undeclared, but they aren't variables but data register assignments.
If I replace the 'n' char in the register assignments to a number it will compile and program but no info is displayed in hyperterminal.
What should the 'n' be set too?
My RX is on pin 2 and TX is on pin 3, if that helps. It is being programmed because I've done the blinky light programs.
unsigned char USARTReadChar( void )
{
   //Wait untill a data is available

   while(!(UCSRnA & (1<<RXCn)))
   {
      //Do nothing
   }

   //Now USART has got data from host
   //and is available is buffer

   return UDRn;
}

THE ENTIRE SOURCE CODE
#define FOSC 1843200 // Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1

//This function is used to initialize the USART
//at a given UBRR value
void USARTInit(unsigned int ubrr)
{

   //Set Baud rate

    UBRR0H = (ubrr>>8);
    UBRR0L = ubrr;

   //Enable The receiver and transmitter
 UCSR0B = (1<<RXEN0)|(1<<TXEN0);
 // Set fram format: 8data 2stopBit
 UCSR0C = (1<<USBS0)|(3<<UCSZ00);

}

//This function is used to read the available data
//from USART. This function will wait untill data is
//available.
unsigned char USARTReadChar( void )
{
   //Wait untill a data is available

   while(!(UCSR0A & (1<<RXC0)))
   {
      //Do nothing
   }

   //Now USART has got data from host
   //and is available is buffer

   return UDR0;
}

//This fuction writes the given "data" to
//the USART which then transmit it via TX line
void USARTWriteChar(unsigned char data)
{
   //Wait untill the transmitter is ready

   while(!(UCSR0A & (1<<UDRE0)))
   {
      //Do nothing
          PORTD ^= 1 << PINB2;

   }

   //Now write the data to USART buffer

   UDR0 = data;
}

int main(void)
{
DDRB |= 1 << PINB2;

   //Varriable Declaration
   char data;

   USARTInit(MYUBRR);

  //Loop forever

   while(1)
   {
      //Read data
       data = USARTReadChar();

      /* Now send the same data but but surround it in
      square bracket. For example if user sent 'a' our
      system will echo back '[a]'.

      */

      USARTWriteChar('[');
      USARTWriteChar(data);
      USARTWriteChar(']');

  }
}

A:

The 'n' is meant to be a placeholder for the actual UART peripheral that you want to use when discussing the set of registers associated with the UARTs.
So if you had two UARTs, you could read the status register from the first UART by replacing it with a '0' or the second UART with a '1' like: UCSR0A or UCSR1A - note that these two are #define'd for you in a register definition file.  Since we only use the UCSRnA convention for when we refer to these registers in discussion, it will not be #define'd to a register and thus using it in code will throw an error.  You can follow your #include statements to find where they are defined.  The register definition file and datasheet are usually two things that I have handy when working.
The ATmega328 only has one UART peripheral, but follows the same naming convention.  So you would replace it with a 0.  Regarding being able to read/write to a serial port - assuming that you have hooked up your MAX232 correctly, have you set your baud rate correctly on both the ATmega and the PC?  Post the rest of your UART initialization code if you want further help debugging that.
EDIT: Summary of follow-up comments.

Check your clock frequency and make sure it's correct when
calculating the baud register value
Ensure that both uC and PC have same UART settings (baud, parity, stop bits)
Try not to use random code samples that may or may not be valid for your hardware configuration.


Q:

How to telecontrol a program?

Is it possible to telecontrol a program that is running by using c#? How to do that?
I have to convert about 500 files to a specific file format by opening it -> converting -> saving. So I want to create an alogrythm that will do the work.
Thank you for your help.

A:

It seems to me that you are best using a scripting language for window automation. One of the most popular ones is AutoHotkey.
If you need to do in .NET you might want to look at the Windows Automation API coming with .NET 3.5.
Without knowing further details about the program that you want to automate it is not easy to give you more detailed advice.


Q:

TFS 2018 XAML build migration

I am currently upgrading our XAML build definitions to the new build system. Already squashed a few errors, but now I am at a point where I can no longer tell what could be wrong. We use PowerShell scripts for most of the build process, and although all required data is available on the server, I get the following error when running the build:

Does anyone have any idea what could cause that error? Or at least where I should check?
Thanks in advance.
EDIT:
The script prepares build configuration that can not be done by external tools and are specific to our project. The error happens on the line $teamProjectCollection =...
Function Get-BuildNumberFromUri() {
<#
.SYNOPSIS
    Reads the build number from the current TFS build ($Env:BUILD_BUILDURI)
.DESCRIPTION
Reads the build number from the current TFS build ($Env:BUILD_BUILDURI)
.NOTES
    May fail if $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI or $env:BUILD_BUILDURI
are not set
#>
[String] $CollectionUrl = "$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"
[String] $BuildUrl = "$env:BUILD_BUILDURI"
if (-not $CollectionUrl -or -not $BuildUrl) {
    return "0"
}
[void[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Build.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client")
$teamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($CollectionUrl)
$buildServer = $teamProjectCollection.GetService([Microsoft.TeamFoundation.Build.Client.IBuildServer])
$buildDetail = $buildServer.GetBuild($BuildUrl)
$buildNumber = $buildDetail.BuildNumber
return $buildNumber

}

A:

In previous versions of Team Foundation Server the Client Object Model was registered in the GAC and pre-loaded by the build agent when running XAML. In the new agent the build steps are independent of the client object model.
You have two options to locate the Client Object Model assemblies:

Ship the Client object model with the powershell scripts by referencing the Client Object Model Nuget package.

https://www.nuget.org/packages/Microsoft.TeamFoundationServer.Client
https://www.nuget.org/packages/Microsoft.TeamFoundationServer.ExtendedClient

Detect the location where Visual Studio is installed and loading the client object model from the Team Explorer extension folder. Examples can be found on the docs wiki.

There is also an easier, but officially unsupported option:

Do not use $(Agent.ServerOMDirectory). It is not safe for task authors to depend on the SDK bundled with the agent. Agent.ServerOMDirectory is a convenience variable that points to the latest SDK bundled with the agent. The SDK may have breaking interface changes between different versions. Depending on the latest version shipped with the agent will cause your task to be unreliable.

Getting at the buildnumber
There is a build variable being populated to set the build number in your script it can be referenced using $env:Build.BuildNumber.
To set the build number write a special statement to the console using
$value = "$($env:Build.BuildNumber)_US`
Write-Host "##vso[build.updatebuildnumber]$Value"

Alternatively you can use my Set Variable task from the  VSTS Variable Toolbox extension.


Q:

C++11 Android vector of pointers push_back doesn't work with libstdc++

The following code compiles fine when using STLPort:
std::vector<Engine::Screen::IOverlay*> Overlays;
auto TestOverlay=new Engine::Screen::Overlay();
Overlays.push_back(TestOverlay);

However when compiling with libstdc++ it's trying to use move constructor for some reason:
error : cannot bind 'Engine::Screen::IOverlay*' lvalue to 'Engine::Screen::IOverlay*&&' ...\android-ndk-r8\sources\cxx-stl\gnu-libstdc++\include\bits\move.h

This is a very basic example but this issue occurs through out the application for all local pointers when using push_back.
Error occurs in move.h:
template<typename _Tp>
inline typename std::remove_reference<_Tp>::type&&
move(_Tp&& __t)
{ return __t; }

Example 2 (Another basic test I wrote:)
class TestClass {};
auto TestInstance=new TestClass;
std::vector<TestClass*> TestVector;
TestVector.push_back(TestInstance);

I compiled with ndk r8: -std=c++11  -D__STDC_INT64__

A:

It seems there are two bugs in the compiler. First it incorrectly callspush_back(T&&) which then attempts to move the object, which is implemented incorrecty:
template<typename _Tp>
inline typename std::remove_reference<_Tp>::type&&
move(_Tp&& __t)
{ return __t; }

It should be implemented as:
template<class _Tp>
typename remove_reference<_Tp>::type&&
move(_Tp&& __t) noexcept //noexcept should be here!
{
  return static_cast<typename remove_reference<_Tp>::type&&>(__t);
}

which means your compiler is showing up two bugs in this context:

incorrect overload resolution, as it calls push_back(T&&).
incorrect implementation of std::move

which version of what compiler are you using?


Q:

At what electromagnetic frequency does the wavelength = the wave height?

At what frequency does the wavelength equal the height of the wave amplitude?
The wave height / amplitude the physical space the wave height occupy in space, similar to the wavelength. My assumption is that the wave height of the basic electromagnetic wave is fixed.

It is my understanding that, fixed amplitude in E.M. graph can be:

Pictures of the electromagnetic spectrum, shows that the amplitude is the same regardless of frequency. what is the amplitude used in these Pictures?
 The maximum photons emitted by single electron per second.
The minimum photons needed to make light wave ???.

Now, let's ignore the typical E.M. wave graph and only take the wavelength from it. As we know, the E.M. waves propagate from left to right or up to down as mentioned by annav down below and here. The next step is to calculate the length  of the up to down motion in physical space most likely it will be in Planck and compare it to the wavelength. At what frequency does the wavelength equal the length of the left to right \ up to down motion?
Follow up question: does the length of the up to down motion change with the frequency??

A:

The electromagnetic wave is not a wave on a medium, as water waves which are coherent variations in position of water molecules.
Electromagnetic waves are built up by photons in coherence , each photon having an energy h*nu where nu is the frequency of the wave that emerges from a large number of photons . ( to get an idea of how many look at my answer here) .
The photons, as quantum mechanical entities, are described by a wavefunction which is a solution of a quantized maxwell's equation. This wave function has information on the electric an magnetic fields that will be built up in the emergent classical wave.
The emergent classical electromagnetic wave

The electromagnetic waves that compose electromagnetic radiation can be imagined as a self-propagating transverse oscillating wave of electric and magnetic fields. This diagram shows a plane linearly polarized EMR wave propagating from left to right (X axis). The electric field is in a vertical plane (Z axis) and the magnetic field in a horizontal plane (Y axis). The electric and magnetic fields in EMR waves are always in phase and at 90 degrees to each other.

This is an instance in time
In the same link there is an animation that shows the propagation in time.

The equations for the electric and magnetic field are:

and to be consistent solutions of maxwell's equations:

The magnitude of the E and B fields, the E_m and B_m depends on the energy carried by the specific electromagnetic wave:
As you can see, the wavelength develops in space, but the height of the wave, as everybody has been trying to explain the comments, is not in units of length, but in units of the electric E field and the corresponding units of c*B field. Thus your question has no answer because it compares apples to oranges.
The connection is not simple even in water waves, whose height is in the units of space.


Q:

Pyside2 - qml returns an empty window

I am trying to use QML with pyside2 but am running in some issues.
I create a simple example to show the issue I am having.
I made a new qml project in Qt Design Studio and am trying to load the qml file in pyside2 but when I run the script, it returns an empty window.
I tried to move the qml at the same level as my main.py but am getting the same results.
my tree structure looks like this.

this is the content of my main.py
from PySide2.QtWidgets import QApplication
from PySide2.QtQuick import QQuickView
from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
import sys

path = 'qmlTest01/qmlTest01.qml'
app = QGuiApplication(sys.argv)
view = QQuickView()
url = QUrl.fromLocalFile(path)

view.setSource(url)
view.show()
app.exec_()

I am getting an empty window like this:

instead of this:

Thank you in advance.
I made a repo with this example:
https://bitbucket.org/aespid/tests/src

A:

Explanation:
Your project structure is as follows:
├── main.py
└── qmlTest01
    ├── imports
    │   ├── qmlTest01
    │   │   └── ...
    │   └── QtQuick
    │       └── ...
    ├── qmlTest01.qml
    ├── qmlTest01.qmlproject
    ├── qtquickcontrols2.conf
    └── Screen01.ui.qml

And in your imports you use:
import qmlTest01 1.0
// ...

but nowhere do you indicate where that library is, but in the case of the second image you must be running the .qmlproject from QtCreator that reads the following configuration:
/* File generated by Qt Creator */

import QmlProject 1.1

Project {
    mainFile: "qmlTest01.qml"

    /* ... */

    Files {
        filter: "qmldir"
        directory: "."
    }

    Environment {
        QT_QUICK_CONTROLS_CONF: "qtquickcontrols2.conf"
        QT_AUTO_SCREEN_SCALE_FACTOR: "1"
    }

    /* List of plugin directories passed to QML runtime */
    importPaths: [ "imports" ]

    /* Required for deployment */
    targetDirectory: "/opt/qmlTest01"
}
Where it is observed that indicates the route of the import of other modules.
Solution:
The solution is to set some environment variables with os.environ() and the path of the "imports" folder using addImportPath() of QQmlEngine:
import os
import sys

from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQuick import QQuickView

if __name__ == "__main__":

    current_dir = os.path.dirname(os.path.realpath(__file__))

    os.environ["QT_QUICK_CONTROLS_CONF"] = os.path.join(
        current_dir, "qmlTest01", "qtquickcontrols2.conf"
    )
    os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"

    app = QGuiApplication(sys.argv)
    view = QQuickView()
    import_path = os.path.join(current_dir, "qmlTest01", "imports")
    view.engine().addImportPath(import_path)

    filename = os.path.join(current_dir, "qmlTest01", "qmlTest01.qml")
    url = QUrl.fromLocalFile(filename)

    view.setSource(url)
    view.show()
    app.exec_()


Q:

Is there a good entry-level tutorial for SPM?

The title pretty much says it all.  I need to do some fMRI data analysis and I can't find any entry-level tutorials for Statistical Parameter Mapping (SPM).  I've looked at some of the videos on the official SPM website, but I find that videos are not the most effective way of learning a new computerized tool -- I'm in the market for reading.
Does anybody have a go-to reference that's a bit less verbose and a bit more crash-course-y than the official manual?

A:

The best way to learn is probably not by reading, but by doing. The SPM website contains a number of useful datasets with tutorials for various tasks.
I also find PowerPoint slides from lectures and talks useful. There are a bunch of slides on the SPM website, but you can also find more on Google by limiting your results to type:pptx.


Q:

MySQL Query to join three table and get data from 2nd and 3rd table

I HAVE 3 TABLES :
Table1: Table Name: FULL_DATA
DATE        ORDER_NO               AMOUNT   MODE
01-04-2019  ADVANVCE.:ORD1971718    5000    DEBIT-CARD
01-04-2019  ADVANVCE.:ORD1961718    6000    CASH
01-04-2019  ADVANVCE.:ORD2001819    8000    CASH
02-04-2019  ADVANVCE.:ORD2011819    10000   CASH
02-04-2019  ADVANVCE.:ORD0891819    3000    CASH
02-04-2019  ADVANVCE.:ORD2021819    8000    DEBIT-CARD
02-04-2019  ADVANVCE.:ORD2031819    12000   CASH
03-04-2019  ADVANVCE.:ORD2041819    14000   CASH
03-04-2019  ADVANVCE.:ORD2051819 17000  CASH
03-04-2019  ADVANVCE.:ORD2061819    14000   CASH
03-04-2019  ADVANVCE.:ORD2061819    15000   DEBIT-CARD
03-04-2019  ADVANVCE.:ORD2071819    4000    DEBIT-CARD
03-04-2019  ADVANVCE.:ORD2071819    1000    CASH
04-04-2019  ADVANVCE.:ORD2101819    500 CASH
04-04-2019  ADVANVCE.:ORD2091819    1000    CASH
04-04-2019  ADVANVCE.:ORD2081819    2000    CASH
04-04-2019  ADVANVCE.:ORD0471819    8000    CASH

Table2: Table Name: ORDER_DETAILS
ORDER_NO    ITEM_NAME   CUSTOMER_ID
ORD2001819  ITEM-1      7
ORD2011819  ITEM-2      6
ORD2021819  ITEM-3      5
ORD2021819  ITEM-4      5
ORD2021819  ITEM-5      5
ORD2021819  ITEM-6      5
ORD2031819  ITEM-7      8
ORD2041819  ITEM-8      67
ORD2041819  ITEM-9      67
ORD2051819  ITEM-10     89
ORD2061819  ITEM-11     54
ORD2061819  ITEM-12     54
ORD2071819  ITEM-13     11
ORD2101819  ITEM-14     12
ORD2091819  ITEM-15     14
ORD2081819  ITEM-16     16
ORD1971718  ITEM-17     68
ORD1971718  ITEM-18     68
ORD0471819  ITEM-19     90
ORD0891819  ITEM-20     44
ORD1961718  ITEM-21     55

Table3: Table Name: CUSTOMER_DETAILS
CUSTOMER_ID    CUSTOMER_NAME
7              CUSTOMER-1
6              CUSTOMER-24
5              CUSTOMER-39
8              CUSTOMER-40
67             CUSTOMER-15
89             CUSTOMER-66
54             CUSTOMER-7
11             CUSTOMER-89
12             CUSTOMER-9
14             CUSTOMER-10
16             CUSTOMER-11
68             CUSTOMER-121
90             CUSTOMER-134
44             CUSTOMER-147
55             CUSTOMER-158

QUERY TO JOIN THESE TABLE WHICH WILL TAKE DATE, ORDER_NO, AMOUNT, MODE COLUMNS FROM FULL_DATA TABLE AND JOIN ITS ORDER_NO (GET ORDER NO BY SPLITTING ORDER NO BY ":") WITH ORDER_DETAILS TABLE AND GET IT CUSTOMER ID AND THEN JOIN ITS CUSTOMER ID WITH CUSTOMER DETAILS TABLE AND GET CUSTOMER NAMES????
THE DATA WILL BE LOOK LIKE THESE:
Final Query Result:
DATE        CUSTOMER_NAME   ORDER_NO               AMOUNT   MODE
01-04-2019  CUSTOMER-121    ADVANVCE.:ORD1971718    5000    DEBIT-CARD
01-04-2019  CUSTOMER-158    ADVANVCE.:ORD1961718    6000    CASH
01-04-2019  CUSTOMER-1      ADVANVCE.:ORD2001819    8000    CASH
02-04-2019  CUSTOMER-24     ADVANVCE.:ORD2011819    10000   CASH
02-04-2019  CUSTOMER-147    ADVANVCE.:ORD0891819    3000    CASH
02-04-2019  CUSTOMER-39     ADVANVCE.:ORD2021819    8000    DEBIT-CARD
02-04-2019  CUSTOMER-40     ADVANVCE.:ORD2031819    12000   CASH
03-04-2019  CUSTOMER-15     ADVANVCE.:ORD2041819    14000   CASH
03-04-2019  CUSTOMER-66     ADVANVCE.:ORD2051819    17000   CASH
03-04-2019  CUSTOMER-7      ADVANVCE.:ORD2061819    14000   CASH
03-04-2019  CUSTOMER-7      ADVANVCE.:ORD2061819    15000   DEBIT-CARD
03-04-2019  CUSTOMER-89     ADVANVCE.:ORD2071819    4000    DEBIT-CARD
03-04-2019  CUSTOMER-89     ADVANVCE.:ORD2071819    1000    CASH
04-04-2019  CUSTOMER-9      ADVANVCE.:ORD2101819    500     CASH
04-04-2019  CUSTOMER-10     ADVANVCE.:ORD2091819    1000    CASH
04-04-2019  CUSTOMER-11     ADVANVCE.:ORD2081819    2000    CASH
04-04-2019  CUSTOMER-134    ADVANVCE.:ORD0471819    8000    CASH

A:

I made a join by selecting distinct values for customer_id and order_no from order_detaisl
SELECT f.DATE, CUSTOMER_NAME, f.ORDER_NO, AMOUNT, MODE
FROM FULL_DATA f
JOIN (SELECT DISTINCT customer_id, order_no
      FROM ORDER_DETAILS) o ON SUBSTRING_INDEX(f.ORDER_NO,':',-1)= o.ORDER_NO
JOIN CUSTOMER_DETAILS c ON o.CUSTOMER_ID = c.CUSTOMER_ID
WHERE f.DATE BETWEEN '2019-04-01' AND '2019-04-04'
ORDER BY f.DATE ASC


Q:

Passing props to child doesn't make him update - React Native

I am writing because I can't figure why one of the two childs Graph.js won't update after I udpate the state of the parent Data.js (throught a "lift up" via the second child Bouton.js).
I feel giga dumb and it's been now hours, I'm desperate...
I am trying to display charts with buttons above to choose a period of time for the chart (day, week, month). Clicking the button can change the state of the parent but I can't make the child Graph to update. I know I am doing something wrong.

Parent: Data.js

    export default class Data extends React.Component {
  constructor(props) {
    super(props);
    this.state = { periode: "Jour" };
  }

  handleClick(p) {
    this.setState({
      periode: p
    });
  }

  render() {
    console.log(this.state);
    return (
      <View>
        <Boutons
          onClick={res => this.handleClick(res)}
          cursor={this.state.periode}
        />
        <Graph periode={this.state.periode} dataType="temp" />
        <Graph periode={this.state.periode} dataType="press" />
      </View>
    );
  }
}

Child 1 (everything seems fine)

export default class Boutons extends React.Component {
  constructor(props) {
    super(props);
  }

  _getNextEntryTime() {
    var d = new Date();
    var h = d.getHours();
    var m = d.getMinutes();
    var res;
    if (m >= 30) {
      res = (h + 1).toString() + ":00";
    } else {
      res = h.toString() + ":30";
    }
    return res;
  }

  //Gestion de la selection des boutons
  _boutonStyle(periode) {
    if (this.props.cursor == periode) {
      return {
        // backgroundColor: "#9c9c9c",
        borderBottomWidth: 3,
        borderColor: "#728FB5",
        width: Dimensions.get("window").width / 3 - 10,
        height: 30,
        alignItems: "center",
        justifyContent: "center"
      };
    } else {
      return {
        backgroundColor: "#dfdfdf",
        width: Dimensions.get("window").width / 3 - 10,
        height: 30,
        borderRadius: 2,
        alignItems: "center",
        justifyContent: "center"
      };
    }
  }

  _textStyle(periode) {
    if (this.props.cursor == periode) {
      return { color: "#728FB5" };
    } else {
      return { color: "black" };
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.container_top}>
          <View style={styles.rect}>
            <Text style={styles.text_top}>
              Prochain relevé: {`\n`}
              <Text style={styles.numbers}>{this._getNextEntryTime()}</Text>
            </Text>
          </View>
          <Single />
        </View>
        <View style={styles.container_buttons}>
          <TouchableOpacity
            style={this._boutonStyle("Jour")}
            onPress={() => this.props.onClick("Jour")}
          >
            <Text style={this._textStyle("Jour")}>Jour</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={this._boutonStyle("Semaine")}
            onPress={() => this.props.onClick("Semaine")}
          >
            <Text style={this._textStyle("Semaine")}>Semaine</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={this._boutonStyle("Mois")}
            onPress={() => this.props.onClick("Mois")}
          >
            <Text style={this._textStyle("Mois")}>Mois</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

Graph.js Child 2 that won't update, nothing is happening

class Graph extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isLoading: true, data: [], format_const: null };
  }

  // Chargement de la page et recherche des entrys
  componentDidMount() {
    const entrys = getEntry(this.props.periode);
    entrys.then(reponse => {
      reponse.map(donnee => {
        this.setState({
          data: this.state.data.concat(donnee[this.props.dataType])
        });
      });
      this.setState({
        format_const: Config.CHART[this.props.dataType],
        isLoading: false
      });
    });
  }

  // Affichage du loading
  _displayLoading() {
    if (this.state.isLoading) {
      return (
        <View style={styles.loading_container}>
          <ActivityIndicator size="large" />
        </View>
      );
    }
  }

  _displayChart() {
    return (
      <LineChart
        data={{
          datasets: [
            {
              data: this.state.data,
              strokeWidth: 2 // optional
            }
          ],
          legend: [this.state.format_const["label"]]
        }}
        width={Dimensions.get("window").width - 10} // from react-native
        height={220}
        withInnerLines={false}
        yAxisSuffix={this.state.format_const["alert"]}
        onDataPointClick={({ value, dataset, getColor }) =>
          Alert.alert(`${value}` + this.state.format_const["alert"])
        }
        chartConfig={{
          backgroundGradientFrom: this.state.format_const["color"],
          backgroundGradientTo: this.state.format_const["color"],
          decimalPlaces: 0, // optional, defaults to 2dp
          color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
          style: {
            borderRadius: 16
          },
          propsForDots: {
            r: "2"
          }
        }}
        bezier
        style={{
          marginVertical: 10,
          borderRadius: 16
        }}
      />
    );
  }

  render() {
    if (!this.state.isLoading) {
      return <View>{this._displayChart()}</View>;
    } else {
      return <View>{this._displayLoading()}</View>;
    }
  }
}

A:

It appears that your only use of the prop periode is in the componentDidMount method of Graph.  So at mount time, Graph reads what the prop is, and then sets the state, which is used in the Graph render method.  But when the parent component changes its state, and the new value for this.state.periode is passed as a prop to Graph, Graph doesnt doesn't necessarily know what to do with this updated information.  So you'll need to use a componentDidUpdate statement to read new props coming in from the parent's state:
componentDidUpdate(prevProps){

  if (prevProps.periode !== this.props.periode){

      const entrys = getEntry(this.props.periode);
        entrys.then(reponse => {
          reponse.map(donnee => {
            this.setState({
              data: this.state.data.concat(donnee[this.props.dataType])
            });
          });
        });

  }

}

I'm assuming you want the same thing to happen in `componentDidMount` as is happening in `componentDidUpdate`, but you may need to change the code within `componentDidUpdate` to whatever you need.


Q:

Clear Winform text boxes code snippet explanation

new to c#
I'm trying to clear all text boxes in a winform, this code snippet from:
How to clear the text of all textBoxes in the form?
does the job but can someone explain to me what it's doing?
private void ClearTextBoxes()
{
    Action<Control.ControlCollection> func = null;

    func = (controls) =>
    {
        foreach (Control control in controls)
            if (control is TextBox)
                (control as TextBox).Clear();
            else
                func(control.Controls);
    };

    func(Controls);
}

A:

Action<Control.ControlCollection> func = null; is declaring a delegate that takes as an argument a Control.ControlCollection.
func = (controls) =>    {... } assigns the delegate an anonymous method body that performs the action inside {...} when executed.
func(Controls); executes the delegate, passing in the form's Controls collection which contains all of the top-level controls in the form.
The method body of the anonymous method enumerates the controls in the ControlCollection passed in, and clears all text boxes.  For controls that are not TextBox controls, it recurses into itself and checks controls that are contained by the control.  This way if there is a GroupBox or some other control container, the children of those controls get searched for TextBoxes.
This could be rewritten simpler (avoiding delegates and anonymous methods) by doing the following:
private void ClearTextBoxes()
{
    ClearTextBoxes(Controls);
}

private void ClearTextBoxes(Control.ControlCollection controls) {
    foreach (Control control in controls)
        if (control is TextBox)
            (control as TextBox).Clear();
        else
            ClearTextBoxes(control.Controls);
};


Q:

How to show menu dynamically in Laravel

I'm trying to show menu in laravel dynamically.
I have two table, One holds Main Category and other one Holds Sub category
Here is the structure of Category table
  ----------------------------------
  | id | title   | slug  |  type   |
  | 1  | title1  | slug1 | Android |
  | 2  | title2  | slug2 | Android |
  | 3  | title3  | slug3 | Android |
  | 4  | title4  | slug4 | Ubuntu  |
  | 5  | title5  | slug5 | Ubuntu  |
  ----------------------------------

Sub Category Structure
  -----------------------------------------------
  | id | title   | slug  | category_of|
  | 1  | title1  | slug1 | 1          |
  | 2  | title2  | slug2 | 1          |
  | 3  | title3  | slug3 | 1          |
  | 4  | title4  | slug4 | 2          |
  | 5  | title5  | slug5 | 1          |
  -----------------------------------------------

Here is What I've tried
<?php
    $category = App\Models\Menu::where('categories.type', 'Android')
                ->select('categories.*', 'sub_category.slug as sub_slug', 'sub_category.title')
                ->join('sub_category', 'sub_category.category_of', '=', 'categories.id')
                ->get();
            ?>
   @foreach ($category as $value)

  slug}}/">{{ucwords(str_replace('-', ' ', $value->slug))}}

      sub_slug}}/{{$value->sub_slug}}">{{ucwords(str_replace('-', ' ', $value->sub_slug))}}

 @endforeach

The Problem I'm facing is, it is duplicating  main category every time due to foreach loop, for e.g

       Android

     Calendars

       Android

    Database Abstractions

As you see it is duplicating main category every time sub category is shown. How can i show Main category Once and then all sub category following under it
I have another Template which has different menu HTML Structure

                        Designer

                        <svg class="svg-arrow">
                            <use xlink:href="#svg-arrow"></use>
                        </svg>

                        <?php $m_des = ''; ?>
                        @foreach ($design_category as $des_value)

                            @if($m_des != $des_value->slug)

                                slug}}/">

{{ucwords(str_replace('-', ' ', $des_value->slug))}}

                                <?php $m_des = $des_value->slug; ?>
                                @endif

                                        slug}}/{{$des_value->sub_slug}}/">{{ucwords(str_replace('-', ' ', $des_value->sub_slug))}}

                        @endforeach

It is generating ul and div again and again which causes html errors

A:

There may be a better solution for it. But you can try this. Do order by categories.id then in loop check main category is printed last time or not
<?php
    $category = App\Models\Menu::where('categories.type', 'Android')
                ->select('categories.*', 'sub_category.slug as sub_slug', 'sub_category.title')
                ->join('sub_category', 'sub_category.category_of', '=', 'categories.id')
                ->orderBy('categories.id');
                ->get();
$latest_category = "";
            ?>
   @foreach ($category as $value)
<?php if($latest_category != $value->slug){ ?>

  slug}}/">{{ucwords(str_replace('-', ' ', $value->slug))}}

<?php
$latest_category = $value->slug;
} ?>

      sub_slug}}/{{$value->sub_slug}}">{{ucwords(str_replace('-', ' ', $value->sub_slug))}}

 @endforeach

EDIT

    <?php $m_des = '';
    $end_div = '';
    ?>
    @foreach ($design_category as $des_value)

        @if($m_des != $des_value->slug)
        {{$end_div}}

            slug}}/">

{{ucwords(str_replace('-', ' ', $des_value->slug))}}

            <?php $m_des = $des_value->slug;
            $end_div = "
";
            ?>
            @endif

                    slug}}/{{$des_value->sub_slug}}/">{{ucwords(str_replace('-', ' ', $des_value->sub_slug))}}

    @endforeach
    {{$end_div}}


Q:

¿Por qué tengo este error a la hora de subir una imagen con php al servidor?

Estoy creando una página para que suba imágenes al servidor, este es mi index:

(function() {
  "use strict";

  $(".input-file").each(function() {
    var $input = $(this),
        $label = $input.next(".js-labelFile"),
        labelVal = $label.html();

    $input.on("change", function(element) {
      var fileName = "";
      if (element.target.value) fileName = element.target.value.split("\\").pop();
      fileName ? $label.addClass("has-file").find(".js-fileName").html(fileName) : $label.removeClass("has-file").html(labelVal);

    });
  });
})();
/* Etiquetas */

html, body {
  margin: 0 auto;
  padding: 0 auto;
}
body {
  background-color:white;
  font-family: 'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif;
}

h1, h3 {
  color:black;
}

/* Formulario */

.input-file {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}
.input-file + .js-labelFile {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 10px;
  cursor: pointer;
}
.input-file + .js-labelFile .icon:before {
  content: "\f093";
}
.input-file + .js-labelFile.has-file .icon:before {
  content: "\f00c";
  color: #5AAC7B;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="author" content="Diesan Romero">
  <meta name="description" content="Sube tus imagenes de manera temporal">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.5.0/css/mdb.min.css" rel="stylesheet">
  <link rel="stylesheet" href="src/styles.css">
  <title>Imágenes Momentaneas</title>

Imágenes Momentáneas

      <form action="data.php" method="post"  enctype="multipart/form-data">

Seleccione el tiempo en minutos que estará su imagen en línea

              <button type="button" class="btn btn-warning">1</button>
              <button type="button" class="btn btn-warning">5</button>
              <button type="button" class="btn btn-warning">15</button>
              <button type="button" class="btn btn-warning">30</button>
              <button type="button" class="btn btn-warning">60</button>

            <input type="file" name="imagen" id="imagen" class="input-file">

              Elija la imagen a subir

            <input type="submit" class="btn btn-lg btn-red" value="Subir Imagen">

      </form>

          La imagen ha sido cargada correctamente, ahora debe subirla.

y acá tengo el php que recogerá los datos de la imagen:
<?php
// Informacion de la imagen
  $nombre = $_FILES['imagen']['name'];
  $tipo = $_FILES['imagen']['type'];
  $tamano = $_FILES['imagen']['size'];

  //Ruta de la carpeta destino en servidor
  $destino = $_SERVER['DOCUMENT_ROOT'].'/imagenes/uploads';

  //Envia la imagen del directorio temporar al servidor
  move_uploaded_file($_FILES['imagen']['tmp_name'], $destino.$nombre);
?>

el problema acá es que cuando subo la imagen, que la envío al servidor me salen estos dos errores:

Warning: move_uploaded_file(C:/xampp/htdocs/imagenes/uploads2.JPG):
  failed to open stream: No such file or directory in
  C:\xampp\htdocs\imagenes-momentaneas\data.php on line 11
Warning: move_uploaded_file(): Unable to move
  'C:\xampp\tmp\php5078.tmp' to 'C:/xampp/htdocs/imagenes/uploads2.JPG'
  in C:\xampp\htdocs\imagenes-momentaneas\data.php on line 11

no se mucho php, y no logro aún comprender cuál es el problema acá.

A:

Te muestra las advertencias porque no existe la carpeta, y al no existir la carpeta no puede crear el archivo, para que no pase eso podemos validar que existan, si no existen las creamos con mkdir y luego guardamos el archivo. También te sugiero utilizar la constante de PHP DIRECTORY_SEPARATOR para que no dependas del sistema operativo
<?php
// Informacion de la imagen
  $nombre = $_FILES['imagen']['name'];
  $tipo = $_FILES['imagen']['type'];
  $tamano = $_FILES['imagen']['size'];

  //Ruta de la carpeta destino en servidor
  $carpetaImagenes = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'imagenes';
  if (!is_dir($carpetaImagenes)) {
      mkdir($carpetaImagenes, 0775);
  }
  if (!is_writable($carpetaImagenes)) {
      chmod($carpetaImagenes, 0775);
  }

  $carpetaUploads = $carpetaImagenes.DIRECTORY_SEPARATOR.'uploads';
  if (!is_dir($carpetaUploads)) {
      mkdir($carpetaUploads, 0775);
  }
  if (!is_writable($carpetaUploads)) {
      chmod($carpetaUploads, 0775);
  }

  // Envia la imagen del directorio temporar al servidor
  move_uploaded_file($_FILES['imagen']['tmp_name'], $carpetaUploads.DIRECTORY_SEPARATOR.$nombre);
?>


Q:

Acumatica - Generic Inquiries: Links redirects to customized pages

I created a page and graph that extends ARPaymentEntry. Now when I navigate to Receivables -> Payments and Applications -> then Hit “Add New Record” it goes to my page not the original page (AR302000).
Attached image is my sitemap.
How do I configure Generic inquiry to open the specific page I want? And what am I missing why the built-in generic inquiry messes up when I extend a graph.
We decided not to use the built-in payments since will be adding custom computation and other business logic.
I am currently running Acumatica 2018 R1.
Thank You
Link to my ARPaymentEntryExtension.cs
Link to my Customized Page

A:

on the Generic Inquiry Screen, Replace ENTRY SCREEN SETTINGS with your own page, so that when you open that customized page, the Generic Inquiry will be opened first, and Check Enable New Record Creation so that the + button will appear.


Q:

How to make links open within webview or open by default browser depending on domain name?

I have WebView in which I want to open links belong to domain www.example.org in webview while all other links (if clicked) open by the default browser outside of my application.
I tried to use public boolean shouldOverrideUrlLoading(WebView view, String url)  but it does not work properly.
Here is the code that does not work:
public class MyWebViewClient extends WebViewClient {
    @Override
               public boolean shouldOverrideUrlLoading(WebView view, String url) {
                   try {
                   URL urlObj = new URL(url);
                   if (urlObj.getHost().equals("192.168.1.34")) {
                       view.loadUrl(url);
                       return true;
                   } else {
                       view.loadUrl(url);
                       return false;
                     }
                   } catch (Exception e) {

                   }
               }
}

In both cases ( return true and return false) the URL is handled by my application.

A:

Once you create and attach a WebViewClient to your WebView, you have overridden the default behavior where Android will allow the ActivityManager to pass the URL to the browser (this only occurs when no client is set on the view), see the docs on the method for more.
Once you have attached a WebViewClient, returning false form shouldOverrideUrlLoading() passes the url to the WebView, while returning true tells the WebView to do nothing...because your application will take care of it.  Unfortunately, neither of those paths leads to letting Android pass the URL to the browser.  Something like this should solve your issue:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    try {
      URL urlObj = new URL(url);
      if( TextUtils.equals(urlObj.getHost(),"192.168.1.34") ) {
        //Allow the WebView in your application to do its thing
        return false;
      } else {
        //Pass it to the system, doesn't match your domain
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
        //Tell the WebView you took care of it.
        return true;
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
}

I know that seems a little counterintuitive as you would expect return false; to completely circumvent the WebView, but this is not the case once you are using a custom WebViewClient.
Hope that helps!

A:

If you can't be bothered to explain what "does not work properly" means, we can't be bothered to give you much specific help.
Use shouldOverrideUrlLoading(). Examine the supplied URL. If it is one you want to keep in the WebView, call loadUrl() on the WebView with the URL and return true. Otherwise, return false and let Android handle it normally.


Q:

How to avoid this degree to radian error?

While developing pie chart using core plot I added animation for that for given code
    CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform"];
   CATransform3D transform = CATransform3DMakeRotation(DegreesToRadians(360), 0, 0, 1);
   rotation.toValue = [NSValue valueWithCATransform3D:transform];
    rotation.duration = 10.0f;
    [pieChart addAnimation:rotation forKey:@"rotation"];

This code gives following error Semantic Issue:
Implicit declaration of function 'DegreesToRadians' is invalid in C99

What can I do for avoid this?
And also run time it gives following error:
Apple_o  Linker id error  "_DegreesToRadians", referenced from:

Thanks and Regards
Vijayakumar
iOS Developer at Rhytha
https://rhytha.com/

A:

Just define a macro like:
#define DEGREES_RADIANS(angle) ((angle) / 180.0 * M_PI)

And change your method like:
CATransform3D transform = CATransform3DMakeRotation(DEGREES_RADIANS(360), 0, 0, 1);


Q:

Serial Port Polling and Data handling

I am trying to read from several serial ports from sensors through microcontrollers. Each serial port will receive more than 2000 measurements (each measurement is 7 bytes, all in hex). And they are firing at the same time. Right now I am polling from 4 serial ports. Also, I translate each measurement into String and append it to a Stringbuilder. When I finish receiving data, they will be ouput in to a file. The problem is the CPU consumption is very high, ranging from 80% to 100%.
I went though some articles and put Thread.Sleep(100) at the end. It reduces CPU time when there is no data coming. I also put Thread.Sleep at the end of each polling when the BytesToRead is smaller than 100. It only helps to a certain extent.
Can someone suggest a solution to poll from serial port and handle data that I get? Maybe appending every time I get something causes the problem?
//I use separate threads for all sensors
private void SensorThread(SerialPort mySerialPort, int bytesPerMeasurement, TextBox textBox,     StringBuilder data)
    {
        textBox.BeginInvoke(new MethodInvoker(delegate() { textBox.Text = ""; }));

        int bytesRead;
        int t;
        Byte[] dataIn;

        while (mySerialPort.IsOpen)
        {
            try
            {
                if (mySerialPort.BytesToRead != 0)
                {
                  //trying to read a fix number of bytes
                    bytesRead = 0;
                    t = 0;
                    dataIn = new Byte[bytesPerMeasurement];
                    t = mySerialPort.Read(dataIn, 0, bytesPerMeasurement);
                    bytesRead += t;
                    while (bytesRead != bytesPerMeasurement)
                    {
                        t = mySerialPort.Read(dataIn, bytesRead, bytesPerMeasurement - bytesRead);
                        bytesRead += t;
                    }
                    //convert them into hex string
                    StringBuilder s = new StringBuilder();
                    foreach (Byte b in dataIn) { s.Append(b.ToString("X") + ","); }
                    var line = s.ToString();

                                            var lineString = string.Format("{0}  ----          {2}",
                                                      line,
                                                    mySerialPort.BytesToRead);
                    data.Append(lineString + "\r\n");//append a measurement to a huge Stringbuilder...Need a solution for this.

                    ////use delegate to change UI thread...
                    textBox.BeginInvoke(new MethodInvoker(delegate() { textBox.Text = line; }));

                    if (mySerialPort.BytesToRead <= 100) { Thread.Sleep(100); }
                }
            else{Thread.Sleep(100);}

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
        }

    }

A:

this is not a good way to do it, it far better to work on the DataReceived event.
basically with serial ports there's a 3 stage process that works well.

Receiving the Data from the serial port
Waiting till you have a relevant chunk of data
Interpreting the data

so something like
class DataCollector
{
    private readonly Action<List<byte>> _processMeasurement;
    private readonly string _port;
    private SerialPort _serialPort;
    private const int SizeOfMeasurement = 4;
    List<byte> Data = new List<byte>();

    public DataCollector(string port, Action<List<byte>> processMeasurement)
    {
        _processMeasurement = processMeasurement;
        _serialPort = new SerialPort(port);
        _serialPort.DataReceived +=SerialPortDataReceived;
    }

    private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while(_serialPort.BytesToRead > 0)
        {
           var count = _serialPort.BytesToRead;
           var bytes = new byte[count];
           _serialPort.Read(bytes, 0, count);
           AddBytes(bytes);
        }
    }

    private void AddBytes(byte[] bytes)
    {
        Data.AddRange(bytes);
        while(Data.Count > SizeOfMeasurement)
        {
            var measurementData = Data.GetRange(0, SizeOfMeasurement);
            Data.RemoveRange(0, SizeOfMeasurement);
            if (_processMeasurement != null) _processMeasurement(measurementData);
        }

    }
}

Note:  Add Bytes keeps collecting data till you have enough to count as a measurement, or if you get a burst of data, splits it up into seperate measurements.... so you can get 1 byte one time, 2 the next, and 1 more the next, and it will then take that an turn it into a measurement.   Most of the time if your micro sends it in a burst, it will come in as one, but sometimes it will get split into 2.
then somewhere you can do
var collector = new DataCollector("COM1", ProcessMeasurement);

and
  private void ProcessMeasurement(List<byte> bytes)
            {
                // this will get called for every measurement, so then
                // put stuff into a text box.... or do whatever
            }


Q:

Band pass filter (digital resonance)

Q1:  Consider a discrete-time band-pass filter (BPF) that uses only two poles as
$$ H(z) = G \frac{1}{\big(1-r \, e^{j \omega_0} z^{-1}\big)\big(1-r \, e^{-j \omega_0} z^{-1}\big)} $$
where this filter has a center frequency of $\omega_0$.  If this BPF was designed to have a very narrow bandwidth by selecting $r$ to be very close to unity, show that the 3dB bandwidth of the BPF filter is approximately given by
$$ BW_{3dB}=2(1-r) $$
(Hint:  Use a geometrical approach on the unit circle.)

A:

Here is (I think) what you are supposed to be doing

Draw a diagram of the poles and the unit circle and zoom in on the area around the resonance frequency
Estimate the relative gain as the inverse of the distance between the pole and the unit circle (assuming that conjugate pole is too far away to change the gain much over a narrow frequency range)
Pencil in the -3dB points by, again, using distance as a representative for gain
Ignore the curvature of the circle (since r is close to 1)
Do some trigonometry to calculate the distance between the two -3dB points
Convert this distance to a frequency difference.


Q:

Метод для складывания цифр числа

Если ли метод для складывания цифр числа?
Например:
15 = 1 + 5 = 6

или
584 = 5 + 8 + 4 = 17

A:

function sum(a) {
  return a.toString().split('').reduce(function(a, b) { return a + parseInt(b); }, 0);
}

console.log(sum(584))

ES2015

function sum(a) {
  return a.toString().split('').reduce((a, b) => a + parseInt(b), 0);
}

console.log(sum(584))

A:

Можно брать остатки и округлять:
function digsum(n) {
  var sum = 0;
  while(n) sum += n % 10, n = Math.floor(n / 10);
  return sum;
}

digsum(15)  // 6
digsum(584) // 17


Q:

Mandrill's attachment without extension on Hotmail/Outlook.com

I guess there is a issue with Mandrill attachments x Hotmail/Outlook.com.
I can send e-mail attachments with Mandrill using base64_encode(). I am using the PHP library.
If I send an e-mail to Gmail or any other provider, the attachment looks fine. Downloading it and opening normally.
But sending to a Hotmail/Outlook.com, the attachments came with no extension/file format. By downloading, it can only be opened by adding the extension manually (for example, .pdf).
The code:
$file_data = file_get_contents($_FILES["test_file"]["tmp_name"])
$file_type = $_FILES["test_file"]["type"]

$mandrill = new Mandrill('MANDRILL_API_KEY_HERE');
$message = array(
  'html' => $html,
  'subject' => 'Testing',
  'from_email' => 'sender@test.com',
  'from_name' => 'Sender',
  'attachments' => array(
    array(
      'name' => 'Test PDF document',
      'type' => $file_type,
      'content' => base64_encode($file_data)
    )
  ),
  'to' => array(
    array(
      'email' => 'to@test.com',
      'name' => 'John Doe',
      'type' => 'to'
    )
  ),
  'headers' => array('Reply-To' => 'sender@test.com')
);
$result = $mandrill->messages->send($message);

Any ideas? Is it a Mandrill or Hotmail issue?
Thanks!

A:

I have found the solution. Gmail and other email services recognizes the type attribute as above, but Hotmail only recognizes the file type by adding the extension to the attachment name (name attribute).
For example:
'name' => 'Test PDF document.pdf',

It look obvious, but Hotmail requires it. Sharing my simple knowledge, since I received no answers.


Q:

Integration of an trig function

How should i start off in integrating the below function. i am trying to use trig substitution? But i can't really see what to replace off in this case. any tips on how to start off with it?
$$\int\frac{1}{2+cosx}dx$$

A:

Let $t=\tan{(x/2)}$; then $dx=2 \, dt/(1+t^2)$ and $\cos{x} = (1-t^2)/(1+t^2)$.  The integral is then
$$2\int \frac{dt}{3+t^2} = \frac{2}{\sqrt{3}} \arctan{\frac{t}{\sqrt{3}}}+C=\frac{2}{\sqrt{3}} \arctan{\left [\frac{\tan{(x/2)}}{\sqrt{3}}\right ]}+C$$


Q:

Why is Main method private?

New console project template creates a Main method like this:
class Program
{
    static void Main(string[] args)
    {
    }
}
Why is it that neither the Main method nor the Program class need to be public?

A:

The entry point of a program is marked with  the .entrypoint IL directive. It does not matter if the method or the class is public or not, all that matters is this directive.

A:

The Main method shouldn't need to be called by anyone.
It is actually marked as the entry point for execution in the EXE itself, and therefore has no outside callers by default.
If you WANT, you can open it up to be called by marking public, e.g. if you are turning a console app into an API.


Q:

how to use placeholder for Textbox in VB.Net 2010 like html

I have a form that does some mathematical calculation.
I want to be able users to enter data quickly without erasing the value.
I thing its good to use placeholder like I did in html
but how can i use it in VB.Net 2010?
Thanks
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        gtp.Text = "0.00"
        vatt.Text = "0.00"
        wht.Text = "0.00"
        npr.Text = "0.00"
    End Sub

A:

This code clears the text box if the current value is the placeholder value, otherwise it retains the input value.
Public Class Form1
Private Sub TextBox1_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
    If TextBox1.Text = "0.00" Then
        TextBox1.Text = ""
    End If
End Sub
Private Sub TextBox1_LostFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus
    If TextBox1.Text = "" Then
        TextBox1.Text = "0.00"
    End If
End Sub
End Class

If you always want it to clear the textbox then use this.
Public Class Form1
Private Sub TextBox1_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
    TextBox1.Text = ""
End Sub
Private Sub TextBox1_LostFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus
    If TextBox1.Text = "" Then
        TextBox1.Text = "0.00"
    End If
End Sub
End Class

To simulate an actual placeholder such as the one in HTML5 you'll need to overlay a label control on top of your textbox and set it's visability based on the event keyDown and LostFocus/Leave Event which will depend on your version of VS


Q:

Show Selected row full information on Modal View

Example :
i have 6 Columns for every row.
    Column1 = personid
    Column2 = Image
    Column3 = FirstName
    Column4 = MiddleName
    Column5 = LastName
    Column6 = Position

Example:
Person ID  Image          FirstName    MiddleName   LastName   Position
    1      Picture1.jpg   John         Doe          Peter      Manager

The PHP Code is:
<?php
include('connect.php');
$selected=mysql_query("SELECT * FROM persontbl order by personid");
$i=1;
while($personrow=mysql_fetch_array($selected))

{
    $personid=$personrow['personid'];
    $personimage=$personrow['personimage'];
    $firstname=$personrow['firstname'];
    $middlename=$personrow['middlename'];
    $lastname=$personrow['lastname'];
    $position=$personrow['position'];

?>

I have created this code to display specific information of the row on grid view using bootstrap(Image and FirstName only):

<img src="<?php echo $personimage;?>" alt="">

<?php echo $FirstName; ?>

And the modal form is:

<button type="button" class="btn btn-info close" data-dismiss="modal">Close Form ×</button>

Full Information of the Person

<img src="<?php echo $personimage; ?>" width="25%" height="25%" alt="">

 Person's Name:
<?php echo $FirstName; ?>

Person's Middle Name:
<?php echo $middlename; ?>

Person's Last Name:
<?php echo $lastname; ?>

Person's Position:
<?php echo $position; ?>

<button type="button" class="btn btn-default" data-dismiss="modal">Close Form</button>

Then I want to display full information on Modal View. Then When I click on one record row, the Modal View will pop up and display the full information for the SELECTED record ROW.
But NOW, The Modal shows only the information of the first row. When I click on another row, It's not showing the full information of the selected row, It only displays the first row's data. But It still opens the Modal.
What should I do to display the selected record full information from the database to the modal view using PDO Method? please support me with full code detail.

A:

this is code i tested in localhost

<?php
include('login/dbconnect.php');
$selected=mysqli_query($conn,"SELECT * FROM leads");
$i=1;
?>
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <?php

while($personrow=mysqli_fetch_array($selected))

{
    $personid=$personrow['ID'];
    $FirstName=$personrow['FIRST_NAME'];

?>

 <a href="" data-toggle="modal" data-target="#<?php echo $personid ?>" class="thumbnail home-thumb"><img src="<?php echo $personimage;?>" alt="">

<?php echo $FirstName; ?>

 <div id="<?php echo $personid ?>" class="modal fade" role="dialog">

<button type="button" class="btn btn-info close" data-dismiss="modal">Close Form ×</button>

Full Information of the Person

hiiiiiiiiiiiiiiii

<?php echo $FirstName; ?>

<button type="button" class="btn btn-default" data-dismiss="modal">Close Form</button>

<?php
}

?>


Q:

wordpress query to show all images by authors

I recently did a conversion from a really old db to a wordpress compatible one.
It's quite a simple site, that allows Artists to show there artwork.
In the worpdress media library each image has an author/image attached to it.
Is there a wordpress query that allows us to tap into this info?

A:

You can try query_posts()
query_posts('author=1&post_type=image');


Q:

Looking for a short SF story about two ultra-fast ships flying around the entire universe

I'm trying to find a story I read maybe fifteen or twenty years ago. The story itself might be much older, of course: it had a 1950's - 60's 'golden age of hard SF' feel to it.
As I remember it, the plot involved an effort to find out if the universe is closed in 4D by having two ultra-fast ships complete a flight around the entire universe.
One of the ships was shaped like a ring so that the other, needle-shaped ship could fly through its central hole.
The idea was that the ring-shaped ship would take off, and after a while the needle-shaped ship would accelerate on a course exactly through the hole in the ring-ship, overtaking it; then the roles would reverse and the ring-ship would accelerate on a course to overtake the needle-ship passing through its hole - and so on. I think this alternating aim-accelerate-overtake process was very fast, the drive being inertia-less hyperdrives or what have you: the crew aboard never noticed the acceleration.
The story follows the crew of only one of the two ships: they could not maintain contact during the flight supposedly because of the choppy flight pattern. They even never saw the other ship during the mission, because they passed one another way too fast for that.
I suppose that the idea was that this would plot a straight course through space (though it would of course be subject to 4D curvature nonetheless). The only other thing I remember is that at a certain point in the story the ship's gyroscope (or whatever they had) revealed their course had begun to curve anyhow.
A detail that I think comes from this story is that when they are really far out on their mission, there are no galaxies or stars in sight anywhere near and the only thing visible is a kind of faraway glow of the assembled galaxies of familiar space. However, I might be conflating it with "The Ethics of Madness" by Larry Niven, where two people in relativistic ramscoop ships fly off, ever closer to light speed and thus eventually covering a huge distance in their subjective time as well.
I also seem to remember that the crew noticed something else; something strange and a bit spooky when they were very far away. But what that something was keeps eluding me, and it might also come from the memory of yet another story, like the Star Trek TNG 'The Traveller' episode, which featured a similar journey to the other side of the universe.
That's what comes from reading too many short SF stories, it seems ;)
Does this sound familiar to anyone?
Thanks!

edited to add more remembered details

A:

You're neither misremembering the story, nor mixing it up.
The spooky thing was exactly that the gyroscope - which was supposed to ensure they could maintain a straight course - was beginning to turn. One member of the crew got afraid they were slowly drifting off course and would be lost in space forever, and tried to turn off the engines before it was too late. The rest of the crew had to restrain him by force. Then they realised that the gyroscope was turning exactly because space itself was curved and that they would be home again when it had made a full turn. This gave the crew new confidence and energy and allowed them to finish their journey in good spirits.
Unfortunately, I remember neither title nor author. I agree with your assessment of its 'golden age' feel. Maybe the details added above allow somebody else to identify the story.
[edit] Found the story! It's Dead Ahead by Jack Vance, written in 1949.


Q:

SDL Tridion 2011 SP1 | How to publish a specific page on publish of another page

I need to publish page B on publish of page A. How can it be done in SDL Tridion 2011 SP1 ? Can it be done through C# TBB ? Can somebody please provide the code sample for the same.

A:

Technically it is possible to do this in a Template Building Block, but it makes more sense to solve it via either an event handler (http://sdltridionworld.com/community/2011_extensions/rapideditorialinterface.aspx) or a custom resolver (http://nunolinhares.blogspot.nl/2011/10/tridion-publisher-and-custom-resolvers.html).
The added benefit of a resolver over an event handler is that you are not creating a new publish action, but you are just adding your additional Page to the existing Publish Transaction.
If you want to know more about custom resolvers, try Googling "tridion custom resolver".

A:

You can achieve this via the Event System.  Bart's Rapid Editorial Interface extension is open source and has an example that does what you're looking for.  Have a look at it here: http://sdltridionworld.com/community/2011_extensions/rapideditorialinterface.aspx


Q:

How to verify that data source is valid and configured properly?

In application start up , I am loading data source as shown below code -
@Bean(name = "dataSource")
public DataSource getDataSource() {
    ComboPooledDataSource dataSource = new ComboPooledDataSource ();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/usersdb");
    dataSource.setUsername("root");
    dataSource.setPassword("secret");
    return dataSource;
}

So here I would like to verify that whether the data source loaded properly,
One possible way could be datasource.getConnection() before return but here I have to create  unnecessary connection object which is having some high cost.
Please help me to find a way to verify that data source has been instantiated properly. I have heard something about validate query but not sure how it would work. please suggest.

A:

It is impossible to validate DataSource without test connection.
First of all, you define bean with singleton scope by default so single DataSource will be created with single check.
Secondly, do not worry about the creation cost of Connection because you use PooledDataSource. 'Pooled' means that pool of connections exists that is why physical connection once created can be used many times by the application.
The validate query (or test query) is used to check if existing Connection was broken. See Configuring Connection Testing for more details.


Q:

Requisição Ajax com dados vindo de outro Ajax

Eu tenho um Ajax. que busca informações do receitaws
esse ajax trás o endereço e tbm o CEP.
E eu tenho outro Ajax, que tras informações de endereço, através do CEP,
um em particular, que eu preciso, que é o Código do Muncipio.
Então eu queria fazer assim, ao pesquisar o CNPJ, carregar os dados vindo do receiraWs ao carregar os dados, ja automaticamente, fazer a outra requisição via CEP. assim, trazendo o Código do municipio.
Ou seja, se a consulta ao receitaws fosse bem sucessedida, no momento que tivesse carregando os dados, ao chegar no dado CEP, ja fizesse o segundo ajax

<input class="form-control-sm" placeholde="CNPJ" id="Cliente_Cnpj" name="Cliente_Cnpj"  type="text" >

Pesquisar Cnpj

<input class="form-control-sm id="Cliente_RazaoSocial" name="Cliente_RazaoSocial" placeholder="rAZÃO sOCIAL">

<input class="form-control-sm"  placeholder="Código Cidade" id="Endereco_Cidade_Codigo" name="Endereco_Cidade_Codigo">

<input class="form-control-sm " placeholder="CEP" id="Endereco_Cep" name="Endereco_Cep">

A:

Utilize os métodos abaixo para processar as chamadas:
$.getJSON("https://...", function(dados1) {
   // 1ª Chamada

})
.done(function(dados1) {
    console.log(dados1); // Dados retornados da primeira chamada

    $.getJSON("https://...", function(dados2) {
        // 2ª Chamada

    })
    .done(function(dados2) {
       console.log(dados2); // Dados retornados da segunda chamada
    })
    .fail(function() {
    })
    .always(function() {
    });
})
.fail(function() {
})
.always(function() {
});

Sempre observando quanto a conversão dos dados recebidos;
Segue documentação completa para maiores detalhes: https://api.jquery.com/jQuery.getJSON/


Q:

LaunchDaemon for pf won't load at startup

I have a plist in /Library/LaunchDaemons/ that should run as root on startup.
When I run sudo launchctl load /Library/LaunchDaemons/com.apple.pfctl.plist, it works. However on reboot it does not work.
Interestingly, after reboot, when I run that command it says /Library/LaunchDaemons/com.apple.pfctl.plist: service already loaded but it is not functioning. However, if I unload and load it works normally.
Nothing appears in my error reporting /tmp/pfctl.err.
My plist is here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.apple.pfctl</string>
<key>ProgramArguments</key>
        <array>
                <string>pfctl</string>
                <string>-e</string>
                <string>-f</string>
                <string>/etc/pf.conf</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
<key>StandardErrorPath</key>
<string>/tmp/pfctl.err</string>
<key>StandardOutPath</key>
<string>/tmp/pfctl.out</string>
</dict>
</plist>

A:

The problem was that there is a default plist for pfctl at /System/Library/LaunchDaemons/com.apple.pfctl.plist. They were conflict.
In that plist I set <key>Disabled</key> to <true/>, and everything works as expected.


Q:

C# Calling a Variable from another Variable

public class Car
 {
     public string Color { get; set; }
     public string Model { get; set; }
 }

How I call "Car.Color" or "Car.Model" from a variable?
Ex.
string MyVariable = "Color";
MyListBox.Items.Add(Car.Model); //It Works Ok
MyListBox.Items.Add(Car.MyVariable); // How??

Regards.

A:

You'd have to use reflection. For example:
var property = typeof(Car).GetProperty(MyVariable);
MyListBox.Items.Add(property.GetValue(Car)); // .NET 4.5

Or:
var property = typeof(Car).GetProperty(MyVariable);
MyListBox.Items.Add(property.GetValue(Car, null)); // Prior to .NET 4.5

(Your sample code would be clearer if you used a different name for the variable Car than the type Car, mind you. Ditto MyVariable which doesn't look like a variable in normal .NET naming conventions.)


Q:

Solve linear congruence: $ax + b = y \; (mod \; m)$

I am trying to solve $ax + b = y \; (mod \; m)$ for x, where $a,b,y,m$ are known values. This corresponds to running a linear congruential generator in reverse for one iteration.
I am happy to assume that $gcd(a,m) = 1$, which according to this page, means there is a single solution for $x$. I am looking for a nice algebraric manipulation of the equation that will produce this value for $x$.
I begin like this: first subtract $b$ from both sides
$$ax = y - b = u \; (mod \; m)$$
Next, compute $n$, the multiplicative inverse of $u$, to arrive at
$$axn = un = 1 \; (mod \; m)$$
How do I continue and find $x$?

A:

Once you have $ax = u \pmod{m}$, just multiply by $a$'s inverse in $\Bbb Z/m\Bbb Z$ (i.e. the only solution to $a a' = 1 \pmod{m}$ since you assume $\gcd(a,m)=1$):
$$x = a^{-1} ax = a^{-1}u \pmod{m}$$
There's a lot of info (including computation methods) on modular inverse on Wikipedia.


Q:

Tetris Piece Rotation Algorithm

What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game?  I always find the piece rotation and representation schemes confusing.
Most tetris games seem to use a naive "remake the array of blocks" at each rotation:
http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris
However, some use pre-built encoded numbers and bit shifting to represent each piece:
http://www.codeplex.com/wintris
Is there a method to do this using mathematics (not sure that would work on a cell based board)?

A:

There is a limited amount of shapes, so I would use a fixed table and no calculation. That saves time.
But there are rotation algorithms.
Chose a centerpoint and rotate pi/2.
If a block of a piece starts at (1,2) it moves clockwise to (2,-1) and (-1,-2) and (-1, 2).
Apply this for each block and the piece is rotated.
Each x is the previous y and each y - the previous x. Which gives the following matrix:
[  0   1 ]
[ -1   0 ]

For counterclockwise rotation, use:
[  0  -1 ]
[  1   0 ]

A:

When I was trying to figure out how rotations would work for my tetris game, this was the first question that I found on stack overflow.  Even though this question is old, I think my input will help others trying to figure this out algorithmically.  First, I disagree that hard coding each piece and rotation will be easier.  Gamecat's answer is correct, but I wanted to elaborate on it.  Here are the steps I used to solve the rotation problem in Java.

For each shape, determine where its origin will be.  I used the points on the diagram from this page to assign my origin points. Keep in mind that, depending on your implementation, you may have to modify the origin every time the piece is moved by the user.
Rotation assumes the origin is located at point (0,0), so you will have to translate each block before it can be rotated.  For example, suppose your origin is currently at point (4, 5).  This means that before the shape can be rotated, each block must be translated -4 in the x-coordinate and -5 in the y-coordinate to be relative to (0,0).
In Java, a typical coordinate plane starts with point (0,0) in the upper left most corner and then increases to the right and down.  To compensate for this in my implementation, I multiplied each point by -1 before rotation.
Here are the formulae I used to figure out the new x and y coordinate after a counter-clockwise rotation.  For more information on this, I would check out the Wikipedia page on Rotation Matrix. x' and y' are the new coordinates:
x' = x * cos(PI/2) - y * sin(PI/2) and y' = x * sin(PI/2) + y * cos(PI/2)
.
For the last step, I just went through steps 2 and 3 in reverse order.  So I multiplied my results by -1 again and then translated the blocks back to their original coordinates.

Here is the code that worked for me (in Java) to get an idea of how to do it in your language:
public synchronized void rotateLeft(){

    Point[] rotatedCoordinates = new Point[MAX_COORDINATES];

    for(int i = 0; i < MAX_COORDINATES; i++){

        // Translates current coordinate to be relative to (0,0)
        Point translationCoordinate = new Point(coordinates[i].x - origin.x, coordinates[i].y - origin.y);

        // Java coordinates start at 0 and increase as a point moves down, so
        // multiply by -1 to reverse
        translationCoordinate.y *= -1;

        // Clone coordinates, so I can use translation coordinates
        // in upcoming calculation
        rotatedCoordinates[i] = (Point)translationCoordinate.clone();

        // May need to round results after rotation
        rotatedCoordinates[i].x = (int)Math.round(translationCoordinate.x * Math.cos(Math.PI/2) - translationCoordinate.y * Math.sin(Math.PI/2));
        rotatedCoordinates[i].y = (int)Math.round(translationCoordinate.x * Math.sin(Math.PI/2) + translationCoordinate.y * Math.cos(Math.PI/2));

        // Multiply y-coordinate by -1 again
        rotatedCoordinates[i].y *= -1;

        // Translate to get new coordinates relative to
        // original origin
        rotatedCoordinates[i].x += origin.x;
        rotatedCoordinates[i].y += origin.y;

        // Erase the old coordinates by making them black
        matrix.fillCell(coordinates[i].x, coordinates[i].y, Color.black);

    }
    // Set new coordinates to be drawn on screen
    setCoordinates(rotatedCoordinates.clone());
}

This method is all that is needed to rotate your shape to the left, which turns out to be much smaller (depending on your language) than defining each rotation for every shape.

A:

This is how I did it recently in a jQuery/CSS based tetris game.
Work out the centre of the block (to be used as a pivot point), i.e. the centre of the block shape.
Call that (px, py).
Each brick that makes up the block shape will rotate around that point.
For each brick, you can apply the following calculation...
Where each brick's width and height is q, the brick's current location (of the upper left corner) is (x1, y1) and the new brick location is (x2, y2):
x2 = (y1 + px - py)

y2 = (px + py - x1 - q)

To rotate the opposite direction:
x2 = (px + py - y1 - q)

y2 = (x1 + py - px)

This calculation is based on a 2D affine matrix transformation.
If you are interested in how I got to this let me know.


Q:

Kotlin: Can I access a nested array from inside another array?

This may be a dumb question, but I have an array:
var testarray = arrayOf(0,0,arrayOf(7,5,2))

So I tried to access the second array by typing testarray[2][1]. However, this throws an error:
error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
@InlineOnly public inline operator fun <@OnlyInputTypes K, V> Map<out Int, ???>.get(key: Int): ??? defined in kotlin.collections
testarray[2][1]
^
error: no get method providing array access
testarray[2][1]

Is there a way to access the nested array?

A:

Your outer array contains Ints, and an array. So its actual declared type (that you could specify, or could let the IDE specify for you), is Array<Serializable>.
A Serializable could be anything. The compiler doesn't know that the element at index 2 happens to be an array. So it can't let you use the [] operator on it. You need to cast the element to an array to be able to do that:
println((testarray[2] as Array<Int>)[1])

That would fix the compilation issue, but not the design issue. Using arrays in general is already a smell, but using arrays containing mixed types is an even bigger smell. You should reconsider your design.


Q:

STM32F103 SPI only receives 0x00

I'm using SPI for interfacing between STM32F103 and MRF24J40. I write a value to MRF24J40 register and then read back to confirm it works functionally but I only receive 0x00 from MISO pin. Here are my SPI Initialize and MRF24J40 interface
SPI Config:
SPI_InitTypeDef SPI_InitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
SPI_InitStruct.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_32;
SPI_InitStruct.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStruct.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStruct.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStruct.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStruct.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStruct.SPI_Mode = SPI_Mode_Master;
SPI_InitStruct.SPI_NSS = SPI_NSS_Soft;
SPI_Init(SPI2, &SPI_InitStruct);
SPI_Cmd(SPI2, ENABLE);
GPIOB->BSRR = GPIO_Pin_12;                  //Disable SPI slave

GPIO Config:
GPIO_InitTypeDef GPIO_InitStruct;
//Clock providing for SPI peripheral
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

//GPIO config for SCK and MOSI pin
GPIO_InitStruct.GPIO_Pin = (GPIO_Pin_13 | GPIO_Pin_15);
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);

//GPIO config for MISO pin
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_14;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStruct);

//GPIO config for NSS pin
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);

SPI Transfer:
uint8_t SPI_ByteTransfer(uint8_t data)      {
    while(!((SPI2->SR) & SPI_I2S_FLAG_TXE));            //Wait for data transmitted
    SPI_I2S_SendData(SPI2, data & 0xFF);                //Send data to TX buffer
    while(!((SPI2->SR) & SPI_I2S_FLAG_RXNE));           //Wait for data received
    data = SPI_I2S_ReceiveData(SPI2);
    return data;
}

MRF24J40 Write and Read register functions:
void MRF24J40_WriteShortAddrReg(uint8_t addr, uint8_t data)         {
    addr = (addr << 1) | 0x01;              //MSB = 0 for short, LSB = 1 for writing
    GPIOB->BRR = GPIO_Pin_12;               //Enable SPI slave
    SPI_ByteTransfer(addr);
    SPI_ByteTransfer(data);
    while(SPI2->SR & SPI_I2S_FLAG_BSY);     //Wait for bus free
    GPIOB->BSRR = GPIO_Pin_12;              //Disable SPI slave
}

uint8_t MRF24J40_ReadShortAddrReg(uint8_t addr)         {
    uint8_t data;
    addr <<= 1;                            //MSB = 0 for short, LSB = 0 for reading
    GPIOB->BRR = GPIO_Pin_12;              //Enable SPI slave
    data = SPI_ByteTransfer(addr);
    while(SPI2->SR & SPI_I2S_FLAG_BSY);    //Wait for bus free
    GPIOB->BSRR = GPIO_Pin_12;             //Disable SPI slave
    return data;
}

A:

As SPI is a synchronous interface, data is received from the slave at the same time as data is transmitted by the master.
In your receive function data is received from the slave while sending the address byte. The slave does not know what register you want to access when it shifts out the first byte as the transmit of the address byte is still undergoing.
Try to add a dummy write (e.g. 0x00) after sending the address byte to enable the slave to shift out the requested data:
uint8_t MRF24J40_ReadShortAddrReg(uint8_t addr)         {
    uint8_t data;
    addr <<= 1;                            //MSB = 0 for short, LSB = 0 for reading
    GPIOB->BRR = GPIO_Pin_12;              //Enable SPI slave
    SPI_ByteTransfer(addr);                //Send address byte and discard received data
    data = SPI_ByteTransfer(0x00);         //Send dummy byte and receive requested data
    while(SPI2->SR & SPI_I2S_FLAG_BSY);    //Wait for bus free
    GPIOB->BSRR = GPIO_Pin_12;             //Disable SPI slave
    return data;
}


Q:

Azure. How to deploy custom file referenced by DSC

I'm building an Azure RM Template that will install DSC on a target VM. DSC must use a .bacpac file. How can I upload that file to a target VM? How can I make it to be downloaded by target VM from GitHub and placed on a specific folder?
The DSC configuration looks like this:
https://github.com/PowerShell/xDatabase/blob/dev/Examples/Sample_xDatabase.ps1

A:

Something like this:
Import-DscResource -ModuleName PSDesiredStateConfiguration,xPSDesiredStateConfiguration,xDatabase

Node $nodeName
{
    LocalConfigurationManager
    {
        RebootNodeIfNeeded = $true
    }

    xRemoteFile BacPacPackage
    {
        Uri             = "https://github.com/url_to_your_bacpac"
        DestinationPath = "c:\where_to_put_it"
        MatchSource     = $false
    }

    xDatabase DeployBacPac
    {
        Ensure = "Present"
        SqlServer = $nodeName
        SqlServerVersion = $SqlServerVersion
        DatabaseName = $DatabaseName
        Credentials = $credential # credentials to access SQL
        BacPacPath = "c:\path_from_previous command"
        DependsOn = "[xRemoteFile]BacPacPackage"
    }
}


Q:

Not fetching the details in jsp

        Board Name

        <input type="text" name="bName" id="bName"  size="40" value="" class="inputbox required" maxlength="50" style="border: thin solid #C1C1C1; width: 235px;height: 40px;"/>

function UpdateboardDetails(){

    stocksubmit=true;
    var boardId=document.getElementById("boardId").value;
    var bName=document.getElementById("bName").value;

    }

I am trying to fetch the value of input id:'bname'. but it is showing null. please help

A:

If you can use JQuery use this
        var boardId=$("#boardId").val();
        var bName=$("#bName").val();


Q:

No access permission error with npm global install on docker image

I'm trying to build a docker image with a global install of firebase-tools and angular-cli.
I'm building the same image for two versions of node: 6.x (LTS boron) and v8.x (latest alpine). Locally, both images build fine, but when I try to build in docker hub only the v6.x builds successfully. With the v8.x it gets trapped in the access permissions for undefined and nobody user. I'm already using the root user (USER root), since without this setting (or using USER node) both images fail to build.
This is my Dockerfile:
FROM node:latest

USER root

RUN npm install --quiet --no-progress -g @angular/cli@latest firebase-tools
RUN npm cache clean --force

And this is the output:
Step 4/5 : RUN npm install --quiet --no-progress -g @angular/cli@latest firebase-tools

 ---> Running in fce3da11b04e

 npm WARN deprecated node-uuid@1.4.8: Use uuid module instead
 /usr/local/bin/firebase -> /usr/local/lib/node_modules/firebase-tools/bin/firebase
 /usr/local/bin/ng -> /usr/local/lib/node_modules/@angular/cli/bin/ng

> node-sass@4.5.3 install /usr/local/lib/node_modules/@angular/cli/node_modules/node-sass
> node scripts/install.js

Unable to save binary /usr/local/lib/node_modules/@angular/cli/node_modules/node-sass/vendor/linux-x64-57 : { Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/@angular/cli/node_modules/node-sass/vendor'
  at Object.fs.mkdirSync (fs.js:890:18)
  at sync (/usr/local/lib/node_modules/@angular/cli/node_modules/mkdirp/index.js:71:13)
  at Function.sync (/usr/local/lib/node_modules/@angular/cli/node_modules/mkdirp/index.js:77:24)
  at checkAndDownloadBinary (/usr/local/lib/node_modules/@angular/cli/node_modules/node-sass/scripts/install.js:111:11)
  at Object.<anonymous> (/usr/local/lib/node_modules/@angular/cli/node_modules/node-sass/scripts/install.js:154:1)
  at Module._compile (module.js:569:30)
  at Object.Module._extensions..js (module.js:580:10)
  at Module.load (module.js:503:32)
  at tryModuleLoad (module.js:466:12)
  at Function.Module._load (module.js:458:3)

errno: -13,
code: 'EACCES',
syscall: 'mkdir',
path: '/usr/local/lib/node_modules/@angular/cli/node_modules/node-sass/vendor' }

> grpc@1.3.8 install /usr/local/lib/node_modules/firebase-tools/node_modules/grpc > node-pre-gyp install --fallback-to-build --library=static_library
node-pre-gyp ERR! Tried to download(undefined): https://storage.googleapis.com/grpc-precompiled-binaries/node/grpc/v1.3.8/node-v57-linux-x64.tar.gz node-pre-gyp ERR! Pre-built binaries not found for grpc@1.3.8 and node@8.1.2 (node-v57 ABI) (falling back to source compile with node-gyp)
gyp WARN EACCES user "undefined" does not have permission to access the dev dir "/root/.node-gyp/8.1.2" gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp"
gyp WARN EACCES user "nobody" does not have permission to access the dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp/8.1.2" gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp"
gyp WARN EACCES user "nobody" does not have permission to access the dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp/8.1.2" gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp"
gyp WARN EACCES user "nobody" does not have permission to access the dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp/8.1.2" gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp"
gyp WARN EACCES user "nobody" does not have permission to access the dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp/8.1.2" gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/firebase-tools/node_modules/grpc/.node-gyp"
(infinite loop)

A:

The problem is because while NPM runs globally installed module scripts as the nobody user, which kinds of makes sense, recent versions of NPM started setting the file permissions for node modules to root. As a result module scripts are no longer allowed to create files and directories in their module.
See discussion in NPM issue #3849, for some references.
A simple workaround, which makes sense in a docker environment, is to set the NPM default global user back to root, like so:
npm -g config set user root

After which you shouldn't have any more EACCES errors.

A:

Use the --unsafe-perm flag:
npm install --quiet --no-progress --unsafe-perm -g @angular/cli@latest firebase-tools

I think that's still better than setting the npm user permanently to root. You can use --unsafe-perm only with the packages which cause problem

A:

I was able to get it working by changing the default npm-global directory.
This is my dockerfile now:
FROM node:latest
USER node

RUN mkdir /home/node/.npm-global
ENV PATH=/home/node/.npm-global/bin:$PATH
ENV NPM_CONFIG_PREFIX=/home/node/.npm-global

RUN npm install --quiet --no-progress -g @angular/cli@latest firebase-tools
RUN npm cache clean --force


Q:

Between *variable sharing* and *command substitution*, which method is better for returning a value from another bash script

Suppose I have

a bash script A.bash, which calls another script B.bash.
B.bash calculates a variable VAR.
Now I would like B.bash to return VAR to the calling script.

I can export VAR in B.bash and source B.bash in A.bash. Another solution is to echo VAR in B.bash, execute B.bash in A.bash and get the the return value as R=$(B.bash).
Does it make sense? Which option is better? Are there any alternatives?

A:

Little introduction
Tracking forks (like $())  as they consume lot more ressource than normal (sequential) execution, if you know which variable has to be modified in advance, you'll better to use local definition around your whole script and use function instead of having to make file access between commands:
#!/bin/bash
# There is the `A` script

local VAR

function B() {
    read -a VAR </proc/uptime
}

B
echo $VAR
sleep 1
B
echo $VAR

could output something like:
1610291.39
1610292.39

with time to access /bin/sleep could be less than 1/100th of second.
A little demonstration:
local V1
B1() {
    read -a V1 </proc/uptime
}
B1 ;echo $V1 ;for i in {0..10000} ;do B1 ;done ;echo $V1
1610843.78
1610844.38
printf "%d 1/100th of sec\n" $((161084438-161084378))
60 1/100th of sec

I could set 10000x my variable in 60/100 seconds, while
B2() {
    local var
    read -a var </proc/uptime
    echo $var
}
V2=$(B2);echo $V2;for i in {0..10000};do V2=$(B2);done;echo $V2
1611121.33
1611168.01
printf "%d 1/100th of sec\n" $((161116801-161112133))
4668 1/100th of sec

May take more time!
If you really wanna keep all in separated file, as @alok suggested, you could source them, as this will not fork:
echo >/dev/shm/B3 'read -a V3 </proc/uptime'
. /dev/shm/B3 ;echo $V3 ; for i in {0..10000};do . /dev/shm/B3;done;echo $V3
1612187.89
1612188.79
printf "%d 1/100th of sec\n" $((161218879-161218789))
90 1/100th of sec

This is lot quicker than having to fork for each loop, but accessing to function via filesystem (even RAM pseudo filesystem, without access time) take some time.
My answer

Yes, it make sense, while $(...) or ... stay usefull for returning result of a binary command or other strong script with a lot of bariables you won't inherit.
Depending on your need and who wrote each parts... paralelism... other factors...
Other alternatives, for dynamic command, not really, but don't miss to use built-ins like mapfile or read -a when you can.

Disclaimer
This concern bash only! If you want your script to be portable (even if bash is already ported on most significant os), you have to not use array variables and try your script with zsh or dash.


Q:

Submitting data from a form to django view

When I open the html file it displays as expected and when I enter data in the text box and submit, It redirects me to localhost/myapp/output/ but why is the data I enter in the text box not submitted for example like localhost/myapp/output/data_I_submitted
My basic html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>db app</title>
</head>
<body>
{% csrf_token %}
<form action="output/" method="post" name="Input">
Data : <input type="text" name="text">
<input type="submit" value="submit">
</form>
</body>
</html>

In my app.urls file:
urlpatterns = patterns('',
    url(r'^$',views.index),
    url(r'^output/(?P<text>\w+)/$',views.return_data)
)

Finally the view:
def return_data(request,text):
    return HttpResponse('entered text ' + text)

A:

If your goal is only getting the text on the form:
change your view to
def return_data(request):
    return HttpResponse('entered text:' + request.POST['text'])

edit your urls
urlpatterns = patterns('',
    url(r'^$', views.index),
    url(r'^output/$', views.return_data)
)

and your template
<form action="output/" method="post">
{% csrf_token %}
...
</form>


Q:

What is the difference between Views and Materialized Views in Oracle?

What is the difference between Views and Materialized Views in Oracle?

A:

Materialized views are disk based and are updated periodically based upon the query definition.
Views are virtual only and run the query definition each time they are accessed.

A:

Views
They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.
The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.
Materialized views
They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.
In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.

Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.
Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.

Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.

A:

A view uses a query to pull data from the underlying tables.
A materialized view is a table on disk that contains the result set of a query.
Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH has been in place since at least Oracle 10.


Q:

Ошибка во второй строке, из-за этого не работает код

a = ('Али 10.03','Гюнай 12.03','Фарид 15.03')
a.append("Васиф 28.03")
del a[1]
print(a)

Помогите пожалуйста, очень срочно

A:

.append - метод питон - листов. Чтобы иметь возможность им пользоваться с а, а должен быть листом. Таким образом
a = ['Али 10.03','Гюнай 12.03','Фарид 15.03']

Первая строка вашего кода


Q:

Як правильно робити морфологічний розбір слова?

Підскажіть, будь ласка, як правильно зробити морфологічний розбір слова. Дякую

A:

Усе залежить від частини мови.
Наприклад, інформацію брала із Острів знань:

Іменник

Початкова форма.

На яке питання відповідає в реченні.

Істота чи неістота.

Власна чи загальна назва.

Конкретне чи абстрактне значення, збірне, речовинне.

Рід, число, відмінок, відміна, група (тверда, м’яка, мішана).

Спосіб творення (якщо це похідне слово).

Правопис.

Синтаксична роль у реченні.

Прикметник

Початкова форма.

На яке питання відповідає в реченні.

Розряд за значенням: якісний, відносний чи присвійний.

Форма: повна чи коротка.

Для якісних – ступінь порівняння.

Група: тверда або м’яка.

Рід, число, відмінок.

Спосіб творення, якщо слово похідне.

Особливості правопису.

Синтаксична роль у реченні.

Числівник

Початкова форма.

На яке питання відповідає в реченні.

Розряд за значенням: кількісний (дробовий, збірний), порядковий.

Група за будовою: простий, складний чи складений.

Рід, число (якщо є), відмінок.

Спосіб творення, якщо слово похідне.

Правопис.

Синтаксична роль у реченні.

Займенник

Початкова форма.

На яке питання відповідає

Розряд за значенням: особовий, зворотний, присвійний, вказівний, означальний, питальний, відносний, неозначений, заперечний.

Рід, число, відмінок.

Спосіб творення.

Синтаксична роль.

Дієслово

Початкова форма.

На яке питання відповідає.

Дієслівна форма: інфінітив, особова форма, родова, безособові дієслова, дієслова на –но, -то, дієприкметник, дієприслівник.

Перехідне чи неперехідне.

Вид.

Спосіб: дійсний, умовний, наказовий.

Час, проста чи складена форма.

Якщо теперішній чи майбутній час, визначити особу та число.

Якщо минулий час, умовний спосіб, то треба визначити рід в однині.

Дієвідміна.

!!! Є така схема розбору наступних форм дієслова (однак нижче подаю чіткішу):
Якщо дієприкметник, то назвати такі ознаки: активний чи пасивний, час, вид, рід, число, відмінок.
Якщо дієприслівник, то назвати такі граматичні ознаки: час, вид.

Особливості творення.

Правопис.

Синтаксична роль.

Прислівник

На яке питання відповідає.

Розряд за значенням: означальний, обставинний (місця, часу…).

Для якісно-означальних – ступінь порівняння.

Спосіб творення, від якої частини мови утворений.

Правопис.

Cинтаксична роль.

Прийменник

Службова частина мови.

Група за походженням: первинний, вторинний.

Група за будовою: простий, складний, складений.

З якою відмінковою формою вживається.

Сполучник

Службова частина мови.

Розряд: сурядний, підрядний.

За вживанням: одиничний, парний, повторюваний.

Група за будовою: простий, складний, складений.

Правопис.

Синтаксична роль.

Частка

Службова частина мови.

Група за значенням і вживанням.

Вигук

Окрема частина мови, що виражає емоції. Волевиявлення, звукові реакції мовця, етикет.

Розряд за значенням: емоційний, спонукальний, звуконаслідування, звертання до тварин, мовний етикет.

Роль у реченні, розділові знаки при вигуку.

Щодо дієприкметника та дієприслівника, раджу сайт http://online-hw.com/content/s_t-pravila/rozbori.html, де подано:

Морфологічний розбір дієприкметника

Особлива форма дієслова.

Початкова форма (дієприкметник у називному відмінку чоловічого роду однини).

Активний чи пасивний.

Вид (доконаний, недоконаний).

Час (теперішній, минулий).

Число.

Рід (в однині).

Відмінок.

Синтаксична роль.

Зразок
Мамин хліб був обсипаний зернятками тмину.
Обсипаний – дієприкметник, поч. ф. обсипаний, пасивний, доконаний вид, минулий час, однина, чоловічий рід, називний відм., присудок.

Морфологічний розбір дієприслівника

Особлива форма дієслова.

Вид (доконаний, недоконаний).

Час (теперішній, минулий).

Перехідність (перехідний, неперехідний).

Синтаксична роль.

Зразок
Білий димок, хвилюючись, здіймається догори.
Хвилюючись – дієприслівник, недоконаний вид, теперішній час, неперехідний, обставина.


Q:

How to grep for a pattern in multiple files while excluding commented lines

I have a bunch of LaTeX files that I want to search using grep pattern *.tex -n --color=always. It's important that I see:

The file's name that matched
The line number of the match
The full line, with the matched pattern highlighted

Furthermore, sometimes the pattern needs to be a full word match, so the command becomes grep pattern *.tex -n -w --color=always
I would like to modify this command to exclude commented lines in my *.tex files, which start with the % character. I am not interested in matches in comments.
Is this possible?

A:

May be you can try the following command:
grep -n -v --color=always '^%' *.tex | grep content

EXPLANATION

The first grep invocation excludes (-v) line starting with % (regex ^% matches % at the start of the line (^))
The output of the first grep invocation is passed as input to the second grep invocation
The second grep invocations includes only rows matching with your filter pattern (you can add -w option if you need it).

I hope this can help you!


Q:

Dragula on drag the nested image doesn't stay styled

Codepen here:
http://codepen.io/jasonsawtelle/pen/jqbeXd
//HTML

//SCSS
//Dragula
.gu-mirror{position:fixed!important;margin:0!important;z-index:9999!important;opacity:.8;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";filter:alpha(opacity=80)}.gu-hide{display:none!important}.gu-unselectable{-webkit-user-select:none!important;-moz-user-select:none!important;-ms-user-select:none!important;user-select:none!important}.gu-transit{opacity:.2;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";filter:alpha(opacity=20)}

// Example
#drag_container{
    display: flex;
    div{
        img{
            height: 100px;
        }
    }
}

//JS
dragula([document.querySelector('#drag_container')])

It's a basic setup and Dragula is working, but when I drag a div, the contained, css resized image is popping to full-size during the drag event.

A:

You should set .gu-mirror img to width: 100px; to achieve what you want. See the CodePen for the result.
.gu-mirror is the div added by the Dragula plugin to mirror the selected element to drag somewhere else.