text:
Q: What's wrong with ADT constructor for SquareMatrix? This project I am writing in order to create a Square Matrix ADT object has a problem with the constructor (not the default constructor). I have traced the problem back to the constructor but I cannot figure out what is wrong with it which makes it crash everytime I try to run my test in main.cpp.
I usually get an error that say something along the lines "Thread 1: EXC_BAD_ACCESS: ..." and the console usually says "(11db)"
Does anyone have any ideas on what might be causing all the problems?
This is the header file:
#include <iostream>
#include <vector>
using namespace std;

#ifndef SquareMatrix_h
#define SquareMatrix_h

class SquareMatrix {
private:
    vector<vector<double>> numMatrix;
public:
     SquareMatrix();
     SquareMatrix(vector<vector<double>>& v2d);
     double getValue(int x, int y);
     void setValue(int x, int y, double value);
     friend SquareMatrix operator * (SquareMatrix m1, SquareMatrix m2);
     friend SquareMatrix operator - (SquareMatrix m1, SquareMatrix m2);
     friend ostream& operator <<(ostream &out, SquareMatrix m);
};

#endif /* SquareMatrix_h */

This is my SquareMatrix.cpp file: (The constructor that I believe isn't working is the second function in the code: SquareMatrix::SquareMatrix(vector>& v2d) {...)
#include "SquareMatrix.h"
#include <iostream>

using namespace std;

SquareMatrix::SquareMatrix() {
    numMatrix.clear();
    for(int i = 0; i < 10; i++) {
        vector<double> initial;
        for(int j = 0; j < 10; j++) {
            initial.push_back(0.0);
        }
        numMatrix.push_back(initial);
    }
}

SquareMatrix::SquareMatrix(vector<vector<double>>& v2d) {
    bool flagSize = true;

    for(int i = 0; i < v2d.size(); i++) {
        if(v2d[i].size() != v2d.size()) {
            flagSize = false;
            break;
        }
    }

   if(flagSize) {
        numMatrix.clear();
        for(int i = 0; i < v2d.size(); i++) {
            vector<double> initial;
            for(int j = 0; j < v2d[i].size(); i++) {
                initial.push_back(v2d[i][j]);
            }
            numMatrix.push_back(initial);
        }
    } else {
        numMatrix.clear();
        for(int i = 0; i < 10; i++) {
            vector<double> initial;
            for(int j = 0; j < 10; j++) {
                initial.push_back(0.0);
            }
             numMatrix.push_back(initial);
        }
    }
}

double SquareMatrix::getValue(int x, int y) {
    if((x < numMatrix.size()) && (y < numMatrix.size()) && (x >= 0) && (y >= 0)) {
        return numMatrix[x][y];
    }
    return 0;
 }

void SquareMatrix::setValue(int x, int y, double value) {
    if((x < numMatrix.size()) && (y < numMatrix.size()) && (x >= 0) && (y >= 0)) {
        numMatrix[x][y] = value;
    }
}

SquareMatrix operator * (SquareMatrix m1, SquareMatrix m2) {
    if(m1.numMatrix.size() == m2.numMatrix.size()) {

        vector<vector<double>> result;
        for(int i = 0; i < m1.numMatrix.size(); i++) {
            vector<double> initial;
            for(int j = 0; j < m1.numMatrix.size(); j++) {
                initial.push_back(0);
            }
            result.push_back(initial);
        }

        for(int i = 0; i < m1.numMatrix.size(); i++) {
            for(int j = 0; j < m1.numMatrix.size(); j++) {
                result[i][j] = 0;
                for (int a = 0; a < m1.numMatrix.size(); a++) {
                    result[i][j] += m1.numMatrix[i][a] + m2.numMatrix[a][j];
                }

            }
        }

        return SquareMatrix(result);
    }

    return SquareMatrix();
}

SquareMatrix operator - (SquareMatrix m1, SquareMatrix m2) {
    if(m1.numMatrix.size() == m2.numMatrix.size()) {
           vector<vector<double>> result;
           for(int i = 0; i < m1.numMatrix.size(); i++) {
                vector<double> initial;
                for(int j = 0; j < m1.numMatrix[i].size(); j++) {
                     double pushNum = (m1.getValue(i,j) - m2.getValue(i,j));
                     initial.push_back(pushNum);
              }
              result.push_back(initial);
          }
          return SquareMatrix(result);
      }
      return SquareMatrix();
  }

 ostream& operator << (ostream &out, SquareMatrix m) {
    out << "(";
    for (int i = 0; i < m.numMatrix.size(); i++) {
         for (int j = 0; j < m.numMatrix.size(); j++) {
             out << " " << m.numMatrix[i][j];
             if(j != (m.numMatrix.size() - 1)) {
                 out << ", ";
             }
        }
    }
     out << ")";

    return out;
}

Then this is the main.cpp that I am using to test the SquareMatrix ADT object:
#include "SquareMatrix.h"
#include <iostream>
#include <random>
#include <ctime>
#include <vector>

using namespace std;

int main() {
    srand(time(NULL));

    vector<vector<double>> m1;
    vector<vector<double>> m2;
    int size = 0;

    cout << "Enter the size of the Square Matrix: ";
    cin >> size;

    for (int i = 0; i < size; i++) {
        vector<double> in1;
        vector<double> in2;
        for (int j = 0; j < size; j++) {
            in1.push_back(rand() % 100);
            in2.push_back(rand() % 100);
        }
        m1.push_back(in1);
        m2.push_back(in2);
    }

    SquareMatrix res1 = SquareMatrix(m1);
    SquareMatrix res2 = SquareMatrix(m2);

    cout<< "\nMatrix 1: " << endl;
    cout << res1 << endl;

    cout<< "\nMatrix 2: " << endl;
    cout << res2 << endl;

    SquareMatrix mult = res1*res2;
    cout << "\nMatrix1 * Matrix 2: " << endl;
    cout << mult << endl;

    SquareMatrix min1_2 = res1 - res2;
    cout << "Matrix1 - Matrix 2: " << endl;
    cout << min1_2 << endl;

    SquareMatrix min2_1 = res2 - res1;
    cout << "Matrix2 - Matrix 1: " << endl;
    cout << min2_1 << endl;

    return 0;
}

Any help you could give would be appreciated. :)

A: As pointed out in the comments, you problem is a simple typo in one of your nested loops. However, I'd like to add some recommendations to make your code less error prone (and also more readable).
Firstly, when iterating over all elements of a vector, unless you need an index for something else, you should be using a range-based for-loop. In your code, you might replace the check for square size with the following:
for (const vector<double>& vec: v2d){
    if (vec.size() != v2d.size()){
        flagSize = false;
        break;
    }
}

This expresses your intent a little more clearly, and, more importantly, prevents you from accidentally reading from/writing to a location out of your vector's bounds (accidentally typing <= instead of just < happens to the best of us).
Secondly, the two nested loops (that contained your error) can be replaced with a simple copy assignment (numMatrix = v2d; reference). Again, this expresses your intent in addition to being a whole lot shorter. No need to reinvent the wheel with functions like these.
The contents of the else-branch of the surrounding if-statement can also be replaced with a call to assign (the first overload listed on the page, use like numMatrix.assign(10, vector<double>(10, 0.0))). Like before, clearer expression of intent and avoidance of index errors.
Finally, the parameter in this constructor can be a const reference instead of a normal one since you do not alter its contents in any way (and, given this, it should be const).
You might wonder why "expression of intent" is relevant, or what it even means in this context. Essentially, it's all about making what you're trying to do immediately obvious to any reader. This is more important in large projects with many contributors but it is helpful even when debugging small applications like this one. You seem to be learning still, but I strongly believe it's a good thing to keep in mind from the beginning. After all, many of these changes also make for briefer code, making it that much easier for others to help you if you run into a problem.
I realize this left the scope of the original question somewhat, but I hope you find this helpful nonetheless.


text:
Q: I am using docx library and when i use docx.document('path/file.docx') it gives the error:module 'docx' has no attribute 'Document' I am using the docx library ato read word documents
:
import docx
doc = docx.Document('C:/Users/gourabd838/Downloads/Initial Report with Scoring/INVESTIGATION REPORT.docx')

it gives the following error :"module 'docx' has no attribute 'Document'"
I have no clue why and am not getting any work around.

A: This is generally caused by one of the following:

*

*You have installed the legacy docx package rather than the python-docx package.

*You have named your project docx and because it is in the local directory, it is receiving the docx name rather than the python-docx installation.
The predecessor (almost a decade ago now) to python-docx was called docx. They both install a docx root package, but the former is installed with pip install docx rather than the now proper pip install python-docx.
If you made this mistake, you need to uninstall the docx package and then install (or reinstall) python-pptx:
pip uninstall docx
pip install -U python-docx

If you have named the module you are developing docx you just need to name it something else (like rename the .py file if it is single-module or the directory if it is a package).

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get database from development to production? What is the best way to dump my development database structure and deploy it to a production server?
Im using capistrano deployment for rails app

*

*how would one migrate changes in development database structure automatic with each cap deploy?

A: You can add a migration that executes your schema dump. Then use migrations to make changes after that.
Then, you'll execute cap deploy:migrations to deploy your code and run your migrations.


text:
Q: sub-family of cover with compact closure is still a cover? Here is a problem about existence of exhaustion of a manifold:

Denote manifold as $M$, with Hausdorff, second-countability and locally Euclidean property.
  Show there exists a exhaustion of $M$.

And first part of proof is here:

Since $M$ is second countable, there is a countable basis of the topology of $M$. Out of this countable sequence of open sets, we pick those that have compact closure, and denote them by $Y_1,Y_2,....$ Since $M$ is locally Euclidean it is easy to see that $\mathcal{Y}={Y_i}$ is a open cover of $M$.

And I'm confuse about the last part. How can locally Euclidean property grant $\mathcal{Y}$ be a sub-cover? I try to PBR but fail. Can anyone get me some hints?

A: All we have to show is that every point of $M$ is contained in some $Y_i\in \mathcal Y$. So let $x\in M$ be arbitrary. Because $M$ is locally Euclidean, there is some open subset $U\subseteq M$ containing $x$ and a homeomorphism $\phi\colon U\to \widehat U$, where $\widehat U$ is an open subset of $\mathbb R^n$. Let $\widehat x = \phi(x)$, and choose $r$ small enough that $B_{2r}(\widehat x)\subseteq \widehat U$. Then $\overline B_r(\widehat x)$ is compact and contained in $\widehat U$. Define
\begin{align*}
K & = \phi^{-1}\big(\overline B_r(\widehat x)\big),\\
W & = \phi^{-1}\big(B_r(\widehat x)\big).
\end{align*}
Since $\phi$ is a homeomorphism, $W$ is an open neighborhood of $x$ contained in the compact set $K$.
Now there is a set $Y$ in our original basis such that $x\in Y \subseteq W$. Because $\overline Y$ is a closed subset of the compact set $K$, it is compact. Thus $Y$ is one of the sets in $\mathcal Y$.


text:
Q: FFmpeg: Read profile level information from mp4 I have a mp4 file and need the profile level of it. FFmpeg says, it has baseline profile, which is what I need, but I need also the level.
Here is what I get from FFmpeg:
ffmpeg version 0.8, Copyright (c) 2000-2011 the FFmpeg developers
  built on Jul 20 2011 13:32:19 with gcc 4.4.3
  configuration: --enable-gpl --enable-version3 --enable-nonfree --enable-postproc --enable-libfaac --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libtheora --enable-libvorbis --enable-libx264
  libavutil    51.  9. 1 / 51.  9. 1
  libavcodec   53.  7. 0 / 53.  7. 0
  libavformat  53.  4. 0 / 53.  4. 0
  libavdevice  53.  1. 1 / 53.  1. 1
  libavfilter   2. 23. 0 /  2. 23. 0
  libswscale    2.  0. 0 /  2.  0. 0
  libpostproc  51.  2. 0 / 51.  2. 0
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'test-show.mp4':
  Metadata:
    major_brand     : f4v
    minor_version   : 0
    compatible_brands: isommp42m4v
    creation_time   : 2012-03-21 16:00:00
  Duration: 00:56:07.40, start: 0.000000, bitrate: 2004 kb/s
    Stream #0.0(eng): Video: h264 (Baseline), yuv420p, 854x480 [PAR 1:1 DAR 427:240], 1904 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc
    Metadata:
      creation_time   : 2012-03-21 16:00:00
    Stream #0.1(eng): Audio: aac, 48000 Hz, stereo, s16, 96 kb/s
    Metadata:
      creation_time   : 2012-03-21 16:00:00
At least one output file must be specified

Is there any option other than -i I can use to get the level information?

A: You could use MP4Box with option -info for this kind of output:
Track # 2 Info - TrackID 2 - TimeScale 25000 - Duration 01:29:42.160
Media Info: Language "Undetermined" - Type "vide:avc1" - 134554 samples
MPEG-4 Config: Visual Stream - ObjectTypeIndication 0x21
AVC/H264 Video - Visual Size 1280 x 720 - **Profile High @ Level 3.1**
NAL Unit length bits: 32
Pixel Aspect Ratio 1:1 - Indicated track size 1280 x 720
Synchronized on stream 1

A: Try ffprobe -show_streams.
ffprobe is bundled with FFmpeg and gives lots of information about video files including level information, e.g.:
$ ffprobe -loglevel error -show_streams Test.mp4
[STREAM]
index=0
codec_name=h264
codec_long_name=H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
codec_type=video
codec_time_base=1001/48000
codec_tag_string=avc1
codec_tag=0x31637661
width=704
height=400
has_b_frames=0
sample_aspect_ratio=N/A
display_aspect_ratio=N/A
pix_fmt=yuv420p
level=51                 <== level!
timecode=N/A
is_avc=1
nal_length_size=4
id=N/A
r_frame_rate=24000/1001
avg_frame_rate=1384898760/57761819
time_base=1/44100
start_time=0.000000
duration=6548.959070
bit_rate=701946
nb_frames=157018
nb_read_frames=N/A
nb_read_packets=N/A
TAG:creation_time=2006-08-17 18:14:49
TAG:language=eng
TAG:handler_name=
[/STREAM]

A: ffprobe with show_entries command should be faster, and it has more options to show only relevant data and to filter only video stream.
to filter only video (add also :0 to filter only first video stream)
ffprobe -v error -select_streams v:0 -show_entries stream=level -of default=noprint_wrappers=1 <filepath>

e.g. OUTPUT:
  level=50

to output only the value (add :nokey=1):
ffprobe -v error -select_streams v:0 -show_entries stream=level -of default=noprint_wrappers=1:nokey=1 <filepath>

e.g. OUTPUT:
  50

to output both Profile and Level in one go:
ffprobe -v error -select_streams v:0 -show_entries stream=profile,level -of default=noprint_wrappers=1 <filepath>

e.g. OUTPUT:
  profile=High
  level=50

to output in json format:
ffprobe -v error -select_streams v:0 -show_entries stream=profile,level -of json <filepath>

e.g. OUTPUT:

{
    "programs": [

    ],
    "streams": [
        {
            "profile": "High",
            "level": 41
        }
    ]
}

in a MS batch file (as fake function):
call :ffprobeGetFormatProfile ffprobe.exe file.mp4 txtFormat
:ffprobeGetFormatProfile <exe> <infile> <outStr>
echo.
echo FILE: %2

set tmpProfile=
set tmpLevel=
for /f "usebackq delims== tokens=1-2" %%a in (`%~s1 -v error -select_streams v:0 -show_entries stream^=profile^,level -of default^=noprint_wrappers^=1 %2`) do (
    if /I %%a == profile set tmpProfile=%%b
    if /I %%a == level set tmpLevel=%%b
)
if not defined tmpLevel set tmpLevel=??
echo on
set %3=%tmpProfile%@%tmpLevel:~0,1%.%tmpLevel:~1%
@echo off

exit /b %errorlevel%

e.g. OUTPUT (in a variable txtFormat passed as 3rd argument):
  High@4.1

You can get some more ideas from ffmpeg.org - Tips

A: try the following to get the more detailed output in json
$ ffprobe -print_format json -show_streams -show_format <filepath>


text:
Q: NFS Server on OSX - squash options Is it possible to have no_root_squash option enabled on an OSX Yosemite NFS server?
I'm running boot2docker on OS X in Yosemite via Virtualbox (boot2docker 1.8 - from Docker Toolbox).
Due to performance issues with large mounted host-volumes, I thought about giving NFS a shot!
This is my /etc/exports
/Users/myuser -mapall=myuser:staff 192.168.99.100

This is my /etc/nfs.conf
nfs.server.mount.require_resv_port = 0

And that script is executed in boot2docker-vm
#!/bin/sh

sudo umount /Users

sudo mkdir -p /Users/myuser

sudo /usr/local/etc/init.d/nfs-client start
sudo mount 192.168.99.1:/Users/myuser /Users/myuser -o rw,async,noatime,rsize=32768,wsize=32768,proto=tcp,nfsvers=3

And inside a container I use a bash script that reads the UID and GID of a mounted volume and changes the UID and GID of a non-privileged user in order to allow read/write operations.
So far so good. But sometimes I would need to change file permissions, however sudo chmod/chown don't work because all operations are matched against my local (unprivileged) user on OSX. NFS on Linux is supporting the option no_root_squash which would perfectly solve my problems, but I'm afraid it's it's not available on OSX Yosemite.
And it's not possible to use -mapall along with -maproot.
And no, I don't want to map against root on OS X too :)
Any ideas?


text:
Q: Open button dropdown programatically, but does something weird to the "caret" First of all, here is an example of the problem I'm getting:
Here is an example of the problem I'm getting:
http://www.bootply.com/fUELEN22ww
If you click the down arrow, it works fine.... but when you trigger it by clicking on Select Room, the down arrow gets extra wide.
At first I thought maybe I was overwriting a class, but I've managed to get it happening with a fresh install on the above bootply.
I've been going round and round in circles with this one, and I still can't see whats causing it.
Anyone got any suggestions? Basically, I just need the dropdown to open upon clicking on the Select Room option)
Thanks!

A: When you click on the "Select Room" button, it inserts a

 element between the two buttons in the .btn-group. This causes the CSS rule below to no longer apply to the .dropdown-toggle button, because the .dropdown-toggle is no longer directly next to a .btn. The default 12px of padding is then applied instead of 8px.
.btn-group>.btn+.dropdown-toggle {
    padding-right: 8px;
    padding-left: 8px;
}

Adding this rule to your css should resolve the issue.
.btn-group>.dropdown-toggle {
    padding-right: 8px;
    padding-left: 8px;
}


text:
Q: Seaborn Boxplot showing dashes rather than data I have been utilizing Seaborn to create a boxplot, however it is returning a chart that solely shows dashes rather than the data present. If anyone can offer any advise it would be greatly appreciated.
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt

    UserCount = list([407, 298, 252, 338, 174, 133, 1816, 1880, 1745, 7684, 4993, 4366, 1439, 1418, 1126, 2286, 2411, 1969, 774, 739, 649])
    Function = list(["Country Risk", "Country Risk","Country Risk", "News", "News", "News", "Search", "Search", "Search", "Entity Page", "Entity Page", "Entity Page", "Corporate Hierarchy", "Corporate Hierarchy", "Corporate Hierarchy", "Financials", "Financials", "Financials","Portfolio", "Portfolio", "Portfolio"])
    Month = list(["October", "November", "December", "October", "November", "December", "October", "November", "December", "October", "November", "December", "October", "November", "December", "October", "November", "December", "October", "November", "December",])

   #Created dataframe combining three lists together
   TotalUsers = pd.DataFrame({"FC Function": Function, "Month": Month, "User Count": UserCount})

   # Draw a nested boxplot to show user count by month
   sns.set(style="ticks")
   sns.boxplot(x='Month', y= 'User Count', data=TotalUsers, hue="FC Function", palette="PRGn")
   sns.despine(offset=10, trim=True)
   plt.show()

A: A box plot "shows the distribution of quantitative data", but your grouping of x='Month', y= 'User Count', hue="FC Function" correspond to single points of data in TotalUsers.  Single points of data have no distribution so no box is drawn.


text:
Q: RAD Editor Dialogs Failing with UrlRewritingNet (Telerik KB Article: "Web.config registration missing!" not helpful) I just swapped out CuteEditor for RAD Editor on my company's production site and the RAD Editor dialogs are not working - kicking the general error:
"Web.config registration missing! The Telerik dialogs require a HttpHandler registration in the web.config file..."
I thoroughly read through the KB article provided by Telerik, but I am still unable to get this resolved.
I have narrowed it down to the UrlRewritingNet assembly being used as I can comment that portion of the configuration out to get the RAD Editor working fully as desired.  However, the Telerik KB article says to modify the code that handles the requested URL. I do not have any code doing this as everything is handled through configuration and the DLL.
Do I need to modify the virtualUrl property's regex??
My production environment is on IIS6 - however, I am locally on IIS7, so I have <system.webServer> running  integrated mode in my config.  I understand this should not affect the production environment which is on IIS6..?
Here is my configuration (the urlrewritingnet configuration is in a separate configSource file which is displayed after the general web.config):
<?xml version="1.0"?>
  <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <configSections>

      <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

          <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

          </sectionGroup>
        </sectionGroup>
      </sectionGroup>
    </configSections>
    <appSettings configSource="Configuration\appsettings.config" />
    <connectionStrings configSource="Configuration\connection_strings.config" />
    <urlrewritingnet configSource="Configuration\urlrewritingnet.config" />
    <location path="admin">
      <system.web>
        <globalization requestEncoding="UTF-8" responseEncoding="UTF-8"/>
        <identity impersonate="false"/>
        <authorization>
          <deny users="?"/>
        </authorization>
      </system.web>
    </location>
    <system.web>
      <pages>
        <controls>
          <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" />
        </controls>
      </pages>
      <sessionState timeout="10"/>
      <customErrors mode="On" defaultRedirect="~/error.html"/>
      <trace enabled="true"/>
      <compilation defaultLanguage="c#" debug="false">
        <assemblies>
          <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
          <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
          <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
          <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
          <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        </assemblies>
      </compilation>
      <httpHandlers>
        <remove verb="*" path="*.asmx"/>
        <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false" />
        <add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false" />
        <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
        <add path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" validate="false" />
        <add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
        <add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
      </httpHandlers>
      <httpModules>
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="UrlRewriteModule" type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter"/>
      </httpModules>
    </system.web>
    <system.web.extensions>

    </system.web.extensions>
    <system.webServer>
      <validation validateIntegratedModeConfiguration="false"/>
      <modules>
        <remove name="ScriptModule"/>
        <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </modules>
      <handlers>
        <remove name="WebServiceHandlerFactory-Integrated"/>
        <remove name="ScriptHandlerFactory"/>
        <remove name="ScriptHandlerFactoryAppServices"/>
        <remove name="ScriptResource"/>
        <remove name="WebServiceHandlerFactory-ISAPI-2.0"/>
        <remove name="ChartImage_axd" />
        <remove name="Telerik_Web_UI_SpellCheckHandler_axd" />
        <remove name="Telerik_Web_UI_DialogHandler_aspx" />
        <remove name="Telerik_RadUploadProgressHandler_ashx" />
        <remove name="Telerik_Web_UI_WebResource_axd" />
        <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
        <add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
        <add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
        <add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
        <add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
      </handlers>
    </system.webServer>
    <system.codedom>
      <compilers>
        <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
          <providerOption name="CompilerVersion" value="v3.5"/>
          <providerOption name="WarnAsError" value="false"/>
        </compiler>
        <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
          <providerOption name="CompilerVersion" value="v3.5"/>
          <providerOption name="OptionInfer" value="true"/>
          <providerOption name="WarnAsError" value="false"/>
        </compiler>
      </compilers>
    </system.codedom>
    <runtime>
      <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
        <dependentAssembly>
          <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
      </assemblyBinding>
    </runtime>
  </configuration>

Here is the specific section for urlrewritingnet:
<urlrewritingnet rewriteOnlyVirtualUrls="true" contextItemsPrefix="QueryString" defaultPage="default.aspx" xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
  <rewrites>
    <add name="Root" virtualUrl="^~/(.*).aspx" rewriteUrlParameter="ExcludeFromClientQueryString" destinationUrl="~/rootPage.aspx?pageName=$1" ignoreCase="true"/>
  </rewrites>
</urlrewritingnet>

Is there a way to exclude Telerik.Web.UI.DialogHandler.aspx in my rewrites?
I've already set DialogHandlerUrl="~/Telerik.Web.UI.DialogHandler.aspx" in my RadEditor as indicated by another post I've come across.

A: It seems that your rewriter is catching all requests for .aspx files and the editor dialogs use .aspx extension by default. You will need to follow the last recommendation of the KB article. I have copied it here for clarity:
open the web.config file and replace Telerik.Web.UI.DialogHandler.aspx with Telerik.Web.UI.DialogHandler.axd
set the RadEditor's DialogHandlerUrl property to "~/Telerik.Web.UI.DialogHandler.axd"


text:
Q: AngularJS: How to Update ng-view using $route.reload() I have searched through a lot of questions regarding $route.reload() and I think I still have a fundamental misunderstanding of how it and Angular are actually working. I really want to understand what is actually going on (not just a quick fix) so I apologize if this question gets rather verbose.
I am trying to create an app that will allow the user to input information into a form and then use ng-view and a controller  LivePreviewController to display that form data in a "live preview" of the form which has some unique styling and other information associated with the form that the user does not input themselves.
This is very simple to do if the "live preview" is occurring on the same page as the user is inputting information using something like this
<input type="text" ng-model="form_name" />

What I would like to do is something like this.

<input type="text" ng-model="form_name" />

Then I have another page styled_form.html which is the partial view that gets displayed by the ng-view div.

Both of these pages are controlled by the same controller LivePreviewController.
There are a lot of things I imagine that I am probably doing incorrectly. First thing could be the routing. I had some issues with the routing as app is only used on one page of a multi-page website my routes are setup as follows.
var previewApp = angular.module('previewApp', ['ngRoute']);
previewApp.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .otherwise({
            redirectTo:'/styled_view.html',
            controller: 'LivePreviewController'
        });
}]);

//Controller Code

previewApp.controller('LivePreviewController', [$scope, $route, function($scope, $route){
    $scope.form_name = 'temporary name';
}]);

All of this works as expected when the form_page.html is originally loaded, but when the user changes the name in the text input the ng-view displaying my styled_form.html page is not changed. This also makes sense because the styled_form.html needs to be reloaded with the new information.
Here is where the noob starts. My first inclination was to create a refresh button and add a function in my LivePreviewController to refresh the page using $route.reload()
previewApp.controller('LivePreviewController', [$scope, $route, function($scope, $route){
    $scope.form_name = 'temporary name';

    $scope.refreshPage = function() {
        $route.reload();
        console.log($scope.form_name) //to ensure scope is updating
    };

}]);

And then updated my html to include the button as follows

<input type="text" ng-model="form_name" />

<button ng-click="refreshPage()"> Update the Page </button>

The function is working just fine when the button is clicked and the updated scope variable is displaying in the console, but my live preview is not updating. After looking through the Angular documentation I have a hunch as to what is happening. It states...

Causes $route service to reload the current route even if $location hasn't changed.
As a result of that, ngView creates new scope and re-instantiates the controller.

So if I understand the docs correctly, which I obviously don't, what is actually happening on $route.reload() is that when styled_form.html is getting reloaded the updated $scope.form_name is getting wiped out and the original $scope value is getting shown on the page. So...
Question 1: am I understanding this correctly i.e. is $route.reload() wiping out my $scope and reloading the old $scope variable, or is my $route.reload() just not reloading the page at all?
Now if I am interpreting my issue correctly my guess (seen suggested on here in other topics) is that the solution would be to create some type of service to store my data and then call that service inside of the controller. This workflow would look like

User input --> Data stored in some Service(factory) --> Data Passed to $scope --> >$scope value displayed in partial view (styled_form.html)

But I am lost as to how to dynamically store the user input inside of a service. Ideally this would all occur in realtime (as with the simple first example) as I would like to avoid having a refresh button. Could this be accomplished by creating a function in my controller that updates the values inside my service every few seconds? I need someone with better ideas than myself to point me in the right direction.
Question 2: Is this the correct workflow assuming Q1 is correct and if so what is the correct way to set up my service to handle the user input and pass it to another html page dynamically?
All help much appreciated

A: Having a service to store data and same controller to serve both view is fine.
Data saving could be done each time, when controller variables are changing.
When new controller is initialized, it my read the date from the service. A separate controller instance will be created for each view.
You may also check this blog to see, how data should be defined within a service, so that changing such data will auto-trigger controller to update view:
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
Notice: that service returns a reference to the array and controller saves this reference, when it is created.

A: Ok so I realized my problem was due to the fact that I was misunderstanding how $scope works in Angular not how $route.reload() was working. This topic
$scope variable not changing in controller when changed using directive
and this link in that question
https://github.com/angular/angular.js/wiki/Understanding-Scopes
helped me understand what I was doing wrong. $route.reload() and $templateCache.remove() were working correctly. The problem was that my $scope variable wasn't updating properly because each view was creating a different scope. Paraphrasing one of the links

The $scope is not the model.
The function of the controller is to write from the model to the scope
The function of the view is to display the $scope and write to the model if needed

I solved the problem using the controllerAS syntax discussed in the answers like this,
.controller('LivePreviewController',['$scope', function($scope) {
    var vm = this;
    vm.form_name = 'temporary name';
}]);

    <input type="text" ng-model="ctrl.form_name>

And in my styled form partial view

 {{ctrl.form_name}}

This causes everything to work as expected


text:
Q: How to track GPS device using GPRS connection I want to track my GPS device using gprs connection, which should give details like speed of the vehicle, location, time etc. Can please some body help me how to write this function in c# code or any idea regarding this would be great full.
Thank you.

A: You need this, probably this, and maybe this.
Good luck!
It wouldn't hurt to check out this as well. :)

A: You may need a COM Interface, I hear that MS provides one too but I am not sure if there are already applications delivered that use it if their owners are not MS personels.


text:
Q: Foreign characters not showing on Chrome, using Arch Linux (Anarchy) I have been using Anarchy and have Chrome installed. Everything is great except for when I try and view pages with foreign characters in particular Duolingo.com for learning Chinese the characters don't show.
I am aware that I probably need to download a language pack or two but can't seem to find out how after Googling the issue.


text:
Q: Obtaining attribute values from emulator Appium I am working on a mobile automation project and I am having issues obtaining an attribute value(Example a radio button if it is checked or a checked box that is not checked). I am using By org.openqa.selenium.By class but I see this class doesn't count with methods like isEnabled(), is Checked(), getText() like Webdriver does, And I am getting an error casting it to SearchContext class to be able to obtain the attribute value.
ExamplePage.locationSharingSwitch.findElement((SearchContext);
ExamplePage.locationSharingSwitch).isEnabled();

Getting this error

java.lang.ClassCastException: org.openqa.selenium.By$ByXPath cannot be
cast to org.openqa.selenium.SearchContext

Any suggestions?

A: The right way to get attribute is
MobileElement element = (MobileElement) driver.findElementByAccessibilityId("someId");
String isEnabled = element.getAttribute("enabled");

From my experience, element can be disabled and still "enabled" value is "true". it really depends on component implementation, so I would not rely on it in 100% cases.


text:
Q: Complexity of large matrix multiplication What is the time complexity of the fastest algorithm known today to multiply large matrices?
What about the theoretical optimal time complexity that could be reached?

A: This is an active area of research, so this answer may very soon be out of date. :-)
To the best of my knowledge, the current fastest matrix multiplication algorithm runs in time O(n2.373), due to a result by Virginia Williams. The algorithm is actually a large family of algorithms that give rise to a complex nonlinear system of equations that give the overall time bound, and in fact there are people doing work right now trying to see how to improve the bound by finding better and better solutions to those equations. I believe that this algorithm is only of theoretical interest, though.
The holy grail of matrix multiplication would be an O(n2)-time matrix multiplication algorithm, and whether such an algorithm exists is still an open problem. This is the theoretical limit, since an o(n2)-time algorithm couldn't even read all the entries of the matrices to multiply.
Hope this helps!


text:
Q: output from expect is not complete I have this script in order to make rsync with another server, the propossal is to get arround 1600 files, this script as two variables, date and hour, so, I send these two values with shell script then I pass the values.
Expect script:
#!/usr/bin/expect

set DIR_DATE [lrange $argv 0 0]
# Define date variable.

set DT_HOUR [lrange $argv 1 1]
# Define hour variable.

spawn rsync -avzb -e ssh user@IPSERVER:/SOURCE_DIR/$DIR_DATE/A$DIR_DATE.$DT_HOUR*.txt /TARGET_DIR/$DIR_DATE/
expect "password:"
send "PASSWORD\r"
#interact
expect eof

And the shell script is:
#!/bin/bash

***HERE is the code to get date and hour variable: DT_DATE,DT_HOUR; then, next step is run the expect script***

${DIR_BIN}/rsync_expect.sh ${DT_DATE} ${DT_HOUR}

You can note, in the expect script, I comment "interactive" word, because:

*

*If it is not comment and run manually the script, it runs very well, it get 1600 files.

*If it is commented, and run through the shell script, it only get arround 50 files and that's off.

So, any sugestion in order to get all files using shell scripts?

A: You're probably timing out: 50 files is probably what you can transfer in (default) 10 seconds. Add this before you spawn: set timeout -1
".sh" is a bad file extension for an expect script: use ".exp"
The lrange command returns a list. Use lassign $argv DIR_DATE DT_HOUR


text:
Q: Does allocating objects of the same size improve GC or "new" performance? Suppose we have to create many small objects of byte array type. The size varies but it always below 1024 bytes , say 780,256,953....
Will it improve operator new or GC efficiency over time if we always allocate only bytes[1024], and use only space needed?
UPD: This is short living objects, created for parsing binary protocol messages.
UPD: The number of the objects is the same in both cases, it just the size of allocation which changes (random vs. always 1024).
In C++ it would matter because of fragmentation and C++ new performance. But in C#....

A:
Will it improve operator new or GC efficiency over time if we always allocate only bytes[1024], and use only space needed?

Maybe. You're going to have to profile it and see.
The way we allocate syntax tree nodes inside the Roslyn compiler is quite interesting, and I'm eventually going to do a blog post about it. Until then, the relevant bit to your question is this interesting bit of trivia. Our allocation pattern typically involves allocating an "underlying" immutable node (which we call the "green" node) and a "facade" mutable node that wraps it (which we call the "red" node). As you might imagine, it is frequently the case that we end up allocating these in pairs: green, red, green, red, green, red.
The green nodes are persistent and therefore long-lived; the facades are short-lived, because they are discarded on every edit. Therefore it is frequently the case that the garbage collector has green / hole / green / hole / green / hole, and then the green nodes move up a generation.
Our assumption had always been that making data structures smaller will always improve GC performance. Smaller structures equals less memory allocated, equals less collection pressure, equals fewer collections, equals more performance, right? But we discovered through profiling that making the red nodes smaller in this scenario actually decreases GC performance. Something about the particular size of the holes affects the GC in some odd way; not being an expert on the internals of the garbage collector, it is opaque to me why that should be.
So is it possible that changing the size of your allocations can affect the GC in some unforseen way? Yes, it is possible. But, first off, it is unlikely, and second it is impossible to know whether you are in that situation until you actually try it in real-world scenarios and carefully measure GC performance.
And of course, you might not be gated on GC performance. Roslyn does so many small allocations that it is crucial that we tune our GC-impacting behaviour, but we do an insane number of small allocations. The vast majority of .NET programs do not stress the GC the way we do. If you are in the minority of programs that stress the GC in interesting ways then there is no way around it; you're going to have to profile and gather empirical data, just like we do on the Roslyn team.
If you are not in that minority, then don't worry about GC performance; you probably have a bigger problem somewhere else that you should be dealing with first.

A: new is fast, it is the GC that causes problems. So, it depends on how long your arrays live for.
If they only live a short time, I don't think there will be any improvement from allocating 1024 byte arrays. In fact this will put more pressure on the GC because of the wasted space and will probably degrade performance.
If they live for the life of your application, I would consider allocating one large array and using chunks of it for each small array. You would need to profile this to see if it helps.

A: Not really, Allocating or clearing a bytes array requires only one instruction, regardless of its size. (I speak about your case. there are exceptions)
You shouldn't worry about the performance aspect of garbage collection, unless you are sure that it's a bottleneck for your application (ie you create a lot of references with complex relationship, and throw it shortly afterward... And the garbage collection is noticeable.)
To read an excellent story about a well known (and quite useful) site having performance issues with the .NET GC (in an impressive use case) see this blog. http://samsaffron.com/archive/2011/10/28/in-managed-code-we-trust-our-recent-battles-with-the-net-garbage-collector ;)
But the most important thing about GC is: Never, ever do optimisations before being sure that you have a problem. Because if you do, you will probably have one. Applications are complex, and the GC interacts with every parts of it, at runtime. Apart from simple cases, predicting its behavior and bottlenecks beforehand seems (in my opinion) difficult.

A: I also don't think only allocating 1024 byte arrays will improve the GC.
Since the GC is not determistic, I also think it will not be your problem.
You can influence the GC by using using {} statements arround your arrays to free memory (maybe) sooner.

A: I do not think GC will be the problem and/ or bottleneck.
Allocating objects of different sizes and freeing them in a different sequence can lead to fragmented heap memory. So this is where allocating objects of the same size might come in handy.
If you really do allocate/ free a lot and really do see this as your bottleneck, try to re-use the objects with a local object cache. This can lead to performance increase, especially if they are data-only objects that do not implement a lot of logic. If the objects do implement a lot of logic and require mor complex initialisation (RAII-pattern) I would forego the performance increase for robustness of the program...
hth
Mario


text:
Q: React Rotate Accordion Arrow Onclick How can I rotate the arrows onclick
This is my code below for my react collapse and I would like to rotate the arrows of my collapse accordion when it clicked.
I'm using reactstrap to build it and react fontawsome for my Icons
I've also attached a .GIF Link to demonstrate how my accordion is currently functioning.
import React, { Component } from "react";
import { Collapse, CardBody, Card, CardHeader } from "reactstrap";
import { faChevronDown } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

const nested = [
  {
    id: 10,
    title:"Customer Queries"
  },
];

const Icon = <FontAwesomeIcon icon={faChevronDown} color={"#EB8C00" } />;

class Colapse extends Component {
  constructor(props) {
    super(props);
    this.tog = this.tog.bind(this);

    this.state = {

      col: 0,

  cards: [
    {
      id:1,
      title:"General information requests",
      sub_title:"Fault reports",
      body:"Something to display for body 1",
    },
    {
      id:2,
      title:"Account queries",
      sub_title:"Communication protocols",
      body:"Something to display for body 2",
    }
    ] };
  }

  tog(e) {
    let event = e.target.dataset.event;
    this.setState({
      col: this.state.col === Number(event) ? 0 : Number(event),
    });
  }

  render() {
    const { col, cards } = this.state;

    return (

          {nested.map((element, index) => {
            return (
              <Card key={index} className="card rounded ">

                <CardHeader
                  className="card-header"
                  onClick={this.tog}
                  data-event={(index = element.id)}
                >

{element.title}

                </CardHeader>

                <Collapse isOpen={col !== index}>
                  <CardBody className="card-body">

Customer Queries relate to information, account or meter related faults reported by the customer.

                    {/**HERE NESTED */}
                    {cards.map((index) => {

                      return (
                        <Card key={index} className="card-sub rounded ">

{index.title}

                          <CardHeader
                            className="card-header-sub"
                            onClick={this.tog}
                            data-event={index.id}
                          >

{Icon}

{index.sub_title}

                          </CardHeader>

                          <Collapse isOpen={col === index.id}>
                            <CardBody className="card-body-sub">

{index.body}

                            </CardBody>
                          </Collapse>
                        </Card>
                      );
                    })}
                    {/**End Of Nested */}
                  </CardBody>
                </Collapse>
              </Card>
            );
          })}

    );
  }
}

export default Colapse;

A: Rotate the svg according to some condition e.g. col === element.id
<div className={`p-2 rotate ${col === element.id ? "isRotated" : ""}`}>{Icon}

on your stylesheet:
.isRotated svg {
  transform: rotate(-90deg);
}


text:
Q: Matlab script for temperature in K or F Write a script that will prompt a user for a temperature in degrees C,and then an F for fahrenheit or K for Kelvin.The script will print the corresponding temperature  in the scale specified by the user.For example the output  mght look as follows:
Enter the teperature in degrees C:29.3
Do you want K or F?F
The temperature in degrees F is 84.7
Here is my try but it doesnt run well,I would like some correction
% this for prompting  a user for a temp in C and
%print a temp either in K or F as specified by the user
C=input('Enter temperature in degrees C:');
%user specification
j=input('Do you want K or F?');
%error check
while j~=K || j~=F

    disp('Please enter K or F')
    j=input('Enter K or F now:');
end
if j==F
    F=9/5*C+32;
    fprintf('The temperature in degrees F is %.2f\n',F);
else
    K=C+273.15;
    fprintf('The temperature in degrees Kis %.2f\n',K);
end

A: I do not have matlab right now but try this:
    C=input('Enter temperature in degrees C:');

% the j should be returned as string
j=input('Do you want K or F?','s');

% You should compare string j 'K' or 'F' - in Your case the K and F was some uninitialized variables
while j~='K' && j~='F'

    disp('Please enter K or F')
    % again return string
    j=input('Enter K or F now:','s');
end
%compare to char F
if (j=='F')
    F=9/5*C+32;
    fprintf('The temperature in degrees F is %.2f\n',F);
% compare to char 'K'
elseif (j=='K')
    K=C+273.15;
    fprintf('The temperature in degrees Kis %.2f\n',K);
end


text:
Q: Show that each $k\in \mathbb{N}$ can be represent as $ k = S_m(a)+S_n(b)$ Let $a,b$ are non negative integers and $m,n$ are positive integers.
Let define
$$S_m(a)=0^m+1^m+2^m+...+a^m$$
and $$S_n(b)=0^n+1^n+2^n+...+b^n$$

Question

Show that each $k\in \mathbb{N}$ can be represent as
$$ k = S_m(a)+S_n(b)$$

Example
$5= S_2(2)+S_n(0)$
$6= S_1(3)+S_n(0)$
$\ \ = S_1(2)+S_1(2)$
Edit
I just changed whole question to simplify , understanding and more motivation, my apologies.
I already asked for representation of $ k = S_1(a)-S_1(b)$ here

A: It appears that this claim is untrue. There are quite a few numbers which cannot be expressed in this manner, the smallest being $52$.
Observe the terms $S_n(k) \leqslant 52$
First powers = $\{0,1,3,6,10,15,21,28,36,45\}$
Second powers = $\{0,1,5,14,30\}$
Third powers = $\{0,1,9,36\}$
Fourth powers = $\{0,1,17\}$
Fifth powers = $\{0,1,33\}$
Rest of the powers = $\{0,1\}$
Union of all such values = $\{0,1,3,5,6,9,10,14,15,17,21,28,30,33,36,45\}$
You can easily check that for all values $m$ in the union set, $52-m$ is not in the union set. Thus, $52$ cannot be represented in the required manner. The first few values of this sort are:
$$52,77,89,116,118,147,152,179,187,197,...$$
This can be easily coded using the logic executed above for $52$.
S=[0]
i=1
while i<=10:
    add=0
    j=1
    while j<=50:
        add=add+(j**i)
        S.append(add)
        j=j+1
    i=i+1
print(S)
for m in range(1,1000):
    sm=0
    for index in range(len(S)):
        if m-S[index] in S:
            sm=sm+1
    if sm==0:
        print(m)


text:
Q: How do I use a function I created on values within a dataframe and replace the values with outcome of the function? I created a function called getExpressionLevel and the question asks me to use this function to replace the numbers with the statements below. So what do I need to use to achieve this?
Function for getExpressionLevel;
function(a)    {
  if    (a<5)    {
  cat    ("none")
  }

 if    (a>=5&a<20)    {
  cat    ("low")
 }

 if    (a>=20&a<60)    {
  cat    ("medium")
 }

  if    (a>=60)    {
  cat    ("high")
  }
}

*

*"none" for expression levels below 5

*"low" for expression levels higher or equal to 5 and lower than 20

*"medium" for expression levels higher or equal to 20 and lower than 60

*"high" for expression levels higher or equal to 60

And the question is;
Create a data.frame called expression_levels, which has 10 row (one for each gene) and 3 columns
(one for each cell line). Then compute average expression for each each gene in each cell line and using
getExpressionLevel function label the expression accordingly.
This is my current data.frame. The data within it needs to replaced with the outcomes of the getExpressionfunction.
  genename       Kc167         BG3         S2

1   Clic        7.333333      48.33333      75.00000

2   Treh        24.666667     12.66667      52.33333

3   bib         31.333333      79.33333     82.00000

4   CalpC       65.000000     69.33333      63.66667

5   tud         59.666667     81.66667      16.33333

6   cort        74.333333     50.66667      28.66667

7   S2P         72.000000     39.66667      50.66667

8   Mitofilin   38.333333     29.00000      54.66667

9   Oxp         73.666667     49.33333      42.66667

10  Ada1-2      87.333333     42.00000      28.00000

This is the expected data.frame:
          Kc167      BG3        S2

 Clic       low      medium     high

 Treh      medium     low      medium

 bib       medium     high      high

 CalpC      high      high      high

 tud       medium     high      low

 cort       high     medium    medium

 S2P        high      medium   medium

 MitofiliN medium    medium    medium

 Oxp        high      medium   medium

 Ada1-2     high      medium   medium

A: bin_breaks <- c(-Inf, 5, 20, 60, Inf)
bin_labels <- c("none", "low", "medium", "high")
df[,-1] <- sapply(df[,-1], function(x) cut(x,
                                           breaks = bin_breaks,
                                           labels = bin_labels,
                                           right = F))
df

Output is:
    genename  Kc167    BG3     S2
1       Clic    low medium   high
2       Treh medium    low medium
3        bib medium   high   high
4      CalpC   high   high   high
5        tud medium   high    low
6       cort   high medium medium
7        S2P   high medium medium
8  Mitofilin medium medium medium
9        Oxp   high medium medium
10    Ada1-2   high medium medium

Sample data:
df <- structure(list(genename = c("Clic", "Treh", "bib", "CalpC", "tud",
"cort", "S2P", "Mitofilin", "Oxp", "Ada1-2"), Kc167 = c(7.333333,
24.666667, 31.333333, 65, 59.666667, 74.333333, 72, 38.333333,
73.666667, 87.333333), BG3 = c(48.33333, 12.66667, 79.33333,
69.33333, 81.66667, 50.66667, 39.66667, 29, 49.33333, 42), S2 = c(75,
52.33333, 82, 63.66667, 16.33333, 28.66667, 50.66667, 54.66667,
42.66667, 28)), .Names = c("genename", "Kc167", "BG3", "S2"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))

Edit: Appropriate right parameter is added in the code to satisfy boundary condition & OP's requirement (courtesy @drf).

A: The functional way. It's always helpful to know how to play with functions.
## sample data
df <- data.table(genename = c('Clic','Treh','bib','CalpC'),
                 Kc167 = c(7.333,24.666,31.3333,65),
                 BG3 = c(48.33,12.66,79.33,69.33),
                 S2 = c(75.00,52.33,82.00,63.66))

## this function updates values based on following criterias
get_values <- function(x)
{
    if(x < 5) return ('None')
    else if ((x >= 5) && (x < 20)) return ('low')
    else if ((x >= 20) && (x < 60)) return ('medium')
    else if (x >= 60) return ('high')
}

## creating a new data frame with answers
df2 <- df$genename
df2$Kc167 <- sapply(df$Kc167, get_values)
df2$BG3 <- sapply(df$BG3, get_values)
df2$S2 <- sapply(df$S2, get_values)

  genename  Kc167    BG3     S2
1:     Clic    low medium   high
2:     Treh medium    low medium
3:      bib medium   high   high
4:    CalpC   high   high   high


text:
Q: How to select different data for each column in table Have query like:
declare @type int = 1

select cf.id, cf.name
from dbo.tbl1 cf
inner join dbo.tbl2 ct on cf.id = ct.field_id and ct.[type_id] = @type

Response is:
ID   NAME
1   number
2   city
4   location
5   username

I want add one field in response which I must get for each name from select
something like:
when name = number then select number from myTbl
when name = city then select name from region_tbl
when name = location then select name from location_tbl
when name = username then select user from user_tbl

and response must be like :
ID   NAME      Field
1   number     1
2   city       Paris
4   location   some_location
5   username   admin

Is it possible to do something like this ?
Or i can add in table one more column and response will be like :
ID   NAME     command
1   number    select number from myTbl
2   city      select name from region_tbl
4   location  select name from location_tbl
5   username  select user from user_tbl

and dynamically execute commands, response must be like :
ID   NAME      command
1   number     1
2   city       Paris
4   location   some_location
5   username   admin

A: You can use the CASE WHEN THEN for getting the desired result with the use of subquery
If your datatype is different for each table column then you might have to cast the subquery result to one uniform type like VARCHAR
   select cf.id, cf.name
   thirdColumn = CASE
                  WHEN cf.name = 'number' THEN CAST((select TOP 1 number from myTbl) AS VARCHAR)
                  WHEN cf.name = 'city' THEN CAST((select TOP 1 name from region_tbl) AS VARCHAR)
                  WHEN cf.name = 'location' THEN CAST((select TOP 1 name from location_tbl) AS VARCHAR)
                  WHEN cf.name = 'username' THEN CAST((select TOP 1 user from user_tbl) AS VARCHAR)
  from dbo.tbl1 cf
  inner join dbo.tbl2 ct on cf.id = ct.field_id and ct.[type_id] = @type

NOTE - The sub-queries without using TOP or WHERE condition can cause you to give the multiple row's as return that can cause the error.So adjust the sub-queries to always return 1 row.


text:
Q: Union help on DB2 I am trying to union two queries to show the top 5 customer codes but I keep receiving an error, SQLSTATE 42601.
Ideally I would like the query to show something like this.
LTIHONIA CLIENT 1 1330
LITHOINA CLIENT 2 1300
LITHONIA CLIENT 3 1000
ATHENS CLIENT 1 1330
ATHENS CLIENT 2 1000
ATHENS CLIENT 3 400

SELECT 'LITHONIA' AS TYPE,  CLIENT_ID, ROUND(DEC(SUM(ORIG_AMT)),2) AS REVENUE FROM AR_SUM AR, TLORDER WHERE AGING_DATE >= '1/1/2016' AND AR.BILL_NUMBER = TLORDER.BILL_NUMBER
AND CURRENT_STATUS IN ('BILLD','EDIBILLED') AND ORIG_AMT > 0 AND AR.SITE_ID = 'SITE1'
GROUP BY CLIENT_ID
ORDER BY REVENUE DESC
FETCH FIRST 5 ROWS ONLY
UNION
SELECT 'LITHONIA' AS TYPE,  CLIENT_ID, ROUND(DEC(SUM(ORIG_AMT)),2) AS REVENUE FROM AR_SUM AR, TLORDER WHERE AGING_DATE >= '1/1/2016' AND AR.BILL_NUMBER = TLORDER.BILL_NUMBER
AND CURRENT_STATUS IN ('BILLD','EDIBILLED') AND ORIG_AMT > 0 AND AR.SITE_ID = 'SITE10'
GROUP BY CLIENT_ID
ORDER BY REVENUE DESC
FETCH FIRST 5 ROWS ONLY

A: Try using parentheses around the subqueries:
(SELECT 'LITHONIA' AS TYPE,  CLIENT_ID, ROUND(DEC(SUM(ORIG_AMT)),2) AS REVENUE
 FROM AR_SUM AR JOIN
      TLORDER
      ON  AR.BILL_NUMBER = TLORDER.BILL_NUMBER
 WHERE AGING_DATE >= '1/1/2016' AND CURRENT_STATUS IN ('BILLD','EDIBILLED') AND ORIG_AMT > 0 AND AR.SITE_ID = 'SITE1'
 GROUP BY CLIENT_ID
 ORDER BY REVENUE DESC
 FETCH FIRST 5 ROWS ONLY
) UNION
(SELECT 'LITHONIA' AS TYPE,  CLIENT_ID, ROUND(DEC(SUM(ORIG_AMT)),2) AS REVENUE
 FROM AR_SUM AR JOIN
      TLORDER
      ON AR.BILL_NUMBER = TLORDER.BILL_NUMBER
 WHERE AGING_DATE >= '1/1/2016' AND
       CURRENT_STATUS IN ('BILLD','EDIBILLED') AND ORIG_AMT > 0 AND AR.SITE_ID = 'SITE10'
 GROUP BY CLIENT_ID
 ORDER BY REVENUE DESC
 FETCH FIRST 5 ROWS ONLY
)

Also, you should learn to use proper explicit JOIN syntax.  Simple rule:  Never use commas in the FROM clause.  And, UNION ALL is probably more appropriate than UNION, unless you intend for duplicates to be removed.

A: @OVO
I am sure that your query has error 42601 due to order by clause. You cant have it in union query.
Remove order by clause from both sqls & put then like select fields from (YOUR UNION SQL) order by bla bla.


text:
Q: AMPscript ContentBlockByName for shared content What is the syntax to use the ContentBlockByName function with shared content. I am getting errors when trying the following:
%%=ContentBlockByName("Shared Content\MyContentBlock")=%%
%%=ContentBlockByName("Shared\MyContentBlock")=%%
%%=ContentBlockByName("\MyContentBlock")=%%

Thanks!

A: I just test this and it works with %%=contentblockbyname("Shared Content\sharedblock")=%%
You can also use the browse function:


text:
Q: Nothing will Wrap in PageBlockTable I have looked up documentation which suggests this should be easy, yet nothing works - why do none of the style elements below get the column header to wrap? It does not wrap in classic or lightning, in preview or on a record page.
<apex:page standardController="Opportunity" extensions="ContactRolesMassEditExtension" >

    <apex:form>

        <apex:pageBlock mode="inlineEdit" >

            <apex:pageBlockButtons location="bottom">
                <apex:commandButton action="{!save}" value="Save" id="saveButton" />
            </apex:pageBlockButtons>

            <apex:pageBlockTable value="{!OCRs}" style="table-layout:fixed" var="OCR">

                <apex:column style="word-wrap: break-all;" headerValue="L0o0o0o0o0o 0o0o0o0o0o0o0o0o0 o0o0o0o0o0o0 o0o0o0o0o0o0o0o0 o0o0o0o0o0o0o0o0o0ng"   >
                    <apex:outputField style="word-wrap: break-word; white-space:normal" value="{!OCR.Attended_First_Meeting__c}"></apex:outputField>
                </apex:column>

            </apex:pageBlockTable>

        </apex:pageBlock>

    </apex:form>

</apex:page>

A: Have you tried using headerClass on the <apex:column> element?
As per the docs for the style attribute:

The style used to display the column, used primarily for adding
inline CSS styles. Note that this value does not apply to the
header and footer cells.

A: None of the myriad of text wrapping related tags seemed to do anything at all - but this worked just fine:
<apex:column >
     <apex:facet name="header">Marketing
Program
Contact</apex:facet>
     <apex:outputField value="{!OCR.Marketing_Program_Contact__c}"></apex:outputField>
</apex:column>


text:
Q: How do I get Python and Task Scheduler to work on Windows VM when not connected from laptop? I wrote a script in python to open and run an alteryx workflow, and used Windows task scheduler to automate it daily. It works great when I'm connected to the VM from my laptop. But when I let it run while the VM is disconnected from my laptop, it opens alteryx but doesn't run the workflow.
Python Script
import pyautogui as pg
import os
import time

time.sleep(10)
os.startfile("C:\\Users\\my_name\\Desktop\\Python Test Workflow.yxmd")
time.sleep(45) #build in enough time for Alteryx to open the workflow
pg.hotkey('ctrl', 'r')
time.sleep(10)

Batch file executed by task scheduler
"C:\Program Files\Python39\python.exe" "C:\Users\my_name\Desktop\Python Alteryx Getv2\Getv2_Refresh_Py_Script.py"
pause

Error Message in cmd.exe
C:\Windows\system32>"C:\Program Files\Python39\python.exe" "C:\Users\my_name\Desktop\Python Alteryx Getv2\Getv2_Refresh_Py_Script.py"
    Traceback (most recent call last):
      File "C:\Users\my_name\Desktop\Python Alteryx Getv2\Getv2_Refresh_Py_Script.py", line 8, in <module>
        pg.hotkey('ctrl', 'r')
      File "C:\Users\my_name\AppData\Roaming\Python\Python39\site-packages\pyautogui\__init__.py", line 597, in wrapper
        failSafeCheck()
      File "C:\Users\my_name\AppData\Roaming\Python\Python39\site-packages\pyautogui\__init__.py", line 1722, in failSafeCheck
        raise FailSafeException(
    pyautogui.FailSafeException: PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED.

    C:\Windows\system32>pause
    Press any key to continue . . .


text:
Q: Store data from local db to Oracle MCS I want to store contents of my local db to oracle cloud. I have searched the internet but cannot find any apis which can guide me to my result. The documentation is very naive and I cannot find a solution.
Been searching for 3 days, help would be appreciated

A: (Disclaimer: I work for the Oracle MCS team)
In response to your update that you want to store data in MCS.
Let's break this discussion into two parts, the MCS server side, and the client side which is Android in your case.
From a MCS server perspective you have two options for storage, the "Storage API" and the "Database API".  The "Storage API" is designed to store files (aka. objects) in collections.  The "Database API" is for more traditional data stored in RDBMS tables, columns & rows.  So you need to make a choice which you think is more suitable for your needs.
Note that the Storage API is accessible external to MCS from a mobile client as a REST API, as well as node.js custom APIs within MCS that you would manually write.  However the Database API is only accessible from node.js custom APIs.  So if you choose to use the Database API you must also build server side custom APIs to expose the Database API to your client.  With the Storage API it is already exposed to your client.
If we move onto the client side and what you need to do, you ultimately need to build your client to contact these server side APIs, which ever you choose as the description above.  In building the client side you have two choices:
1) Manual - you create your own code to create, store and manage objects in the Android local db (eg. SQLLite), and then you need to write client side code to consume the MSC server APIs you've setup and read/write data from the local db.  There is potentially significant work here, but, the MCS Android SDK will make this job easier as it provides client side libraries to call both the server side Storage API or Custom API (wrapping the Storage API or Database API) that we considered above, rather than you having to write raw REST calls.
2) Automatic - the MCS Android SDK also provide a "data offline & sync" SDK that takes care of the creation, store and management of objects in the device's database for you, and synchronising the data with the server side for you, based on a bunch of policies you pick.  There is still some coding required, but mostly it's greatly reduced compared to the manual option above.
I'm sure you are already familiar with the MCS YouTube channel and it does cover how to build custom APIs, use the storage API, and does include videos on the Data Offline & Sync SDK too.  Look to the playlists in the channel for the major topic areas.  By chance I literally finished the Android video for Data Offline & Sync a couple weeks back (remember to watch the other data offline & sync videos before this one!), and it's not yet public.  But you can have a sneak peak of the video here.
(A comment for future readers of this post: Please note that URL may change when we finally properly publish that video)


text:
Q: GetPrivateProfileString in .NET Is there a .NET version of GetPrivateProfileString?
(I can use p/invoke, I just don't want to unless necessary.)

A: Not built in, no.  There's nothing that can natively read and understand the layout of an .ini file in .NET.  GetPrivateProfileString is your best bet.

A: No, there isn't, at least not in the Base Class Library.  This isn't surprizing, given that .NET doesn't have any native support (in the form of pure managed code, or wrappers over P/Invoke calls) for INI files.

A: If you dont want to use Interop, you can use ini file loader class like this one
http://www.codeproject.com/KB/recipes/INI_Files.aspx


text:
Q: How can 'brand new, never before seen' IDs be counted per month in redshift? A fair amount of material is available detailing methods utilising dense_rank() and the like to count distinct somethings per month, however, I've been unable to find anything that allows a count of distinct per month which also removes/discounts any id's that have been seen in prior month groups.
The data can be imagined like so:
id (int8 type) | observed time (timestamp utc)
------------------
1  | 2017-01-01
2  | 2017-01-02
1  | 2017-01-02
1  | 2017-02-02
2  | 2017-02-03
3  | 2017-02-04
1  | 2017-03-01
3  | 2017-03-01
4  | 2017-03-01
5  | 2017-03-02

The process of the count can be seen as:
1: in 2017-01 we saw devices 1 and 2 so the count is 2
2: in 2017-02 we saw devices 1, 2 and 3. We know already about devices 1 and 2, but not 3, so the count is 1
3: in 2017-03 we saw devices 1, 3, 4 and 5. We already know about 1 and 3, but not 4 or 5, so the count is 2.
with the desired output being something like:
observed time | count of new id
--------------------------
2017-01       | 2
2017-02       | 1
2017-03       | 2

Explicitly, I am looking to have a new table, with an aggregated month per row, with a count of how many new ids occur within that month that have not been seen at all before.
The IRL case allows devices to be seen more than once in a month, but this shouldn't impact the count. It also uses integer for storage (both positive and negative) of the id, and time periods will be to the second in true timestamps. The size of the data set is also significant.
My initial attempt is along the lines of:
WITH records_months AS (
SELECT *,
date_trunc('month', observed_time) AS month_group
FROM my_table
WHERE observed_time > '2017-01-01')
id_months AS (
SELECT DISTINCT
month_group,
id
FROM records_months
GROUP BY month_group, id)
SELECT *
FROM id-months

However, I'm stuck on the next part i.e counting the number of new ID that were not seen in prior months. I believe the solution might be a window function, but I'm having trouble working out which or how.

A: First thing I thought of. The idea is to

*

*(innermost query) calculate the earliest month that each id was seen,

*(next level up) join that back to the main my_table dataset, and then

*(outer query) count distinct ids by month after nulling out the already-seen ids.

I tested it out and got the desired result set. Joining the earliest month back to the original table seemed like the most natural thing to do (vs. a window function). Hopefully this is performant enough for your Redshift!
select observed_month,
    -- Null out the id if the observed_month that we're grouping by
    -- is NOT the earliest month that the id was seen.
    -- Then count distinct id
    count(distinct(case when observed_month != earliest_month then null else id end)) as num_new_ids
from (
    select t.id,
        date_trunc('month', t.observed_time) as observed_month,
        earliest.earliest_month
    from my_table t
        join (
            -- What's the earliest month an id was seen?
            select id,
                date_trunc('month', min(observed_time)) as earliest_month
            from my_table
            group by 1
        ) earliest
        on t.id = earliest.id
)
group by 1
order by 1;


text:
Q: How to create multi JSON object in java I want to create a object array in JSONObjet. But not run in java. Please help me.
JSONObject jo[] = new JSONObject[10];

    jo[0].put("A","a");
    jo[1].put("B","b");
    jo[2].put("B","c");
    ...

java

A: You are probably looking for this -
        JSONObject jo[] = new JSONObject[10];

        jo[0]=new JSONObject().put("A","a");
        jo[1]=new JSONObject().put("B","b");
        jo[2]=new JSONObject().put("B","c");

Use JSONArray instead of that like this -
    public void getJSONArray() throws JSONException {

        JSONArray jo= new JSONArray();

        JSONObject obj1= new JSONObject();
        obj1.put("A","a");

        JSONObject obj2= new JSONObject();
        obj2.put("B","b");

        JSONObject obj3= new JSONObject();
        obj3.put("B","c");

        jo.put(obj1);
        jo.put(obj2);
        jo.put(obj3);

        System.out.println(jo.toString());

    }

Output -
 [{"A":"a"},{"B":"b"},{"B":"c"}]


text:
Q: Как правильно получить координаты и масштаб? У меня вопрос:
Я правильно получаю координаты x,y?
Как сделать если x,y равны (0.5, 0.5), то центр картинки будет размещаться в правом верхнем углу синей области?
Если scale = 1, картинка будет занимать всю поверхность синей области.
Если картинка квадратная и scale = 1, то картинка будет по высоте занимать всю синею область, а по ширине вылезать немного за пределы.
Соответственно уменьшая scale картинка будет уменьшаться на синей области, если scale = 0 значит картинку вообще не будет видно, а если 0.5 то картинка = половинка синей области!
Как такое сделать с масштабом?
Вот я набросал свой пример на котором я остановился, и больше ничего в голову не лезет:

Ссылка на codepen.io
Спасибо!

A:
Масштаб - scale, это всего-лишь отношение коэффициента к длине стороны.

Если предположить что исходная сторона ровна 360, а текущая 90, то найти масштаб можно так -
90 / 360 = 0.25

И наоборот, если известны текущие размеры стороны, пусть будут так же 90 и масштаб .25, то исходные значения можно узнать -
90 / .25 = 360 // исходный размер стороны

Надеюсь понятно объяснил чтобы справится с масштабом самостоятельно.
Ну а дальше все так же просто. Находите центр ручки, размер которой 360x360 и центр фигуры, размер которой 720х720, в которую эта ручка должна быть вписана. В стартовом состоянии маштаб ручки будет 1х1, а длина между центрами будет 0.
Теперь представьте что Вы переместили ручку центром в правый верхний угол и тем самым масштаб должен стать 0.5х0.5. Поэтому нужно найти длину между двумя точкам, она же будет максимальным расстоянием от центра, пусть эта длина будет 500. Это означает что переместив ручку из исходного положения на 500px её размер с 360x360 изменится до 180x180, то есть её масштаб уменьшится в два раза. Находим это так -
0.5 * 500 = 0.001 // это коэффициент масштаба к длине 500

Теперь все что нам осталось, это при драге ручки находить длину между её центром и центром фигуры в которою она вписана, умножать её на 0.001 и вычитать из 1, так как у нас происходит удаление от центра и полученное значение будет значением масштаба ручки.


text:
Q: JavaScript along with the HTML file is not running in UIWebView I have placed the HTML Resource files and java script files with the project files in my iphone application. My objective is to build an application which has UIWebview which loads when we tab on the app icon. The UIWebView should actually load the local html content that I have in the resource folder. I can see the HTMl content in the webview but its not running the Javascript..

A: Checkout stringByEvaluatingJavaScriptFromString: in the
UIWebView Class Reference

A: Her the actual problem comes with adding the files(javascript and css) in the project. while adding files following option should be clicked that showed in the following image.


text:
Q: Verilog counter made of 32 bit adder (syntax error) For a school assignment I have to make a counter, based on a 32-bit adder, that increments with 1 every clockcycle if 'enable = high' and 'reset = low'.
When I try to use the adder in my counter module, verilog gives me a syntax error which i dont know how to solve, near 'adder adder_count(.a(a), .b(b), .c(count));'
can anyone of you help?
 module half_adder(
    input a,
    input b,
    output sum,
    output Cout
    );

    assign sum = a ^ b;
    assign Cout = a & b;

endmodule

module full_adder(
    input Cin,
    input a,
    input b,
    output sum,
    output Cout
    );

    wire sum1_w;
    wire Cout1_w;
    wire Cout2_w;

    //Half adder 1

    half_adder half_add1 (.a(a), .b(b), .sum(sum1_w), .Cout(Cout1_w));

    //Half adder 2

    half_adder half_add2 (.a(Cin), .b(sum1_w), .sum(sum), .Cout(Cout2_w));

    //Resulting OR gate

    or or_cout (Cout, Cout1_w, Cout2_w);

endmodule

module adder(
    input [31:0] a,
    input [31:0] b,
    output [31:0] c
    );

    wire [31:0] carry;
    genvar i;
    for (i = 0; i < 32; i = i + 1) begin
        if(i==0)
        half_adder half_add (.a(a[0]), .b(b[0]), .sum(c[0]), .Cout(carry[0]));

        else
        full_adder full_add (.Cin(carry[i-1]), .a(a[i]), .b(b[i]), .sum(c[i]), .Cout(carry[i]));

    end

endmodule

module counter(
    input clk,
    input reset,
    input enable,
    output [3:0] count
    );

    reg [0:31] a;
    reg [0:31] b = 32'b00000000000000000000000000000001;
    // b starts as 1, a as 0

always @(posedge clk) begin

    if (enable == 1'b1 && reset == 1'b0) begin

        adder adder_count(.a(a), .b(b), .c(count));

        // every step:  a + 1 = c
        // a becomes c
        // repeat
    end

     if (reset == 1'b1) begin
         //reset

     end
end

endmodule

A: @ThePhoton gave the correct answer to your immediate problem, "You can't instantiate a module inside a procedural block."
But the whole approach is impractical for many other reasons. I understand why they make you build adders out of gates when you're learning the language, but continuing to use such techniques to build larger systems is just silly. You need to start using the power of the language to make your tasks easier. A counter in Verilog should be a 7-line block:
always @(posedge clock) begin
  if (reset) begin
    count <= 0;
  end else begin
    count <= count + 1;
  end
end

Which can be replaced by a single line if you want:
always @(posedge clock) count <= reset ? 0 : count + 1;

Keeping your source code simple makes it both easier to debug and easier to understand and extend later. It also gives you more room for comments that capture the design requirements and implementation constraints that are not visible in the code itself. THAT's the real lesson here!


text:
Q: How to allow form elements to have more than one class and concatenate / slice for error message I am trying to alter this code by allowing the form element's label
to have more than one class. I know I have to use concatenation to add the error
class, and remove the error class by slicing off the text after the last space
in the className value but where do I start, am i supposed to just modify the span?
    function addErrorMessage(id, msg) {
    'use strict';

    // Get the form element reference:
    var elem = document.getElementById(id);

    // Define the new span's ID value:
    var newId = id + 'Error';

    // Check for the existence of the span:
    var span = document.getElementById(newId);
    if (span) {
        span.firstChild.value = msg; // Update
    } else { // Create new.

        // Create the span:
        span = document.createElement('span');
        span.id = newId;
        span.className = 'error'
        span.appendChild(document.createTextNode(msg));

        // Add the span to the parent:
        elem.parentNode.appendChild(span);
        elem.previousSibling.className = 'error';

    } // End of main IF-ELSE.

} // End of addErrorMessage() function.

// This function removes the error message.
// It takes one argument: the form element ID.
function removeErrorMessage(id) {
    'use strict';

    // Get a reference to the span:
    var span = document.getElementById(id + 'Error');
    if (span) {

        // Remove the class from the label:
        span.previousSibling.previousSibling.className = null;

        // Remove the span:
        span.parentNode.removeChild(span);

    } // End of IF.

} // End of removeErrorMessage() function.

A: Why not use jQuery so you can simply use addClass and removeClass?
http://api.jquery.com/addclass/
http://api.jquery.com/removeclass/
You'd also get the benefit of things like hasClass, among other things...
http://api.jquery.com/hasclass/


text:
Q: Prevent WKWebView to handle media keys events I'm working on native media player for macOS. It should be a simple music streaming website wrapper with global support of media-keys.
Interface of the App it's just full sized WKWebView. Everything works fine with MPRemoteCommandCenter to handle media keys events like play/pause until browser starts playing audio. It's looks like browser is overriding method addTarget(Any, action: Selector) for instance of class MPRemoteCommand and my custom handlers haven't called anymore.
Is there a way for WKWebView instance to prevent interception access to MPRemoteCommandCenter and/or MPNowPlayingInfoCenter?


text:
Q: Android - ListView layout two line list item I have a listview with two lines of items: user ID and username. How to retrieve only user ID from the listview when one of the rows is clicked?
public class MainActivity extends AppCompatActivity {

private DatabaseReference mUsers;
String getValue = null;
ListView lvUsers = (ListView) findViewById(R.id.lvUsers);

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mUsers = FirebaseDatabase.getInstance.getReference().child(Constants.FIREBASE_USERS);

    FirebaseListAdapter<Users> adapter = new FirebaseListAdapter<Users>(
            this, Users.class, android.R.layout.two_line_list_item, mUsers
    ) {
            @Override
            protected void populateView(View v, Users user, int pos) {
            ((TextView)v.findViewById(android.R.id.text1)).setText(user.getUserID());
            ((TextView)v.findViewById(android.R.id.text2)).setText(user.getUsername());
            }
    };

    lvUsers.setAdapter(adapter);
    setupListViewMenu();
}

private void setupListViewMenu() {
    lvUsers.setOnItemLongClickListener(
            new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapter,
                                       View item, int pos, long id) {

            // How to retrieve only User ID from here?
            getValue = ((TextView)view).getText().toString();

            return true;
        }

    });
}
}

The listview data is from Firebase database. Is retrieving using for loop the only way? I have to loop through two dimensional array? Thanks

A: Could you please try the code below?
getValue = ((TextView)item.findViewById(android.R.id.text2)).getText().toString();

I believe that android.R.id.text2 is one of the childs of item(View received in the clickListener)
But need to test... Hope it works


text:
Q: Getting a UITabBar after breaking out of a UINavigationBar I have a UINavigationBar that has an AuthenticateViewController in it.  Then when the user his Sign In in the upper right of my navigation control, I want to show a UITabBar controller. Do I still create this in appDelegate? How do I "break out" of the UINavigation controller?
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

// Add methods for layout of this view controller here

//1
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//2
self.managedObjectContext = appDelegate.managedObjectContext;

[self.navigationItem setHidesBackButton:YES];

// Now add the Sign In button
UIBarButtonItem *signinButton = [[UIBarButtonItem alloc] initWithTitle:@"Sign In" style:UIBarButtonItemStylePlain target:self action:@selector(signinButtonPressed:)];

self.navigationItem.rightBarButtonItem = signinButton;
}

- (void) signinButtonPressed:(UIBarButtonItem *) sender
{
    // What goes here to start the UITabBars
}

A: Set your TabBarController as rootViewController after signed in.
Your button action would be like this:
UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.viewControllers = @[<your viewControllers>];

AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
[appDelegate.window setRootViewController:tabBarController];

Edit: You might don't get use with array creation with @[]. So here is an explanation:
UIViewController *viewController1 = [[UIViewController alloc] init];
UIViewController *viewController2 = [[UIViewController alloc] init];

// Two methods of adding item to array

// First method
NSArray *array = [NSArray arrayWithObjects:viewController1, viewController2, nil];

// or
NSArray *array = @[viewController1, viewController2];

tabBarController.viewControllers = array;

A: You'll need to do a modalTransition to jump out of the navigationController.. this will keep the AuthenticateViewController as RootViewController of the window.. if you want to change the RootViewController as well then you'll need to get the AppDelegate's window and change its RootViewController to the TabBarController you'll make here… hope you got it..


text:
Q: Create functions indexes MySQL I have a table with [date] index.
[date] column:
'2015-01-05'
'2015-01-06'
and etc

Can I create new index for function index?
When i am trying to create it I get error, example:
create index date_y on table (year(date))

If I could we didn't recreate queries for program performance.

A: Yes and no. No, you cannot create an index on an expression in this fashion. However, if you happen to have mysql v5.7.8 or newer, then you can create generated columns and you can create a secondary index on them (secondary index means that a generated column cannot be part of a primary key).
So, create your expression as a generated column and then create an index on it - if you have mysql v5.7.8 or newer.

A: One moment, when I have:
   date is created index on tableX
   id is created index on tableX
   id is created index on tableY

My query:
   Select * from tableX as x left outer join tableY as y on x.id=y.id
    where year(x.date)=2015 and month(x.date)=11

Should I recreate date to:
create index date on tableX (date,id)

or some else?


text:
Q: Golang fill slice in function not working I am trying to add stuff to my slice but somehow the slice is never updated.
endpointsList := make([]string, 3)

for _, route := range routes {
    if len(route.Endpoints) > 0 {
        waitGroup.Add(1)
        go endpointRoutine(route, template, route.Protected, &waitGroup, &endpointsList)
    }
}

I pass the endpointsList by reference, meaning I should be able to assign new things to its memory location I think.
In the function endpointRoutine I do this:
list := make([]string, 3)

for _, r := range route.Endpoints {
    list = append(list, "some data comes here...")
}

endpointsList = &list

When I do a printr after this (below my first bit of code and AFTER the waitGroup.Wait() part) the slice is still empty.
Obviously, I am overwriting the slice now and my final goal is to ADD to the slice. But when I try to add with this code:
endpointsList = append(endpointsList, "fdssdfsdfsdf")

It gives me the error:

cannot use endpointsList (type *[]string) as []Type

Can someone please explain to me what might be wrong?

A: With endpointsList = &list, you are assigning the pointer pointing to the slice to some other slice. To set the slice, do this instead:
*endpointsList=list


text:
Q: OPENGL how to use glTexImage3D function the following code is used to draw an ocean, i tried to convert it to c# code, but i failed because i didn't understand what 3d functions do, so i want some explanation on these functions (3d texture i mean)...
int res = 64;
int nr = res / 2;
int nv = res * 2;
int nb = res / 2;
int na = 8;
f = fopen("E:\\New folder\\ConsoleApplication1\\Debug\\data\\inscatter.raw", "rb");
data = new float[nr*nv*nb*na*4];
fread(data, 1, nr*nv*nb*na*4*sizeof(float), f);
fclose(f);
glActiveTexture(GL_TEXTURE0 + INSCATTER_UNIT);
glGenTextures(1, &inscatterTex);
glBindTexture(GL_TEXTURE_3D, inscatterTex);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA16F_ARB, na*nb, nv, nr, 0, GL_RGBA, GL_FLOAT, data);
delete[] data;

A: 3D textures are volumetric images, i.e. they're sort of a cuboid filled with voxels of color. So instead of a picture of width × height · color_channels you have a picture of width × height × depth · color_channels.
This is an animation showing a volumetric image (courtsey of the research working group I'm a member of): http://www.bmo.physik.uni-muenchen.de/~z19/OCTanimation.gif (unfortunately StackOverflow doesn't allow linking of animated GIFs).
I saw that sb. else was about ocean rendering in another post. Be advised that this is a hugely nontrivial subject requiring some very sophisticated algorithms. The use of a 3D texture called "inscatter" suggests that whatever code you've looked up implements one of those complex models, where the 3D texture is used as a scattering term lookup table.
Note that without a solid understanding of OpenGL and numerical methods implementing an ocean renderer is a almost impossible to perform task. I'd start with understanding the basics first.


text:
Q: glMapBuffer returns random values I am trying to get the vertices in a VBO to generate a fitting bounding box but the values returned from glMapBuffer are random.
Here is my code:
//Data (Quad):
FloatBuffer vertexData = FloatBuffer.wrap(new float[] {
        -0.5f, -0.5f, 0.0f,
        -0.5f, 0.5f, 0.0f,
        0.5f, -0.5f, 0.0f,
        0.5f, 0.5f, 0.0f,
    });

Storing vertices:
//Generating IDs
int vaoID = glGenVertexArrays();
glBindVertexArray(vaoID);
int vboID = glGenBuffers();

//Storing vertex data in attribute list
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, vertexData , GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);

//Unbinding
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

Loading Vertices:
//Binding VAO and VBO
glBindVertexArray(vaoID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
ByteBuffer vertexBuffer = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);

//Printing values
//vertices.flip(); //Do I have to flip it? No, right?
System.out.println("Capacity: " + vertices.capacity() + ", Limit: " + vertices.limit());
//Capacity: 48, Limit: 48, Position: 0
while(vertices.remaining() != 0) {
    System.out.print("x: " + vertices.get());
    System.out.print(", y: " + vertices.get());
    System.out.println(", z: " + vertices.get());
}

//Unbinding
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

The output are random values (mostly just zeros but sometimes random). GlGetError() returns 0 (no errors).
Is this a reasonable way to generate bounding boxes or just dumb? Why are the values random?

A: Unless this is in something you're not showing: glMapBuffer returns a ByteBuffer, so aren't you getting the 4 bytes that make up each float one at a time? So either try casting it to FloatBuffer with vertices.asFloatBuffer, or use getFloat() instead of get().


text:
Q: Openshift Kibana proxy I have a multi-node Openshift cluster (3.9, maybe I will update it to 3.11).
Authentication to Openshift is not managed by Openshift itself, but I have an external provider, Keycloak, where I use ocp_openid_connect.
Installations of Kibana, ES and Fluentd are ok.
The problem is with Kibana-proxy.

*

*Can I get rid of it?

*Can I configure it in order to use ocp_openid_connect?

When I try to access Kibana, I am always redirected to Openshift console.

A: As far as I know, kibana-proxy is needed for OpenShift OAuth. If you want to use authentication(OpenID [0])/authorization(OpenShift), then you need not get rid of kibana-proxy. I think you should use external authentication via OpenShift OAuth.
[0] OpenID Connect


text:
Q: Merge section polygons in PLSS I am trying to merge quarter quarter sections of polygons from PLSS into a quarter section.
However, I also want it assigned to correct Township/Range/Section while merging.
I know I can hand merge all of them using the Editing tool, but since I will have to do to the entire state of Kansas.
I was thinking of writing a script to help.  The problem is that the Township/Range/Section field in the attribute table is in one field and I don't know how to do that when is all together.
I will need to merge those four polygon that belong to the same Township/Range/Sec/qtr as following:
01S01E01NWNE
01S01E01NWNW
01S01E01NWSE
01S01E01NWSW
and I need to leave in 01S01E01NWNW.
Thanks!

A: It looks as though you are using the USGDR data (BLM)
BTW: Dissolve is what you would use instead of merge.
the python part is not my thing.
The dissolve command with the first division identifier column as the
dissolve field should get you what you want
First you want to create a new field to hold the qtr section value for each qtr qtr by using ...
right ([SECDIVNO],2)
{sorry vbscript is how I have to do it until I learn python}
Then run the dissolve on firstdivid
Second Division Identifier  -   WY060480N1030W0SN310ASESW
First Division Identifier  -    WY060480N1030W0SN310


text:
Q: Lookup using table with separated columns I would like to use VLOOKUP() using a table input consisting of columns that are not next to each other.
Example
MyCell = VLOOKUP(A1, MyTable, 2, FALSE)
MyTable = B1:B10 and D1:D10

Is there a way of making this operation work using a lookup function or any other worksheet function? Now I get an error.
Thanks in advance.
Edit:
It's because the table is very large and I'm afraid that the operation will slow down the application if I use the entire table as input

A: In Google Sheets you can use array literals to concatenate two columns:
= VLOOKUP(A1, {B1:B10,D1:D10}, 2, FALSE)

A: =INDEX(D1:D10,match(A1,B1:B10,0))

index/match is typically more efficient than vlookup anyway. if you really want VLOOKUP for just those columns you can use
=VLOOKUP(A1,CHOOSE({1,2},B1:B10,D1:D10),2,FALSE)


text:
Q: MS Excel scroll bar disappeared I'm using MS Excel 2013 on Windows 7. Vertical and horizontal scroll bars have disappeared and I can't find why or how ?
I checked for resolution in the Documentation on Microsoft Support that says this.

But the options are already checked. Can anyone figure out What's the problem ?
Here is the screenshot. Whether it's full screen mode or not, it's the same.

A: You or another user of the sheet may have minimized your horizontal scroll bar to show the maximum number of tabs in the view. The clue is if there are 3 vertical dots next to the add sheet symbol. To fix it click on the three horizontal dots and drag to the left to reveal the scroll bar once more.

A: I had a similar problem. This is what worked for me:
From your active spreadsheet:

*

*Click on the VIEW tab

*Click on ARRANGE ALL

*Click on TILES

*Click on OKAY

A: 1.Click the File tab.
2.Click Options, and then click the Advanced category.
3.Under Display options for this workbook, clear or select the Show horizontal scroll bar check box and Show vertical scroll bar check box to hide or display the scroll bars.

A: In my case, it was that the document window had been made much wider than my monitor screen so I couldn't see the right side of it (including where the scroll bar is).  The other symptom I experienced was that using the right arrow to move the cursor across columns was not resulting in the screen scrolling to the left.  I only saw one rather than two sets of the minimize/full-screen/close icons at the top of my screen (dash, box, X) like I should (one for the Excel program and one for the file itself).  It occurred to me that they must be off the screen on the right side of the page and that I needed to resize the file window to bring the scroll bar back onto the screen the bottom.  If this sounds like your issue...

*

*Drag your file by the file-name bar at the top of the Excel file to the left until you see the right edge of the file.

*Grab the right border of the file and drag it to the left (and move the file back to the right) until it is small enough that both left and right borders are visible on your monitor.

*

*Your scroll bar should now be visible in the lower right.

*Click the full-screen (box icon) to get back to that view if that's what you want.

A: If you tried all of these with no resolve, try saving your work, closing the application and opening the application again.  This worked for me.