text:
Q: How to override the semantic UI Form Input Color? I have been trying to override a semantic UI CSS property in a form input element. I want to change the background color in the input field to white. It keeps showing yellow. I just am testing out different colors and borders trying to get them to work. But nothing does. I have been trying to change it for hours now. Any suggestions?
I have tried the following CSS (and many other things) and none of it works. I am expecting for the background color of the semantic UI form input selector to change because I am trying to over ride it with CSS.
CSS
input {
  background-color: blue !important;
}

ui.input {

  background-color: blue !important;

}
#root > div > div > div.form-container > div > div > form{
  background-color: blue !important;
}
#root > div > div > div.form-container > div > div > form > div:nth-child(1) > div{
  background-color: yellow !important;
}

#root > div > div > div.form-container > div > div > form > div:nth-child(2){
  background-color: yellowgreen !important;
}

div.ui.grid.container > .form-container > .ui.stackable > form{
   background-color: magenta !important;
  }

HTML CODE

              <Form
                onSubmit={onSubmit}
                noValidate
                className={loading ? "loading" : ""}
              >

Log In

                <Form.Input
                  label="Username"
                  placeholder="Username.."
                  name="username"
                  type="text"
                  value={values.username}
                  error={errors.username ? true : false}
                  onChange={onChange}
                />
                <Form.Input
                  label="Password"
                  placeholder="Password.."
                  name="password"
                  type="password"
                  value={values.password}
                  error={errors.password ? true : false}
                  onChange={onChange}
                />
                <Button
                  onClick={() => Redirect("/")}
                  type="submit"
                  id="login-btn"
                  primary
                >
                  Log In
                </Button>
              </Form>
              <Button
                onClick={() => history.push("/register")}
                id="register-btn"
                primary
              >
                Register
              </Button>
              {Object.keys(errors).length > 0 && (

                    {Object.values(errors).map((value) => (

{value}

                    ))}

              )}


text:
Q: Theme-Chooser in Github - to choose a jekyll-theme vanished I am currently setting up a page and I wonder where the GitHub theme-chooser has gone. According to the following instruction, I want to go through the process:

It seems that the theme-chooser has been removed. I want to use the jekyll-theme minimal (like caroly stransky does).

Is this documentation still correct and is the information still relevant?
update: see here the image of how it looks here
i want to add the line that carol did in the configuration; Christian it would be awesome if you can help here...
second update: hi there  - since i cannot see the config.yml i think that i have to add the additional line to the so called raw file: see below the image

can you confirm that is that all right!?
love to hear from you

update3:  well i guess that i ll need to create a new file named "_config.yml" and with this i ll ned to set it's contents to this: ´theme: jekyll-theme-minimal`´ I guess that i have to do this
update4: well i ve created the file - and i guess this is done right - but wait. I have to edit this file correctly
theme: jekyll-theme-minimal

Well i need to add this correctly - not as comment but as content of the file... This is pretty important.

A: The blog post (workwithcarolyn.com/blog/digital-cv-guide) is from 2020. The displayed images are outdated. In a test repo I couldn't find the option to select a theme anymore. The new pages setup page (https://github.com/YOURUSER/REPOSITORY/settings/pages) just contains a link to the docs:

The link to the docs explains how to set a theme for your site. Under point 5 the page says:

Add a new line to the file for the theme name.
To use a supported theme, type theme: THEME-NAME, replacing THEME-NAME with the name of the theme as shown in the README of the theme's repository. For a list of supported themes, see "Supported themes" on the GitHub Pages site.

The supported themes page is linking to the repository of each theme.
Some other themes are remote themes, e.g. Minimal. The repository explains how to add the theme:

To use the Minimal theme:
Add the following to your site's _config.yml:

remote_theme: pages-themes/minimal@v0.2.0
plugins:
  - jekyll-remote-theme

You can have a look at https://github.com/cadamini/test/blob/main/_config.yml  and the resulting page at https://cadamini.github.io/test/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Url gets stripped I have an issue where I can console log the url when it in a var but the moment that I add it back to the page within html it strips the forward slashes.
does anyone know why this would happen. I have tried to change this in any way possible but I am coming up short on why this is happening.
function hiddenlinks() {
    var urllink = $(".hidden-small").map(function() {
        return $(this).attr("href");
    }).get().reverse();
    console.log(urllink);
    var spantext = $(".hidden-small span").map(function() {
        return $(this).text();
    }).get();
    for ( var i = 0; i < urllink.length; i++ ) {
        for ( var i = 0; i < spantext.length; i++ ) {
            console.log(urllink[i])
            var urlencode = urllink[i];
            console.log(urlencode);
            var finlink = '
'+spantext[i]+'
'
            $( finlink ).prependTo( ".paradeiser_children" );
        }
    }
}

A: try to change,
for ( var i = 0; i < urllink.length; i++ ) {
     for ( var i = 0; i < spantext.length; i++ ) {

to
for ( var i = 0; i < urllink.length; i++ ) {
     for ( var j = 0; j < spantext.length; j++ ) {

A: Alright, I am guessing that you have the same number of SPANs as the number of links and trying to construct those many LIs. You could make it a bit more simpler/cleaner using $.each() as below.
function hiddenlinks() {
    var urllink = $(".hidden-small").map(function() {
        return $(this).attr("href");
    }).get().reverse();
    console.log(urllink);

    var spantext = $(".hidden-small span").map(function() {
        return $(this).text();
    }).get();

    var $items = $();
    $.each(urllink, function(i, url) {

        $items = $items.add(
            $("
", {
                html: '' + spantext[i] + ''
            })
        );
    });
    $(".paradeiser_children").prepend($items);
}

A: Add an missing equal sign after the href:
 <a href="'+urlencode+'"


text:
Q: Is it possible that GEE and mixed effect GLM give contradicting answers? If so, which one should be trusted? Is it possible that GEE and mixed effect GLM give contradictive answers in significance of covariates? I assume both GEE and GLM selects same covariates. If so, which one should be trusted?
From asymptotic viewpoint, GEE and GLM should give same answer. However, I am always in finite sample case. The same answer is not guaranteed.

A: Do you mean inference rather than "answer", in terms of the supposed contradictions? Then yes for a number of reasons. A non-comprehensive list:

*

*There is not a perfect 1-1 correspondence between the types of models GEE and LME fit. Consider variance structures versus random effects. For instance, a single random intercept cannot induce a negative correlation within subjects in the same cluster, but the WLS estimator with exchangeable correlation can. Even when positive intraclass correlation is met, the estimates induced by random effect variance may not be the same as those from WLS.

*The GEE is not a maximum likelihood procedure, and so handles missing and unbalanced data differently. LME places relatively more weight on subjects with sparser data.

*GEE is, in general, more robust to model specification whereas LME is, in general, more efficient with smaller sample sizes.

*When considering marginal models for response, such as the famous example of educational attainment versus age in a sample with a strong cohort effect, the LME is powered to detect individual level effects, or conditional effects, whereas the GEE is powered to detect population-average effects.


text:
Q: Cross Compiling libogg for iOS I've been trying to cross compile libogg for armv6, armv6 and i386 using the iOS 5.1 SDK in Mountain Lion.  Libogg uses autoconf, and I've been having pretty similar issues with a few other libraries as well. I picked up a neat little cross-compiling script from here. I had to update it a bit to find the location of the SDK's.
GLOBAL_OUTDIR="`pwd`/dependencies"
mkdir -p $GLOBAL_OUTDIR/include $GLOBAL_OUTDIR/lib
OUTDIR="./outdir"
OGG_LIB="`pwd`/libogg-1.3.0"

IOS_BASE_SDK="5.1"
IOS_DEPLOY_TGT="3.2"

setenv_all()
{
# Add internal libs
export CFLAGS="$CFLAGS -I$GLOBAL_OUTDIR/include -L$GLOBAL_OUTDIR/lib"

export CXX="$DEVROOT/usr/bin/llvm-g++-4.2"
    export CC="$DEVROOT/usr/bin/llvm-gcc-4.2"

export LD=$DEVROOT/usr/bin/ld
export AR=$DEVROOT/usr/bin/ar
export AS=$DEVROOT/usr/bin/as
export NM=$DEVROOT/usr/bin/nm
export RANLIB=$DEVROOT/usr/bin/ranlib
export LDFLAGS="-L$SDKROOT/usr/lib/"

export CPPFLAGS=$CFLAGS
export CXXFLAGS=$CFLAGS
}

setenv_arm6()
{
unset DEVROOT SDKROOT CFLAGS CC LD CPP CXX AR AS NM CXXCPP RANLIB LDFLAGS CPPFLAGS CXXFLAGS

export DEVROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer
export SDKROOT=$DEVROOT/SDKs/iPhoneOS$IOS_BASE_SDK.sdk

export CFLAGS="-arch armv6 -pipe -no-cpp-precomp -isysroot $SDKROOT -miphoneos-version-min=$IOS_DEPLOY_TGT -I$SDKROOT/usr/include/"

setenv_all
}

setenv_arm7()
{
unset DEVROOT SDKROOT CFLAGS CC LD CPP CXX AR AS NM CXXCPP RANLIB LDFLAGS CPPFLAGS CXXFLAGS

export DEVROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer
export SDKROOT=$DEVROOT/SDKs/iPhoneOS$IOS_BASE_SDK.sdk

export CFLAGS="-arch armv7 -pipe -no-cpp-precomp -isysroot $SDKROOT -miphoneos-version-min=$IOS_DEPLOY_TGT -I$SDKROOT/usr/include/"

setenv_all
}

setenv_i386()
{
unset DEVROOT SDKROOT CFLAGS CC LD CPP CXX AR AS NM CXXCPP RANLIB LDFLAGS CPPFLAGS CXXFLAGS

export DEVROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer
export SDKROOT=$DEVROOT/SDKs/iPhoneSimulator$IOS_BASE_SDK.sdk

export CFLAGS="-arch i386 -pipe -no-cpp-precomp -isysroot $SDKROOT -miphoneos-version-min=$IOS_DEPLOY_TGT"

setenv_all
}

create_outdir_lipo()
{
for lib_i386 in `find $LOCAL_OUTDIR/i386 -name "lib*\.a"`; do
    lib_arm6=`echo $lib_i386 | sed "s/i386/arm6/g"`
    lib_arm7=`echo $lib_i386 | sed "s/i386/arm7/g"`
    lib=`echo $lib_i386 | sed "s/i386\///g"`
    lipo -arch armv6 $lib_arm6 -arch armv7 $lib_arm7 -arch i386 $lib_i386 -create -output $lib
done
}

merge_libfiles()
{
DIR=$1
LIBNAME=$2

cd $DIR
for i in `find . -name "lib*.a"`; do
    $AR -x $i
done
$AR -r $LIBNAME *.o
rm -rf *.o __*
cd -
}

And then to build the ogg library.
## libogg
cd $OGG_LIB
rm -rf $OUTPUT_DIR
mkdir -p $OUTDIR/arm6 $OUTDIR/arm7 $OUTDIR/i386

## Build for armv6
make clean 2> /dev/null
make distclean 2> /dev/null
setenv_arm6
./configure --host=arm-apple-darwin6 --enable-shared=no
make
cp /src/.libs/libogg.a $OUTDIR/arm6

## Build for armv7

make clean 2> /dev/null
make distclean 2> /dev/null
setenv_arm7
./configure --host=arm-apple-darwin7 --enable-shared=no
make
cp src/.libs/libogg.a $OUTDIR/arm7

## Build for iPhone simulator
make clean 2> /dev/null
setenv_i386
./configure
make -j4
cp src/.libs/libogg.a $OUTDIR/i386

## Stich it altogether in a fat .a file.
create_outdir_lipo

Anyway, when building armv6 and armv7, configure finds the compiler's and sdk's okay , and the compiling stage goes off without a hitch.  But they both fail to link. The armv7 build spits out the error.
ld: in section __TEXT,__text reloc 1: unknown relocation type 9 for architecture armv7 collect2: ld returned 1 exit status

And when I test the output binary with lipo :
$ lipo -info libogg.a
lipo: archive with no architecture specification: libogg.a (can't determine architecture for it)

What is strange is i386 seems to compile perfectly, (I've tried it in the simulator and all is okay).
Any suggestions on what I can do to try and fix this, or a least where I should start looking. Sorry for the massive code dumps, and thanks.

A: I was able to solve this by setting the optimization level on the compile to -O3 instead of -O4. With -O4 the files output do not seem to be recognizable to lipo (and even file reports them as data instead of Mach-O object arm).
Update: It seems quite a few people are encountering difficulty compiling Ogg Vorbis. I have made my build available. See: Precompiled Ogg Vorbis Libraries for iOS.


text:
Q: Change default program I know that this question was also asked here, but I have a slightly different problem.
I want to open CSV files using sublime instead of Calc.
However, sublime does not even appear to my applications, when I follow the procedure at mentioned at that answer, in order to select that as default.
I am using Ubuntu 14.04 desktop edition with Unity.
How can I do that?

A: OK, the answer was at this post. What should be done is to execute the following command:

gksudo gedit /usr/share/applications/sublime.desktop

find the exec line:

Exec=sublime

and add an "%f" next to it

Exec=sublime %f

In any case sublime can be replaced by the program you want to add to the applications list.


text:
Q: Sum of residuals of scipy regression model I am going through a stats workbook with python, there is a practice hands on question on which i am stuck. Its related to Poisson regression and here is the problem statement:-
Perform the following tasks:

*

*Load the R data set Insurance from MASS package and Capture the data as pandas data frame

*Build a Poisson regression model with a log of an
independent variable, Holders and dependent variable Claims.

*Fit the model with data.

*Find the sum of residuals.

I am stuck with point 4 above. Can anyone help with this step?
Here is what i have done so far :-
import statsmodels.api as sm
import statsmodels.formula.api as smf
import numpy as np
df = sm.datasets.get_rdataset('Insurance', package='MASS', cache=False).data
poisson_model = smf.poisson('np.log(Holders) ~ -1 + Claims', df)
poisson_result = poisson_model.fit()
print(poisson_result.summary())

Now how to get sum of residuals?

A: np.sum(poisson_result.resid)
works fine
You have used the wrong variables to build the poisson model as pointed out by Karthikeyan.
Use this instead,
poisson_model = smf.poisson('Claims ~ np.log(Holders)',df)

A: Try below code for Fresco play
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd
import numpy as np
df_insurance=sm.datasets.get_rdataset("Insurance","MASS")
df_data=df_insurance.data
insurance_model=smf.poisson('Claims ~ np.log(Holders)', df_data).fit()
print(np.cumsum(insurance_model.resid))

A: 1.a) Load the R data set Insurance from MASS package
1.b) and Capture the data as pandas data frame
2) Build a Poisson regression model with a log of an independent variable, Holders and dependent variable Claims.
3) Fit the model with data.
4) Find the sum of residuals.
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd
import numpy as np

#load the R data set insurrance from MASS package
ins = sm.datasets.get_rdataset('Insurance','MASS').data
# capture the data as pandas data frame
ins_pd = pd.DataFrame(ins)
# build a poisson regressions model with
# a log of an independent variable "Holders"
# and dependent variable "Claims"
# fit the model with data
result = smf.poisson('Claims ~ np.log(Holders)',data=ins).fit()
# you can also use
# model = smf.poisson('Claims ~ np.log(Holders)',data=ins)
# result = model.fit()

# Find tue sum of residuals
print('Sum ot the residuals:',np.sum(result.resid))

i'm new on this so i don't know if capture the data as panda dataframe is fine or not but letme now
greetings

A: Fresco Mex
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd
import numpy as np

df_data=sm.datasets.get_rdataset("Insurance","MASS").data
df_dataf= pd.DataFrame(df_data)
insurance_model=smf.poisson('Claims ~ np.log(Holders)',df_data)
insurance_model_result=insurance_model.fit()
print(np.sum(insurance_model_result.resid))

A: in the poisson_model = smf.poisson('np.log(Holders) ~ -1 + Claims', df) statement, the dependent variable "Claims" should come in the right hand side
poisson_model = smf.poisson('Claims ~ np.log(Holders)-1 ', df)

A: this qualified in "Fresco" if anyone is looking for the solution
df_insurance=sm.datasets.get_rdataset("Insurance","MASS")
df_data=df_insurance.data
insurance_model=smf.poisson('Claims ~ np.log(Holders)',df_data)
insurance_model_result=insurance_model.fit()
res=(insurance_model_result.resid)
print(np.sum(res))

A: I don't know it will work or not .but I  refer this docs
https://vincentarelbundock.github.io/Rdatasets/doc/MASS/Insurance.html
https://vincentarelbundock.github.io/Rdatasets/datasets.html
So  I hope this will work too.
import statsmodels.api as sm
import  statsmodels.formula.api as smf
import numpy as np
import pandas as pd

data=pd.DataFrame(sm.datasets.get_rdataset("Insurance","MASS",cache=True).data)
model=smf.poisson('Claims ~ District + Group + Age + np.log(Holders)',data).fit()
print(np.sum(model.resid))

A: Try np.cumsum(model.resid) for this question.
Ideally np.sum(model.resid) should be the right answer for the question... But if the system is not accepting it, try the cumsum


text:
Q: PHP insert into mysql database with dates I would like to be able to add children into a database, which are connected to their parents (who has a member id MID). I believe that the error lies within the date format (atleast that's what I believe), I have also tried to use strtotime($dob), however this didn't change anything.
   $name = htmlspecialchars($_GET['Name']);
   $dob = $_GET['DOB'];
   $newDOB = date("Y-m-d", $dob);
   $mid = $_GET['mid'];

   if(isset($_GET['Name'], $_GET['DOB'], $_GET['mid']))
       $alert = true;
   if(!empty($name) && !empty($newDOB) && !empty($mid))
       add_family_member($mid, $newDOB, $name);

The function that adds the member:
function add_family_member($mid, $dob, $name)
{
    global $con;
    $sql = "INSERT INTO Children(MID, DOB, Name) VALUES(?, ?, ?)";
    $stmt = $con->prepare($sql);
    if($stmt)
    {
        $b = $stmt->bind_param("iss", $mid, $dob, $name);
        if($b)
        {
            $e = $stmt->execute();
            if($e)
                return true;
        }
    }

    return false;
}

A: function add_family_member($mid, $dob, $name)
{
    global $con;
    $sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
    $stmt = $con->prepare($sql);
    if($stmt)
    {
        return $stmt->execute(array(
             'mid' => $mid,
             'dob' => $dob,
             'name' => $name
        ));
    }

    return false;
}

see http://www.php.net/manual/en/pdostatement.execute.php for more examples

A: Try...
function add_family_member($mid, $dob, $name)
    {
        global $con;
        $sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
        $stmt = $con->prepare($sql);
        $stmt->bindParam(':mid', $mid);
        $stmt->bindParam(':dob', $dob);
        $stmt->bindParam(':name', $name);
        if ($stmt->execute()) {
            return true;
        }
        return false;
    }


text:
Q: How to set windows path regex pattern? I have a list of paths, and I need a match for all starting with C:\Program Files\_folder_\_folder_\etc and then having any amount and any type of character a windows path can use.
This is how I approach, though I guess this only allows alpanumeric characters:
string pathPattern = @"C:\Program Files\_folder_\_folder_\etc[0-z]*";
if (System.Text.RegularExpressions.Regex.IsMatch(myList[n], pathPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
    {
        //some action
    }

A: If C:\Program Files\_folder_\_folder_\etc is the pre-defined part. I think you can do this without Regex like this using Contains
if(pathPattern.Contains(@"C:\Program Files\_folder_\_folder_\etc"))
{
    //some action
}

Edit 1: You can do ToLower() on pathPattern
var ss = pathPattern.ToLower().Contains(@"C:\Program Files\_folder_\_folder_\etc".ToLower());

A: 1. If you want your path should starts with :

C:\Program Files\

then use below code :
if (Regex.IsMatch(code, @"[cC]{1}\:\\Program Files\\.*"))
{
   \\ Do Your work
}

2. If you want your path should starts with :

c:\Program Files_folder__folder_\

then use below code :
if (Regex.IsMatch(code, @"[cC]{1}\:\\Program Files\\_folder_\\_folder_\\.*"))
{
    \\ Do Your work
}

Description:

*

*cC{1} : Check for C drive (c:)

*@"[cC]{1}\:\Program Files\ : Check for C:\Program Files

*.* : Checks for any folder after C:\Program Files

A: Try this regex
^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$

Sample Code
string path = @"C:\Program Files\_folder_\_folder_\";
string pathPattern = @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$"

if(System.Text.RegularExpressions.Regex.IsMatch(path, pathPattern)){
    //It matches the regex
}
else
{
    //it doesnot matches the regex
}

Works for these:
\\test\test$\TEST.xls
\\server\share\folder\myfile.txt
\\server\share\myfile.txt
\\123.123.123.123\share\folder\myfile.txt
c:\folder\myfile.txt
c:\folder\myfileWithoutExtension


text:
Q: error 0xC00CE020: App manifest validation error: The app manifest must be valid as per schema ,,, Required attribute 'ForegroundText' is missing Launched a "blank Windows 10 Universal App" using "Visual Studio 2015 RC". I am not able to see the design view for MainPage.xaml. The designer shows the following Error:

error 0xC00CE020: App manifest validation error: The app manifest must be valid as per schema: Line 20, Column 8, Reason: Required
  attribute 'ForegroundText' is missing

Tried including 'ForegroundText="dark"' attribute in Package.appxmanifest file but the attribute seems to be undeclared for VisualElements.
     <uap:VisualElements
          DisplayName="BackgroundSensorsCS"
          Square150x150Logo="Assets\squareTile-sdk.png"
          Square44x44Logo="Assets\SmallTile-sdk.png"
          Description="BackgroundSensorsCS"
          BackgroundColor="#00b2f0"
          **ForegroundText="dark"**>
            <uap:SplashScreen Image="Assets\Splash-sdk.png" />
            <uap:DefaultTile>
                <uap:ShowNameOnTiles>
                    <uap:ShowOn Tile="square150x150Logo" />
                </uap:ShowNameOnTiles>
            </uap:DefaultTile>
        </uap:VisualElements>

A: I was able to fix it by selecting Lock screen notifications item.

A: The issue was resolved after re-installing Visual Studio 2015 RC on Windows 10 Preview, Build 10074.

A: Somehow, I started experiencing a similar issue while developing a UWP app. It said some 'Wide..' attribute was not defined in the DTD. So I went to the project's properties > Application and tried to open the package manifest. I then deleted the faulty attribute from the manifest xml, restarted VS and opened package manifest file again which opened this time fine.
So, something there seems to have fixed the issue. Also, I cleaned the deployment inside bin > Debug and re-deployed, which worked this time.

A: For me, today, Visual Studio 2022, this happened after adding Badge Logos to the Visual Assets in the App Manifest, for store distribution. Apparently, when you add badges it is assumed you are receiving notifications, and you are required to select "Lock screen notifications" in the "Application" tab in the package manifest editor. Once you select Lock screen notifications: Badge the error disappears. Or, remove the Badge Logos if you don't need them.

A: Solution Explorer -> Package.appxmanifest -> right click -> View code ->
Find the tag: <mp:PhoneIdentity PhoneProductId="### GUID ###"
-> Add property PhonePublisherId="### GUID ###"
I've added the same ID like my publisher ID
Good luck...


text:
Q: tomcat 8 upgrade from tomcat 6 - classloading performance issue Background
Application server has been upgraded from tomcat 6 to tomcat 8. We are experiencing performance issues in transactions which involve XML processing using DOM4J and xerces api. The application uses dom4j-1.6.1.jar and xercesImpl-2.10.0.jar. There has been no change in the application which was deployed in tomcat 6 to the application deployed in tomcat 8.
Problem
We use Dynatrace to monitor our application. We have seen that in tomcat 8, the time taken for classloading api has increased significantly, leading to performance degradation. This

shows the time taken by the classloading api in Tomcat 8 and this

shows what was happening in tomcat 6.
From the above pics, we can see that Classloading is invoked from the xerces apis(Xml Processing in the pic), so the transactions using the xerces api have show performance degradation.
Please help in understanding why the classloading times have increased in tomcat 8 and how to get rid of this problem in tomcat8. Thanks.

A: Have you seen this blog? Check out the first comment which talks about configuration settings for Xerces: http://apmblog.dynatrace.com/2015/05/14/java-performance-impact-by-dynamic-class-loading/


text:
Q: How to style a label without an ID or class associated with it? I got a FluentForm form embedded in a wordpress page. I need to style one of the labels that don't have an ID or class nor can I add one. Is there a way to style what is marked in the screenshot below?

A: Since the label has a for attribute, you can use that in your selector.

label[for="selector"] {
  color: red;
  font-weight: bold;
}
Pick Me

A: You can select label with label[for=ff_150_description_3] and style it:

label[for=ff_150_description_3] {
  color: red;
}
aaa


text:
Q: Sending large files over socket I got working over socket file sender, it worked perfectly, but I couldn't send large files with it. Always got heap error. Then I changed the code of client, so it would send file in chunks. Now I can send big files, but there is new problem. Now I recieve small files empty and larger files for example videos can't be played. Here is the code of client that sends file:
public void send(File file) throws UnknownHostException, IOException {

    // Create socket
    hostIP = "localhost";
    socket = new Socket(hostIP, 22333);

    //Send file

    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);

    DataInputStream dis = new DataInputStream(bis);

    OutputStream os = socket.getOutputStream();

    //Sending size of file.
    DataOutputStream dos = new DataOutputStream(os);
    dos.writeUTF(file.getName() + ":" + userName);

    byte[] arr = new byte[1024];
    try {
        int len = 0;
        while ((len = dis.read(arr)) != -1) {
            dos.write(arr, 0, len);

        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    dos.flush();

    socket.close();
}

and here is the server code:
void start() throws IOException {

        // Starts server on port.
        serverSocket = new ServerSocket(port);

        int bytesRead;

        while (true) {
            connection = serverSocket.accept();

            in = connection.getInputStream();

            clientData = new DataInputStream(in);

            String[] data = clientData.readUTF().split(":");
            String fileName = data[0];
            String userName = data[1];

            output = new FileOutputStream("C:/" + fileName);
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];

            // Build new file
            while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }
            output.close();
        }
    }

A: You failed to write out the length of the file to the stream in the client:
long size = clientData.readLong();

So that call in the server is reading the first 8 bytes of the actual file and who knows what that quantity is.  You don't have to read the length from the stream since you only wrote a single file.  After reading the filename, and username (not very secure is it?) you can just read the stream until EOF.  If you ever wanted to send multiple files over the same open socket then you'd need to know the length before reading the file.
Also your buffers for reading are way to small.  You should be at a minimum of 8192 instead of 1024.  And you'll want to put all .close() in a finally block to make sure your server and clients shutdown appropriately if there is an exception ever.


text:
Q: Shell globbing without matching files I frequently make use of shell file name globbing to do things like operate on all of /dev/sda, /dev/sdb, /dev/sdc, etc by doing /dev/sd[a-f], however, this relies on there being files on disk that match that pattern.  Today I wanted to run gitk on each of master@{1}, master@{2}, etc, but gitk master@{[1-5]} does not work since there are no file names matching that pattern on disk.
How can you get the shell to perform globbing without regard to actual disk files?

A: You can't do shell globbing without matching files. You need brace expansion:
gitk master@{{1..5}}

or:
gitk master@{{1,2,3,4,5}}

With form {x..y}, you need zsh 2.6-beta4 and later, bash 3.0 and later, ksh93r and later.
{x,y} was original in csh and copied to Bourne like shell first in ksh.

A: In at least bash you can use ranges, e.g.
$ echo gitk master@{{1..5}}
gitk master@{1} master@{2} master@{3} master@{4} master@{5}

Obviously the echo is used above just to show what happens.
It works for letters as well:
$ echo /dev/sd{x..z}
/dev/sdx /dev/sdy /dev/sdz

Note: the is glob matching, and there is regex matching. These are two distinct things. The shell does glob matching. So Shell regex globbing is not a thing.


text:
Q: Improving test class coverage Can any one help me in increasing code coverage .for the below class and test class.
Class:
global class Clear_Territory_Flag_Batch implements Database.Batchable<sObject> {

    global String sql;

    global Database.QueryLocator start(Database.BatchableContext BC) {

   sql='select id,Territory_Update_Falg__c from opportunity where

Territory_Update_Falg__c=true and lastmodifieddate=today';

     return Database.getQueryLocator(sql);

    }

     global void execute(Database.BatchableContext BC, List<SObject> objs) {

       List<Opportunity> Opptys=new List<Opportunity>();

       for(Opportunity o:(List<Opportunity>)objs){

         o.Territory_Update_Falg__c=false;
         Opptys.add(o);

       }

       if(Opptys.size()>0){

          OpportunityTriggerHandler.skipTriggerProcessing = true;
             update Opptys;
          OpportunityTriggerHandler.skipTriggerProcessing = false;
          }
     }

     global void finish(Database.BatchableContext BC) {

       }
}

Test Class:
@isTest(SEEALLDATA=TRUE)

  public class TestClear_Territory_Flag_Batch {

    static testMethod void testMethod1()

    {

   List<Opportunity> st=new List<Opportunity>([Select id , Name , Territory_Update_Falg__c from Opportunity where Territory_Update_Falg__c = true  ]);

    for(integer i=0;i<1500;i++) {

   Opportunity t=new Opportunity();

    t.Territory_Update_Falg__c = true;

    //t.id='0000000123';
    st.add(t);
 }

    Database.BatchableContext bc;

    Clear_Territory_Flag_Batch obj =new Clear_Territory_Flag_Batch();

   //st=obj.start(b);

  obj.execute(bc,st);

   obj.finish(bc);

   }

}

A: Please, check Adding a Test for the Batch Apex Class

A: @isTest
public class TestClear_Territory_Flag_Batch {
static testMethod void testMethod1()

{
 List<Opportunity> oppListToInsert=new List<Opportunity>();
//insert some Opportunity records
for(integer i=0;i<10;i++) {

    Opportunity opp=new Opportunity();
    opp.Name ='Test Opp'+i;
    opp.Territory_Update_Falg__c = true;
    //assign every require fields like closedate, stagename etc

    oppListToInsert.add(opp);
 }
try{
    insert oppListToInsert;
}catch(Exception e){
    system.debug('******Error in--'+e.getMessage());
}

Clear_Territory_Flag_Batch obj =new Clear_Territory_Flag_Batch();
database.executeBatch(obj,5);

}
}
Do let me know if it works for you. Thanks!!

A:  Create a new test method for this condition to make this condition false

if(Opptys.size()>0){
      OpportunityTriggerHandler.skipTriggerProcessing = true;
         update Opptys;
      OpportunityTriggerHandler.skipTriggerProcessing = false;
      }


text:
Q: How can I be sure "apt-get install" successfully finished its work? I have Ubuntu 14.04 and I intend to download Skyrim. So I put the command into the terminal sudo apt-get install playonlinux.
Everything was loading fine and it seemed to be working, however before it finished it brought up:
Setting up libpam-winbind:amd64 (2:4.1.6+dfsg-1ubuntu2.14.04.7) ...
Setting up odbcinst1debian2:amd64 (2.2.14p2-5ubuntu5) ...
Setting up liblwp-protocol-https-perl (6.04-2ubuntu0.1) ...
Setting up libwww-perl (6.05-2) ...
Setting up icoutils (0.31.0-2) ...
Setting up unixodbc (2.2.14p2-5ubuntu5) ...
Setting up gnome-exe-thumbnailer (0.9.3-0ubuntu1) ...
Setting up odbcinst (2.2.14p2-5ubuntu5) ...
Setting up wine1.6 (1:1.6.2-0ubuntu4) ...
Setting up wine1.6-i386 (1:1.6.2-0ubuntu4) ...
Setting up wine (1:1.6.2-0ubuntu4) ...
Setting up playonlinux (4.2.2-1) ...
Setting up wine1.6-amd64 (1:1.6.2-0ubuntu4) ...
Processing triggers for libc-bin (2.19-0ubuntu6.5)
Setting up libpam-winbind:amd64 (2:4.1.6+dfsg-1ubuntu2.14.04.7) ...
Setting up odbcinst1debian2:amd64 (2.2.14p2-5ubuntu5) ...
Setting up liblwp-protocol-https-perl (6.04-2ubuntu0.1) ...
Setting up libwww-perl (6.05-2) ...
Setting up icoutils (0.31.0-2) ...
Setting up unixodbc (2.2.14p2-5ubuntu5) ...
Setting up gnome-exe-thumbnailer (0.9.3-0ubuntu1) ...
Setting up odbcinst (2.2.14p2-5ubuntu5) ...
Setting up wine1.6 (1:1.6.2-0ubuntu4) ...
Setting up wine1.6-i386 (1:1.6.2-0ubuntu4) ...
Setting up wine (1:1.6.2-0ubuntu4) ...
Setting up playonlinux (4.2.2-1) ...
Setting up wine1.6-amd64 (1:1.6.2-0ubuntu4) ...
Processing triggers for libc-bin (2.19-0ubuntu6.5) ...
moonshadows@moonshadows-A740GM-M:~$

It doesn't look like an error, however it does not look like it finished downloading. My question is, is there something more I need to type in to finish the process or is it done? I don't want to close out of the terminal until I am sure I am done so that I don't have to repeat everything.  Any help or insight would be greatly appreciated! Thank you!

A: No problems here!
The moonshadows@moonshadows-A740GM-M:~$ part is where you can enter your commands, so whenever it comes up, you know the previous process has finished.
So you can safely exit the terminal and playonlinux will work fine.


text:
Q: Solution for a second order ODE with initial conditions Suppose you have a second order differential equation as
$$\ddot{\theta}+C\dot{\theta}+K\theta=0$$
Where $\theta(t)$ represents the  angle at time $t$. $K,C$ are constants
Then if $C^2-4K<0$ we have the solution as:
$\theta(t)=Ae^{-ct/2}\cos(\frac{\sqrt{4K-C^2}}{2}t)+Be^{-ct/2}\sin(\frac{\sqrt{4K-C^2}}{2}t)$.
This can be rewritten as $\theta(t)=De^{-ct/2}\sin(\frac{\sqrt{4K-C^2}}{2}t+E)$.
My question is, if we have two initial conditions as:
$\theta(0)=\frac{\pi}{3}radians$
$\dot{\theta}(0)=0$
Then how should I find the arbitary constants $D \& E$?  Because if I directly plug in the values you get:
$\theta(0)=D\sin(E)=\pi/3$
$\dot{\theta}(0)=D\sin(E)+D\frac{\sqrt{4K-C^2}}{2}\cos(E)=0$
Appreciate your help

A: $$\dot{\theta}(0)=D\sin(E)+D\frac{\sqrt{4K-C^2}}{2}\cos(E)=0$$
Divide by $D \sin E$:
$$\frac{\sqrt{4K-C^2}}{2} \dfrac {\cos E}{\sin E}=-1$$
$$\tan E= -\frac{\sqrt{4K-C^2}}{2}$$


text:
Q: HTML/rich text email signatures in iOS? My work (Exchange) email signature has text formatting and a photo in it, as I'm sure many do. Does anyone know of a way to enable Apple Mail like signature customization in iOS?
My iPhone is jailbroken, so if you have a jailbreak solution that works I'm good with that.

A: There's a JailBreak Tweak called Mail Enhancer that does exactly what you want. It's $4.99 in the BigBoss repository, and there's another one called SIGnify for $1.50 in the ModMyi repo. They both allow you to have signatures with HTML formatting, but the more expensive one has many more features that make the Mail.app much more usable.

A: Here's an interesting workaround for getting rich-text signatures to cooperate in iOS' mail.app (without jailbreaking):

*

*Select the rich text you want to use for your signature

*Paste into empty signature field for account within Mail settings

*Shake to Undo and you should see "Undo Change Attributes" prompt

*Pasted text should now appear formatted as it was originally copied

This works well in my testing within iOS7, however inline images still are not supported (they show within the signature field in settings but end up as attachments when emailed)
/via http://forums.macrumors.com/showthread.php?t=1522622


text:
Q: 3rd grade math problem My niece asked me to help her with a problem, since she and her parents couldn't figure it out.
The question was:
abcde - fghi = 42137
with a-i being 1-9 (so for example 12345 - 6789), with each digit appearing once.
I had no idea how to do this intelligently, and wrote some code which brute-forced through all permutations of 1-9 and give me the results ((43726, 1589),(43789, 1652),(47326, 5189),(47398, 5261)).
How would I go about this as a 9 year old student who cannot code this? Just trial and error?
All we could really say is that the first digit is a 4 or 5, but thats it, aside from that it was just trying, and at some point I was so pissed with that task I wrote code to deal with it.

A: If $abcde-fghi=42137$, then (supposing no carrying operations are expected of the student) $e$ and $i$ must be either $8$ and $1$ or $9$ and $2$. Suppose they are $9$ and $2$. Then we have $\{1,3,4,5,6,7,8\}$ remaining.
  Then $a$ must be $4$ as we've used the $9$. Remaining: $\{1,3,5,6,7,8\}$.
 Now we can use $8$ and $5$ in the spots of $d$ and $h$ to make $3$. Remaining: $\{1,3,6,7\}$.
Now we can use $7$ and $6$ for $c$ and $g$ to make $1$. Remaining: $\{1,3\}$.
And obviously, we can use $3$ and $1$ for $b$ and $f$ to make $2$.
So we have $43789 - 1652 = 42137$.
We got here more or less deductively from the initial assumptions --- the total number of 'guesses' I had to take was actually only two --- I guessed that we need to use $9$ and $2$ to make $7$ as opposed to $8$ and $1$, and I guessed the order in which I had to proceed. Note that there aren't that many integer combinations in this puzzle anyway.
It is, however, not a good problem --- if you really think about it and begin to consider the possibility of carrying operations being necessary, then it becomes much more intimidating. I don't think this is pedagogically useful in teaching math --- if anything, it teaches the student a haphazard trial-and-error approach, instead of cementing the foundations of deductive argument.


text:
Q: Python escape character mixed with backslash n for newline I have a function in python which return a huge text table in a neat format.
My output has multiple \n an \t.
I can print out the output and it would have preserved the table format. However, in a python interactive window,I want to call the function and not store it the output but display it on console screen.
What I see is \\n instead of \n.
I understand that \ is an escape character.But what do I do make my python interactively handle the formatting.
eg. for descriptive purpose only
def print_table():
    return table;

>>> print_table() #is there anything I can do here to have neat display
>>> r0c0 r0c1 \nr1c0 r1c1
>>> print (print_table())
>>> r0c0 r0c1
    r1c0 r1c1

I am using Python3.6

A: Have you tried pretty printer?
from pprint import pprint
pprint(print_table)

A: You could store the result in a variable
>>> def print_table():
>>>    return table

>>> my_table = print_table()
>>> print(my_table)
>>> r0c0 r0c1
    r1c0 r1c1


text:
Q: Read geotiff files alttitude using GDAL I am using GDAL to read a geotiff file.
I would like to read the coordinate Z of my geotiff file.
has anyone worked on a case before ?
Regard,

A: I have managed to read the elavation from osgeo import gdal
gdal.UseExceptions()

ds = gdal.Open('test_data.tif')
band = ds.GetRasterBand(1)
elevation = band.ReadAsArray()

print elevation.shape
print elevation


text:
Q: how to write a regex to parse refs/changes I have the following as input. I am trying to write a regular expression which yields the below output. Can anyone provide
input on how to do this?
INPUT:-

refs/changes/44/1025744/3
refs/changes/62/1025962/5
refs/changes/45/913745/2

OUTPUT:-
1025744/3
1025962/5
913745/2

A: >>> import re
>>> input="""refs/changes/44/1025744/3
... refs/changes/62/1025962/5
... refs/changes/45/913745/2"""
>>> res=re.findall(r'.*/.*/.*/(.*/.*)',input)
>>> for i in res:
...    print i
...
1025744/3
1025962/5
913745/2

A: If you are feeding the input line by line, you could do this:
import re
instr = 'refs/changes/44/1025744/3'
print get_match(instr)

def get_match():
    match = re.match("^(refs/changes/[0-9]*/)([0-9/]*)", instr)
    if match:
        return match.group(2)

A: If that is the actual import format, a regex is not needed:
>>> source = """\
... refs/changes/44/1025744/3
... refs/changes/62/1025962/5
... refs/changes/45/913745/2
... """
>>> output = [line.split('/', 3)[-1] for line in source.splitlines()]
>>> output[0]
'1025744/3'
>>> output[1]
'1025962/5'

You can also have them all in one string, like this:
>>> ' '.join(line.split('/', 3)[-1] for line in source.splitlines())
'1025744/3 1025962/5 913745/2'


text:
Q: SQL having trouble getting desired query Say we have the following relation:
Author(name,title,language)
What I'm trying to accomplish is to make query that lists all the authors and how many books in a particular language they made, and if they made none in that language then display zero.
What I've tried so far is this
select name, count("language") as SomeLanguage
from Author
where "language"='English'
group by name;

Which gives the count of how many books in the specified language they made, but I don't know how to include the other authors that did not write a book in that language.
Example Output:
Name | SomeLanguage
----------------
Bill | 4
Rob  | 1
Bob  | 0

A: You want conditional aggregation:
select name,
       sum(case when language = 'English' then 1 else 0 end) as SomeLanguage
from Author
group by name;


text:
Q: DSPIC30f timer1 not trigger everytime on POR I am using timer1 on DSPIC30f4011 to generate an interrupt every one millisecond. However, the timer1 ISR is not executed every time on POR (2 out of 10 times). If I turn on the power for the chip and use MCLR (switch it to high or low) the timer will work everytime on a MCLR reset. Is there anything that I need to clear in the software? I already reset the timer1 flag.
unsigned char t2=0;
unsigned char  t1=0;
unsigned char t0=0;
void main() {
  ADPCFG=0xff;
  //timer1 setting##########
  T1IF_bit= 0;                     //clear flag
  IEC0.T1IE         = 1;           //enable timer1 interrupt
  IPC0=0b0100000000000000;         //priority
  PR1                 = 7373;      //load
  //###########

  UART2_Init(115200);             //output something to computer

  ////////
  T1CON.TON=1;  ///start timer1
  ////////
  while(1){

    UART_Write(t2);
    UART_Write(t1);
    UART_Write(t0);
  }
}
void Timer1Interrupt() iv IVT_ADDR_T1INTERRUPT{

  T1IF_bit= 0;  //clear the flag
  t0++;         //increment something
  if(t0==255){t1++;}
  if(t1==255){t2++;}
}

A: If it only sometimes starts, it is probably a hardware problem.  Check that the power supply rise time is within spec for the PIC.  If not, a external reset circuit may be required.  The power up timer and brown out detect (if there is one) may also help.
It doesn't seem that the firmware is all that relevant to this, but there are a number of issues with it.  Hard coded constant, like 7373, magically picked out of the air are a really bad idea.  Also, your 3-byte increment routine in the interrupt is broken.  It's funny how you have to stand on your head to increment 3 bytes in C when this would be simpler in assembler.  I haven't done a interrupt routine in C30, so I'm not sure about this, but I don't see any obvious way the compiler is supposed to know this is a interrupt routine and therefore end with a RETFIE instruction instead of RETURN.  Isn't there some pragma you have to mutter to the compiler for it to produce a valid interrupt routine?


text:
Q: Getting all user data using Microsoft Graph API Using PHP and the Microsoft Graph API I'm fetching a user by querying:
https://graph.windows.net/<tenant>/users/<userId>?api-version=2013-11-08
This works fine, but only returns the standard fields for the user object. According to the documentation I'm supposed to be able to use $select=* to get all the user data, like this:
https://graph.windows.net/<tenant>/users/<userId>?$select=*&api-version=2013-11-08
However this gives me the following error:
{"odata.error":{"code":"Request_BadRequest","message":{"lang":"en","value":"The ability to use the $select query option to define a projection in a data service query is disabled. To enable this functionality, set the DataServiceConfiguration. AcceptProjectionRequests property to true."}}}
How can I enable "AcceptProjectionRequests"? I find nothing about this in the documentation or in other SO-threads.

A: The APIs you are referencing above are Azure AD Graph which is different than the Microsoft Graph APIs. It might be worth your time to have a look at the Microsoft Graph APIs and consider transitioning away from Azure AD Graph. The general guidance from the Azure AD Graph team recommends using the Microsoft Graph instead of the Azure AD Graph. You can read more about the differences and the Azure AD guidance here.
Having said that, Azure AD Graph does not support $select (as stated in the blog posting I linked to above). Microsoft Graph does support $select for doing query projections (see Microsoft Graph or Azure AD).

Currently (as of 7/8/2016) Microsoft Graph supports most of the directory features that Azure AD Graph supports, but not all.  In some cases, Microsoft Graph supports functionality that is not in Azure AD Graph (such as ability to make $select projection queries).

Per OData spec, $select=* can either return all entity properties or a default set of properties (provided the default set contains all key properties). The Microsoft Graph implementation is the latter and it will return a set of key properties. In order to get all the necessary properties you need, you will need to explicitly request the entire list you want unless they happen to be within the default set.


text:
Q: Bigrams and .Join I got this function and I tried to edit it a little for my purpose
but instead of getting bigrams I get unigrams. what do I need to add or edit?
I am really new with python and nltk
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import WordPunctTokenizer
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
import re

 def get_bigrams(myString):
 tokenizer = WordPunctTokenizer()
 tokens = tokenizer.tokenize(myString)

 bigram_finder = BigramCollocationFinder.from_words(tokens)
 bigrams = bigram_finder.nbest(BigramAssocMeasures.chi_sq, 500)

for bigram_tuple in bigrams:
    x = "%s %s" % bigram_tuple
    tokens.append(x)

result = [x for x in tokens if x not in stopwords.words('english') and   len(x) > 3]
 return result

 filename = raw_input('Enter File Name :')
 word_list = re.split('\s+', file(filename).read().lower())

 f=open ('test2.csv', 'w')

for line in word_list:
       features = get_bigrams(line)
       print features
       f.write(str(line))
       f.write("\n")

the output of for an exmple "It has been a long time"
It
has
been
a
long
time

Yet I am looking for something like
It has
has been
been a
a long
long time

A: Nltk seems like overkill here. Why not just do:
def pairs(seq):
    return zip(seq, seq[1:])

s = "It has been a long time"
words = s.split()
for bigram in pairs(words):
    print bigram

Result:
('It', 'has')
('has', 'been')
('been', 'a')
('a', 'long')
('long', 'time')

A: I think your problem is how you tackle the file reading and the line processing:
The following line gives you a list of words (as the name suggests)
word_list = re.split('\s+', file(filename).read().lower())

but later you treat each single word as a line:
for line in word_list:

This just means that your code can simply not work.
If I understand you correctly you might want to change file reading in the following way:
filename = raw_input('Enter File Name :')
lines = file(filename).readlines()

f = open('test2.csv', 'w')

for line in lines:
    features = get_bigrams(line)
    # do more things

A: Your function get_bigrams seems to work for me so I think the problem is your file or the way you read it.
By the way, Id like to suggest a shorter code for get_bigrams:
import nltk

def get_bigrams(sentence):
    tokens = nltk.word_tokenize(sentence)
    return zip(tokens, tokens[1:])

Use:
>>> [' '.join(b) for b in get_bigrams("It has been a long time")]
['It has', 'has been', 'been a', 'a long', 'long time']


text:
Q: TeamCity Azure Resource Manager Template: Missing MSBuild I'm using the Azure Resource Manager Template to generate an Azure TeamCity server with an agent on the same Linux CoreOS Azure VM. All the tools are there for building .NET Core projects, but for Xamarin projects, I need the Visual Studio Build Tools enabled on the box.
Following the instructions on http://www.mono-project.com/download/vs/#download-lin, I tried logging onto the agent by connecting to the VM via SSH, and then running:
docker exec -it [container id] bash
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
apt install apt-transport-https
echo "deb https://download.mono-project.com/repo/ubuntu vs-xenial main" | tee /etc/apt/sources.list.d/mono-official-vs.list
apt update
apt install mono-devel #Also apt-install mono-complete

However, even after rebooting the TeamCity VM, there is still an unmet requirement, listed as "Mono4.5_x86 exists".
Installing Mono on the agent works; however, every time I restart the agent, the installation is removed.
How can I install Mono on the build agent so that it persists when I restart the agent?

A: This took ages to fix, but I managed to find the solution eventually.
By default, the Azure Resource Manager for TeamCity does not contain Mono in its Docker image. You can install Mono on the Docker image, but then as soon as you restart the agent, the changes are not persisted.
You have to customise it following the instructions in https://hub.docker.com/r/jetbrains/teamcity-agent/.
Start off by creating a new image:
docker run -it -e SERVER_URL="http://<my-teamcity-server>.westeurope.cloudapp.azure.com" -v /mnt/data/teamcity-mono-agent:/data/teamcity_agent/conf --name="teamcity-mono-agent" jetbrains/teamcity-agent

Then start the agent using
docker start teamcity-mono-agent

Start a bash session in the agent with
docker exec -it teamcity-mono-agent bash

and in the bash terminal, install Mono using the sequence of instructions in the original question. (You may need to check the version of Linux that is running in the container, and modify these steps accordingly. There are detailed instructions on the Mono website.)
Once you have installed Mono, check the installation by typing mono, and then exit the bash session.
Commit the image using
docker commit teamcity-mono-agent mono-agent

And then restart the agent:
docker restart teamcity-mono-agent

In your TeamCity project, go to the build step and choose "MSBuild" from the dropdown. Choose "Mono xBuild 4.5" for the MSBuild version, "4.0" for the MSBuild Tools version, and x64 for the Platform.
Your new agent should now be able to pick up builds that require Mono.


text:
Q: Update Opportunity along with children using batch apex I am getting list of opportunities and 1 master opportunity, using batch apex I am updating list of oppys from master oppy, what is the best way to know that child objects- say opportunityLineItems and attachments -  are updated or not, if yes, the how can i update children?
For Example:
I have an Opportunity with 2 OpportunityLineItems, 5 Activities and 10 Attachments. I want to clone this opportunity 200 times along with OpportunityLineItems and Attachments only using batch apex.
As per my understanding I have to create Batch Apex, In execute method I have to clone and insert the Opportunities first, then I have to clone Attachments and OpportunityLineItems for each of the Opportunity. But while doing so if I set the batch size to 20, it will throw the error of Heap Space.
Is there any efficient way to achieve this?
Thanks in advance.

A: It is almost certainly the multiple attachments that you are cloning that are causing you to exceed the Heap Space limit. In a batch job you get the asynchronous limit, which is currently 12 MB.
You will need to start a secondary batch job to clone the attachments. Depending on the size of the attachments you may be best setting the batch size to 1, maybe 2.
During the batch you can check the current heap size using Limits.getHeapSize() and  Limits.getLimitHeapSize(). If the current heap size plus the size of the attachment you want to load into memory exceeds the heap limit then you will get an exception. Worse still with cloning as you will probably end up with two copies of the attachment in the heap at any one time.


text:
Q: Are certain words forbidden as keys in a dict() statement? So I was getting carried away after finishing my function to convert user time strings to seconds when I decided to extend my conversion dictionary with the statement:
dict(ys=1e-24, zeptoseconds=1e-21, zs=1e-21, attoseconds=1e-18, as=1e-18)

This fails. I can assign bs=1e-18, but if I assign as=1e-18 it says SyntaxError: invalid syntax, so I tried escaping the a but no luck.
Are there forbidden words in dictionary keys?

A: as is a reserved word in python.
>>> as = 10
  File "<stdin>", line 1
    as = 10
     ^
SyntaxError: invalid syntax

However, it is possible to use it as a dict key like so:
d = {"as": 10}

If you're curious where as shows up in python:
import json.load as loadjson

with open("myinputfile.json", "r") as infile:
    data = loadjson(infile)

A: Dictionary keys are strings, there are no forbidden values.
But there are reserved words that can't be used as variables, so you can't use that syntax for creating the dictionary if any of the keys are reserved words. as is reserved for its use in the with statement.
Instead, use a dictionary literal.
d = {'ys': 1e-24, 'zeptoseconds': 1e-21, 'zs': 1e-21, 'attoseconds': 1e-18, 'as':1e-18}

A:
Are there forbidden words in dictionary keys?

No. You can use any string as a dictionary key.
>>> {"as": 1}
{'as': 1}

You just can't use syntax keywords in the function call syntax because that will confuse the parser, and this is not specific to calling dict. You can not use the following strings as keywords in any function call:
>>> import keyword
>>> for kw in keyword.kwlist:
...     print(kw)
...
False
None
True
__peg_parser__
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield


text:
Q: RSA Decryption error I am implementing RSA decryption. I have tried lot more things regarding RSA decryption and i have develop below code snipet.
public class AsymmetricEncryptionWithRSA {

  public void decryptdata1(){

    String PRIVATE_RSA_KEY_PKCS8 =
            "-----BEGIN PRIVATE KEY-----\n" +
            "<RSAKeyValue><Modulus>rotP8p9dJpRM/D7HHW9wsRWJEBVdZolRR0PuYGp/Mjae2gElTZSBQ44ifOvVquI95ECDa2ypIrEz1k/mKRtHPmsSMqmySWL9CVsEZAc/zNfYjIKb4BDaFiBaPEsboebIEuaN3NFt2bbl/RB45TCycYylgDjCdFFASRbHs0jX4cM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>\n" +
        "-----END PRIVATE KEY-----\n";
        String key = PRIVATE_RSA_KEY_PKCS8
            .replace("-----BEGIN PRIVATE KEY-----\n", "")
            .replace("\n-----END PRIVATE KEY-----\n", "");
        System.out.println("key : "+key);

        PKCS8EncodedKeySpec keySpec =
            new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(key));
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            String s = "kjZzSUPJBY4rM23P7t47W3RYPTqhEARCqOcgRfxxBSc3O2mxQZKE/HKDN9OzW5pc3K37rcd+Dc/d55uNJcJUWwmZL0vVgrQIBkQdSkrzcpXV9JD80Qgy8sCuHoqMU49U6I34I43+NUAFmQDkApHbMA8LGV6KLtoyIyUSpDiuW8Q=";
            byte[] ciphertextBytes = Base64.decode(s.getBytes());
            byte[] decryptedData = cipher.doFinal(ciphertextBytes);
            String decryptedString = new String(decryptedData);
            System.out.println("decrypted (plaintext) = " + decryptedString);
        }catch(Exception e){
            e.printStackTrace();

        }
  }

  public static void main(String[] args) {

    AsymmetricEncryptionWithRSA ae = new AsymmetricEncryptionWithRSA();
    ae.decryptdata1();

  }

}
But the above code ran into the following error:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=11, too big.
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
    at java.security.KeyFactory.generatePrivate(Unknown Source)
    at decrypttest.AsymmetricEncryptionWithRSA.decryptdata1(AsymmetricEncryptionWithRSA.java:189)
    at decrypttest.AsymmetricEncryptionWithRSA.main(AsymmetricEncryptionWithRSA.java:210)
Caused by: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=11, too big.
    at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
    at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(Unknown Source)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(Unknown Source)
    at sun.security.rsa.RSAKeyFactory.generatePrivate(Unknown Source)
    ... 4 more

A: Crypto is frequently misunderstood, and thus I've decided to post a negative answer here. It's not very exciting, but if somebody finds themselves in scenario similar to the OPs they should probably be told why it can't work as early as possible in the process.
There are two possibilities when presented with a problem like this.

*

*OP understands the problem correctly and they've been instructed to decrypt something with the public key.

or

*OP does not completely understand their task but have been given a public key and some data and they need to make some progress with it.

For #1, it's simple: You can't decrypt RSA-encrypted data using a public key. It turns out the OP has only an RSA public key here, provided in an XML format. There's no way to reformat, massage, or otherwise fix up the public key to make it into the private key needed to decrypt the message. If this were doable then RSA would be trivially weak.
Now for #2, we have to step back and think of what might be true. We often find question askers here on stack overflow referring to "encrypting with the private key" in a context that inevitably implies that they really have an instance of an RSA signature. Rather than encryption, for clarity this should be called signing. An RSA signature is generated using the private key, and then everyone can verify the signature using the public key.
Now to verify the signature you also need the data that was signed, though there are some uncommon RSA signature schemes that allow for "message recovery". Since we have no data in this question, we have to try to go through the steps of verifying an RSA signature until we can make no more progress.
So we convert the XML data into an RSA modulus and public exponent. They are:
modulus
n = 122569097529914546498069291857337865246611656055620489010618854241554260593577609267786261511762266943671570032800601669006596562960007716726461943599993657820822102674379936038822313418546881231271467615708966752462196756466881703206510681054434799028982952649926637620598591790584184591371562810823451075011

and public exponent
e = 65537

The next step is to convert the signature string s into an integer. Using base64 decoding and the treating the result byte as big-endian integer I get:
sig  = 102674047248928745858859342743181557926563805477311756100001889942342552706930945260621737497972422939132498975770606253415531107828422537100810225687174208681096157106683665614198008538708912251973616331643319025696474841958268570965587969021816350210845541576380037736081469197294740984924898949880343321540

And now I compute compute plain = sige mod n and get:
plain  = 18281761513910757613247127600811463135393884768551021193363621715044011507027712128790112174797966270576132751506458211850250035395641481824697193105741034925363331241318624392861667609810000005509535564907655043671685464003456777077702725291701153287408411076758261166861253557068704213449855094306290667395

and finally convert plain to bytes using big endian to get:
92 36 73 49 43 c9 05 8e 2b 33 6d cf ee de 3b 5b 74 58 3d 3a a1 10 04 42 a8 e7 20 45 fc 71 05 27 37 3b 69 b1 41 92 84 fc 72 83 37 d3 b3 5b 9a 5c dc ad fb ad c7 7e 0d cf dd e7 9b 8d 25 c2 54 5b 09 99 2f 4b d5 82 b4 08 06 44 1d 4a 4a f3 72 95 d5 f4 90 fc d1 08 32 f2 c0 ae 1e 8a 8c 53 8f 54 e8 8d f8 23 8d fe 35 40 05 99 00 e4 02 91 db 30 0f 0b 19 5e 8a 2e da 32 23 25 12 a4 38 ae 5b c4

And ... nothing. It looks random to me, I see no patterns at all, nothing that looks like any possible version of PKCS#1 padding including PSS, nothing that looks like a 'message recovery' format.
So I can't solve this, none of the obvious things to try yield anything. It may be that the OP has been given an RSA-encrypted message but only given a public key, or maybe this is one of those RSA capture-the-flag exercises for which there is some weakness that allows for factoring the modulus, or maybe the public key is wrong. Or maybe I've made a mistake.


text:
Q: Cannot find name 'classes'. TS2304? when trying to style with React + Typescript I'm currently trying to add my own styles to my website and I've encountered this issue when I try to add a custom className.

Cannot find name 'classes'. TS2304

Here is my code so far:
import React from 'react';
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import { withStyles } from '@material-ui/core/styles';

const useStyles = makeStyles({
  aboutSection: {
    color:"red",
  }
});

class About extends React.Component {
  render() {
    return (

        <Grid container className ={classes.aboutSection} spacing={4} justify='center'>
          <Grid item sm={12}>

A Little More About Me!

          </Grid>
          <Grid item xs={12}>
            More about Me
          </Grid>
        </Grid>

    );
  }
}

export default About;

A: classes is a normal javascript variable, where do you expect it to come from? In the code given it does not appear to exist.
I think what you meant to do was use the useStyles hook in your component. Probably like this:
const classes = useStyles();

The problem is, your component is a class, and hooks are not allowed in class components. You could convert it to a functional component, or use the withStyles HOC for injecting styles.
Here is how it would look as a functional component:
import React from 'react';
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  aboutSection: {
    color:"red",
  }
});
const About = (props) {
  const classes = useStyles();

  return (

      <Grid container className ={classes.aboutSection} spacing={4} justify='center'>
        <Grid item sm={12}>

A Little More About Me!

        </Grid>
        <Grid item xs={12}>
          More about Me
        </Grid>
      </Grid>

  );
}

export default About;

Here is how it would look with the withStyles HOC:
import React from 'react';
import Grid from "@material-ui/core/Grid";
import { withStyles } from '@material-ui/core/styles';

const styles = {
  aboutSection: {
    color:"red",
  }
};
class About extends React.Component {
  render() {
    const { classes } = props;

    return (

        <Grid container className ={classes.aboutSection} spacing={4} justify='center'>
          <Grid item sm={12}>

A Little More About Me!

          </Grid>
          <Grid item xs={12}>
            More about Me
          </Grid>
        </Grid>

    );
  }
}

export default withStyles(styles)(About);

A: You are missing
class About extends React.Component {
  const classes = useStyles();`
...

https://material-ui.com/styles/basics


text:
Q: Firebase Firestore nested collection in Cloud Functions I am trying to implement the nested query with Firestore in Cloud Functions but stumbled upon issues with reading values in a for loop. Are there ways to adjust the following code so I could do some operations after reading all records from a collection?
const firestore = admin.firestore();
        const today = new Date();

        const snap = await firestore
            .collection('places')
            .where('endDate', '<', today)
            .get()

        const userIds = [...new Set(snap.docs.map((doc: any) => doc.data().owner))];

        const updatePromises = snap.docs.map((d: any) => {
            return d.ref.update({
                isPaid: false,
                isActive: false
            })
        })

        await Promise.all(updatePromises);

        const userCol = firestore.collection('users');
        const userDocs = await Promise.all(userIds.map(uid => userCol.doc(uid).get()));
        const userData = userDocs.reduce((acc, doc) => ({
            ...acc,
            [doc.id]: doc.data()
        }), {})

        snap.docs.forEach((l: any) => {
            const ownerData = userData[l.owner];
            const { email, displayName } = ownerData;

            console.log(email, displayName);

            const message = {
                // Some values
            }

            return sendGrid.send(message);
        })

        return null;

{ owner: '<firebaseUid'>, address: 'Royal Cr. Road 234' }

{ email: 'asdfa@afsdf.com' }

<firebase_uid>: {
  displayName: '',
  email: '',
  phoneNumber: ''
}

A: The userIds.push(owner); will keep adding duplicate values in that array and if a single user is owner of multiple locations, you'll end up querying same data multiple times. If you are trying to read owner's data along with a location, then try refactoring the code as shown below:
const firestore = admin.firestore();
const today = new Date();

const snap = await firestore
  .collection('locations')
  .where('isActive', '==', true)
  .get()

const userIds = [...new Set(snap.docs.map(doc => doc.data().owner))];

const updatePromises = snap.docs.map((d) => {
  return d.ref.update({
    isPaid: false,
    isActive: false
  })
})

// update documents
await Promise.all(updatePromises);

const userCol = firestore.collection("users")
const userDocs = await Promise.all(userIds.map(uid => userCol.doc(uid).get()))
const userData = userDocs.reduce((acc, doc) => ({
  ...acc,
  [doc.id]: doc.data()
}), {})

// To get data of a location's owner
// console.log(userData[ownerId])

snap.docs.forEach((l) => {
  const ownerData = userData[l.owner]
  // run more logic for each user
})

return null;


text:
Q: IPython notebook installation error I am having trouble getting my ipython to work after a regular python upgrade.
If I type:
ipython notebook --pylab inline

I get the following error:
-bash: /usr/local/bin/ipython: No such file or directory

If I type:
which ipython

I get no response, just the command line prompt.
if I type:
which python

I get
/usr/bin/python

if I type:
ipython --version

I get the following error:
-bash: /usr/local/bin/ipython: No such file or directory

When I inspect my system I see that my Ipython is installed in:
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Ipython

What should I do to make my ipython function again?  I had to fix the links for pip and easy_install to get them to work after the python installation.  I just can't seem to get ipython working again.

A: pip install -U "ipython[notebook]"

You may need to prefix this with sudo for authorization purposes:
sudo pip install -U "ipython[notebook]"

Replace pip with pip3 to install for Python 3.
Further install documentation is here.

A: I can recommend using Canopy (or Anaconda) as a package manager. Canopy, which I use, has its own terminal. Since I started using Canopy to manage my iPython environment, things have just been easier. Pip install/upgrades work like a charm every time, and I dont have to worry about mixing up python installations ect.
See this post for more info.
PS. This should probably be a comment, but don't have enough rep yet to comment :-)

A: This should be updated to be
pip install jupyter

From
ImportError: No module named notebook.notebookapp


text:
Q: Не выводит сообщение в консоль Не читает Console.WriteLine(x);
using System;
namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            double a, x, y,b;
            Console.Write("a=");
            a = double.Parse(Console.ReadLine());
            Console.Write("b=");
            b= double.Parse( Console.ReadLine());

            for (x = a; x < b; x++);
            {
                if (x <= 3)
                {
                  y = Math.Log10(Math.Pow(x, 3));
                    Console.WriteLine("y=%if \t");
                    Console.WriteLine("x");
                }

                else if (3 < x && x < 4.5)
                {
                    y = 1 / Math.Abs(Math.Sin(x));
                    Console.WriteLine("y");
                    Console.WriteLine("x");
                }
                else if (x <= 4);
                {
                    y = 1 / Math.Cos(1 / x);
                    Console.WriteLine("y");
                    Console.WriteLine("x");
                }
            }
        }
    }
}

A: Вероятно, вы хотите, чтобы вместо Console.WriteLine("x") и аналогичные строк кода в консоль выводились значения переменных.
Всё что заключено в двойные кавычки* воспринимается как текст. Уберите кавычки и просто напишите Console.WriteLine(x), аналогично для других переменных.
*всё что заключено в двойные кавычки воспринимается как текст, за исключением случаев, когда речь идёт об интерполированных строках.


text:
Q: When calling a member function of a class, I get Error C3867 In my displayData member function of the car class, the error says I should create a pointer to the member, do I have to create pointers to the member? If I do how so? I completely forget pointers. Do i make the object a pointer then point to the displayData member function? I get no red squiggles just an error message saying "use '&' to create a pointer to the member. I tried but had no luck.
#include<iostream>
#include<string>

using namespace std;
class Car
{
private:
int xVal, yVal, zVal;

protected:

public:
Car() { int xVal = 0; int yVal = 0; int zVal = 0; }
Car(int x,int y,int z) { xVal = x; yVal = y; zVal = z; }
~Car() {};
int getX() { return xVal; }
int getY() { return yVal; }
int getZ() { return zVal; }
void changeX(int n) { xVal = n; }
void changeY(int n) { yVal = n; }
void changez(int n) { zVal = n; }
virtual void getData();
void displayData();

};

class Sensor : public Car
{
private:
string sensorType;

protected:

public:
Sensor() { sensorType = "EMPTY"; }
Sensor(int x, int y, int z, string type) :Car(x,y,z) { sensorType = type; }

};

void Car::displayData()
{
cout << "The x values is: " << getX() << endl;
cout << "The y values is: " << getY() << endl;
cout << "The z values is: " << getZ() << endl;
}

int main()
{
Sensor n1;
Sensor n2(20,30,40, "Accelerometer");
n1.displayData;
n2.displayData;

return 0;
}

A: There is a syntax error in calling the function.
it should be
n1.displayData();

instead of
n1.displayData;


text:
Q: Using a CNAME record to point to an Amazon ELB I have an elastic load balancer in an AWS VPC.
I can access the resources successfully behind the load balancer exposed on different ports - standard https 443 and a couple of higher ones say 8888.
So
https://aws-elb.xxxxxxxxxxxx.region.com:443
https://aws-elb.xxxxxxxxxxxx.region.com:8888
all work - I get the expected security warning but can ignore and access the service.
I then added a CNAME record for mysite.example.com to point at https://aws-elb.xxxxxxxxxxxx.region.com and got a cert for mysite.example.com.
Now I can access
https://mysite.example.com[:443]
successfully, but
https://mysite.example.com:8888
times out.
I was under the impression that the CNAME would just route through to the underlying url and all would work?

A: That's weird, DNS has nothing to do with the port you're connecting to (443, 8888).
Are you sure you're testing it from the same place? Does the ELB security group permit connection to 8888 from your location?
Or is it perhaps not timeout but instead some other error that you're facing on 8888?


text:
Q: Introducir un input en html para una verificación me gustaría introducir un input en mi formulario, para verificacion, el caso es que no doy con el elemento html para darle este estilo, me refiero concretamente, a un input que dentro del mismo tenga subdivisiones entre dígitos

A: ¿Has probado con el tag select?, échale un vistazo https://www.w3schools.com/tags/tag_select.asp

<label for="digit">Elige el dígito:</label>

<select name="cars" id="cars">
<option value="digit1">1</option>
<option value="digit2">2</option>
<option value="digit3">3</option>
<option value="digit4">4</option>
</select>


text:
Q: When will postUserFunc executed I create a typoscript file. In this file i include my own PHP file like:
includeLibs.sendNews = fileadmin/send_news.php

In my PHP file i have a function execute. Now i call the function execute with typoscript postUserFunc, but my function never executed.
page.stdWrap.postUserFunc = execute

I don't find in the documentation when was the postUserFunc executed. Can someone help me and give me a hint when was the postUserFunc executed?

A: In TYPO3 6.2, the execution order of stdWrap-properties can be found in the source code of the content object renderer, line 62ff.
The gist of the order is below, I have removed some things that occur double due to technicalities. As you can see, the postUserFunc is executed as almost the last thing.
    stdWrapPreProcess
    cacheRead
    setContentToCurrent
    addPageCacheTags
    setCurrent
    lang.
    data
    field
    current
    cObject
    numRows
    filelist
    preUserFunc
    stdWrapOverride
    override
    preIfEmptyListNum
    ifNull
    ifEmpty
    ifBlank
    listNum
    trim
    strPad
    stdWrap
    stdWrapProcess
    required
    if.
    fieldRequired
    csConv
    parseFunc
    HTMLparser
    split.
    replacement.
    prioriCalc
    char
    intval
    hash
    round
    numberFormat.
    expandList
    date
    strftime
    age
    case
    bytes
    substring
    removeBadHTML
    cropHTML
    stripHtml
    crop
    rawUrlEncode
    htmlSpecialChars
    encodeForJavaScriptValue
    doubleBrTag
    br
    brTag
    encapsLines.
    keywords
    innerWrap
    innerWrap2
    fontTag
    addParams.
    textStyle.
    tableStyle.
    filelink.
    preCObject
    postCObject
    wrapAlign
    typolink.
    TCAselectItem.
    space
    spaceBefore
    spaceAfter
    wrap
    noTrimWrap
    wrap2
    dataWrap
    prepend
    append
    wrap3
    orderedStdWrap
    outerWrap
    insertData
    offsetWrap
    postUserFunc
    postUserFuncInt
    prefixComment
    editIcons
    editPanel
    cacheStore
    stdWrapPostProcess
    debug
    debugFunc
    debugData


text:
Q: Sql Query to get column name from another table In the below code i have a
document table
document name   |  document id  |  client id

and attachment table
attach id   |   document id   |   attachment name.

I want to get attachemt name from attachment table.in the below code i get document id,document name ,clientid from document name and i want to get attachment name from attachment table.how to do in this same query.
@i_DocumentID varchar(MAX)

SELECT
    DocumentID,
    DocumentName,
    ClientID
FROM Documents
WHERE DocumentID IN (SELECT * FROM dbo.CSVToTable(@i_DocumentID))

A: @i_DocumentID varchar(MAX)

 SELECT
    a.DocumentID,
    a.DocumentName,
    a.ClientID,
    b.AttachmentName
    from Documents  a
    join Attachments b on a.DocumentId = b.DocumentId

    where a.DocumentID IN (SELECT * FROM dbo.CSVToTable(@i_DocumentID))

You can read more about joins here: http://www.w3schools.com/sql/sql_join.asp or here http://www.mssqltips.com/sqlservertip/1667/sql-server-join-example/

A: Use a join:
@i_DocumentID varchar(MAX)
SELECT D.DocumentID, D.DocumentName,D.ClientID, A.Attachement_name
from Documents D JOIN
     Attachment A on D.document_id=A.document_id
where D.DocumentID IN (SELECT * FROM dbo.CSVToTable(@i_DocumentID))

A: You need a JOIN.
@i_DocumentID varchar(MAX)

SELECT d.DocumentID, DocumentName,ClientID,AttachmentName
from Documents d
INNER JOIN attachment a
ON a.document_id=d.document_id
where DocumentID IN (SELECT * FROM dbo.CSVToTable(@i_DocumentID))


text:
Q: Why does mean() have different behavior on empty DataFrames? If I have an empty DataFrame in pandas like this:
df = pandas.DataFrame(columns=['a','b','c'])
>>> df
Empty DataFrame
Columns: [a, b, c]
Index: []

and I aggregate on groups, the output will usually be an empty DataFrame:
>>> df.groupby('a', as_index=False).sum()
Empty DataFrame
Columns: [a, b, c]
Index: []

I say usually because this is not always the case. It works this way for min(), max(), sum(), count(), and quantile() but not for mean(), that one raises an exception:
>>> df.groupby('a', as_index=False).mean()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/pandas/core/groupby.py", line 666, in mean
    return self._cython_agg_general('mean')
  File "/usr/local/lib/python2.7/site-packages/pandas/core/groupby.py", line 2358, in _cython_agg_general
    new_items, new_blocks = self._cython_agg_blocks(how, numeric_only=numeric_only)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/groupby.py", line 2408, in _cython_agg_blocks
    raise DataError('No numeric types to aggregate')
pandas.core.groupby.DataError: No numeric types to aggregate

Why is the behavior different for this one aggregate function?
I am using pandas 0.14.1 on python 2.7.

A: This exception is raised for the genuine groupby functions: http://pandas.pydata.org/pandas-docs/stable/api.html#id35,  when you are calling sum, this is calling the Series or df version which has no such restriction.
So in fact mean, median, sem, std, var and ohlc will all raise an exception.
Note also that if you had non-numerical data, the exception would be raised.
Compare what happens when you call apply with mean:
In [18]:

df.groupby('a', as_index=False).apply(mean)
Out[18]:
Empty DataFrame
Columns: []
Index: []

here no exception is raised as the Series or Df version is being applied.

A: I'm not exactly sure but I would hypothesize it's because mean() would divide by the number of elements in the dataframe, in this case 0.  Which would cause a divide by zero error.  I would just catch the error that is thrown


text:
Q: Induction Proof - Primes and Euclid's Lemma I'm having some trouble with this proof. Here's the question: Use mathematical induction and Euclid's Lemma to prove that for all positive integers $s$, if $p$ and $q_1, q_2, \dotsc, q_s$ are prime numbers and $p$ divides $q_1q_2\dotsb q_s$, then $p=q_i$ for some $i$ with $1 ≤ i ≤ s$.
Here's what I know: Euclid's Lemma says that if $p$ is a prime and $p$ divides $ab$, then $p$ divides $a$ or $p$ divides $b$. More generally, if a prime $p$ divides a product $a_1 a_2 \dotsb a_n$, then it must divide at least one of the factors $a_i$. For the inductive step, I can assume $p$ divides $q_1q_2\dotsb q_{s+1}$ and let $a=q_1q_2\dotsb q_s$. Then, $p$ divides $aq_{s+1}$ and either $p$ divides $a$, $p$ divides $q_{s+1}$, or $p=q_{s+1}$. I know that since $q_i$ is prime, it cannot divide $q_i$ unless $p=q_i$ for some $1 ≤ i ≤ s$. I'm just not sure how to formulate the proof. Usually with Induction I can set some property $P(n)$ and test it is true for some base like $P(0)$ or $P(1)$ for the base step. I'm unsure how to go about it here.

A: First, we note that $p|q_1$ implies $p=q$ (we don't even need Euclid's lemma to see this).
Now assume that $p|q_1q_2\ldots q_k\implies p|q_1$ or $p|q_2$ or $\cdots$ or $p|q_k$.
Now consider the statement $p|q_1q_2\ldots q_kq_{k+1}$. Using Euclid's lemma, $p$ must divide one of $q_1q_2\ldots q_k$ or $q_{k+1}$. By our inductive hypothesis, we conclude that $p|q_1$ or $p|q_2$ or $\cdots$ or $p|q_k$ or $p|q_{k+1}$.
I see that this is pretty much what you did, so which part specifically are you having difficulty writing?


text:
Q: Intermittent NATS Connection failures with timeouts on AWS We have a clojure application that users NATS and the NATS Java libraries to support clustering. This is all deployed on AWS EC2 instances.
Starting last night we are seeing intermittent connection timeouts between the application and the NATS instance. We didn't change any code and don't know of any network or AWS configuration changes. The errors started occurring in all environments at the same time.
Our connection code:
defn connect
  "Create a Nats connect and return a Connection object.
     @urls -> Nats server urls (\"nats://127.0.0.1:4222\"), either a seq or comma separated string
     returns <- a Nats Connection object"
  ([]
   (connect ["nats://127.0.0.1:4222"]))
  ([urls]
   (->> (.. (Options$Builder.)
            (errorListener (make-error-handler))
            (connectionListener (make-connection-handler))
            (servers (into-array String urls))
            (executor pool)
            build)
        (Nats/connect))))

We also modified the connection code above to update the timeout to be 10 seconds and still are seeing timeouts with an error like the one below.
NATS Error Exception: java.net.SocketTimeoutException: connect timed out

java.io.IOException: Unable to connect to NATS servers: nats://my.nats.uri:4222.
    at io.nats.client.impl.NatsConnection.connect(NatsConnection.java:235)
    at io.nats.client.impl.NatsImpl.createConnection(NatsImpl.java:29)
    at io.nats.client.Nats.createConnection(Nats.java:247)
    at io.nats.client.Nats.connect(Nats.java:164)
...

Without a code change what could cause NATS connections to start failing in that fashion?


text:
Q: Exponer ACF en endpoint peronalizado de Wordpress estoy creando un endpoint personalizado con Wordpress, pero por mas que intento no logro exponer los campos adicionales de ACF que agregue a mi CPT, si alguien me pudiera dar un poco mas de luces estaría muy agradecido. :D
add_action( 'rest_api_init', function () {
  register_rest_route( 'negocio', '/rubro(?:/(?P<rubro>\d+))?', array(
    'methods' => WP_REST_Server::READABLE,
    'callback' => 'negocios_data_rubro',
  ) );
} );

function negocios_data_rubro( $data ) {

    $args  = array(
        'relation' => 'AND',
        'post_type'  => 'negocio',
        'meta_query' => array(
            array(
                'key'     => 'rubro',
                'value'   => $data['rubro'],
                'compare' => 'LIKE'
            )
        ),
    );
    $query = new WP_Query( $args );

    return $query->posts;
}

A: El resultado de WP_Query no incluye los meta, hay que agregarlos, algo así:
    $args  = [
      'post_type'  => 'negocio',
      'posts_per_page' => -1,
      'post_status'    => [ 'publish', 'future' ],
      'meta_query' => [
        'relation' => 'AND',
        'negocio_by_rubro' => [
          'key' => 'rubro',
          'value'   => $data['rubro'],
          'compare' => 'LIKE'
        ],
        // ... otros meta
      ],
      'orderby' => [
        'menu_order' => 'ASC',
        'negocio_by_rubro' => 'ASC',
      ],
    ];

    $Q = new WP_Query($args);
    $P = $Q->posts;
    $los_posts = [];

    if ($P){
      foreach( $P as $key => $el_post ){
        // traemos los fields acf delpost
        $F = get_fields($el_post);
        $los_posts[$key] = $el_post->to_array(); // agregamos el post al array
        $los_posts[$key]['fields'] = $F; // agregamos los fields al post
      }
    }

    return $los_posts; // retornamos los posts con fields


text:
Q: Not able to change default font to Optima in android device using jquery mobile I am trying to change default font to "Optima" in android device using query mobile. When i tested , the font is not changing in Android device. But when i test in Crome or Safari, its working.
Can any one have idea how to change font in android device.(other than google fonts solution).
Thanks,
Ravi S Karri.

A: you need have the CSS to read the font from a local folder in your site, so you need to have the font files in your local folder and then define your font in your CSS:
@font-face {
  font-family:'Optima';
  font-style:normal;
  font-weight:700;
  src: local('Optima'), local('Optima'), url(../font/Optima.woff) format('woff');
}

and then use it as you used to use it before:
font-family:Optima;


text:
Q: Can one perform sync read/write operations on an async named pipe? My expectation is that is this the case, that after creating a NamedPipeServerStream with PipeOptions.Asynchronous (and the client side as well), that one can still perform synchronous Read/Write operations on the pipe.
However, I have found that when the server synchronously writes bytes which exceed the size of the out buffer, the client end blocks on the read, never to return, even though the server has written the appropriate amount of data to satisfy that read.
Update: I have not yet been able to make a simple repro case, but I have isolated what I think to be suspicious results from the PipeStream class.  I have the following code:
byte[] buffer = new byte[ 66754 ];
int n1 = pipeStream.Read( buffer, 0, 66754 ); // Read returns 65536
int n2 = pipeStream.Read( buffer, buffer.Length - 1218, 1218 ); // Read blocks

This code is executed under the circumstances where the other side of the pipe has written 66754 bytes of data and the read side has not yet read this data (note, that the in and out max buffersize of the pipe at both ends is 65536 and that 65536 + 1218 == 66754).
When this code executes, the first read returns with n1 == 65536, indicating that not all the data I expected was read, so I execute another read, asking for the remaining data.  This read blocks indefinitely, never to return.
However, before the second read, when I inspect the buffer, I see the expected data that was written, even after the 65535 position!
It seems like the first Read read all the data, but only returned the max buffer size, so the second read hangs because there is no more data to be read.  But, I do not know that because I was told, incorrectly, the amount of data read on the first Read.
Now, a slight modification to this code.  This new code runs in exactly the same conditions as the previous.
byte[] buffer = new byte[ 66754 ];
int n1 = pipeStream.Read( buffer, 0, 65536); // Read returns 65536
int n2 = pipeStream.Read( buffer, buffer.Length - 1218, 1218 ); // Read blocks

Note that now the first Read has asked to read only the max buffer size of 65536.  In this case, n1 == 65536, and when the second read takes place, it returns successfully with n2 == 1218.
Here, instead of the first read asking for all the data, it asks for the max buffersize.  These are expected correct results of the Reads.
This suggests that there is a bug in the PipeStream code, where it returns the incorrect value from Read.
I will continue to try to make a simple repro case for this.
Another Update:  Found this:
NamedPipe's ReadByte hangs
Seems relevant to my issues.


text:
Q: REST Route/Input Design I have one Restaurant to many Menu, one Menu to many Category, one Category to many Item. I'm stuck trying to find the best way to lay out the routes for these models. Here are the options I see:

*

*I can flatten the routes and simply require the id of the parent model.

*

*this makes the routes simple, but requires an extra input/parameter every time I want to do anything with the model.

*GET /menus?restaurant_id=X

*POST /menus?restaurant_id=X&name=foo&description=bar

*I can nest all the routes within their given parent models.

*

*this makes the routes long, but doesn't require any extra inputs/parameters

*this adds unnecessary information to certain lower-level models (don't need to know restaurant directly when accessing categories/items)

*GET /restaurant/:restaurant_id/menus

*POST /restaurant/:restaurant_id/menus?name=foo&description=bar

*GET /restaurant/:restaurant_id/menus/:menu_id/categories/:category_id/items
Is there a good standard for which to choose?

A: I would go with your very last example - I try to keep URL params to a minimum for readability and cache/proxy concerns.

A: I would design it as such:
menus

*

*POST /menus?restaurant_id=123&name=foo&description=bar

*GET /menus?id=890  // specific menu

*GET /menus?/restaurant_id=123  // many menus
Items

*

*POST /items?category_id=594&name=milkshake&description=vanilla
more generically

*

*POST /<model_of_interest>?<parent_of_model_of_interest>&<other>&<parameters>

*GET /<model_of_interest>?<model_of_interest_id>
As you can see this would work for your top most and bottom most model without any additional cruft. Then validate the request and enforce access with your models which should be easily abstracted given the "only one parent" scheme you are going for (i.e. by passing &category_id=345 to create item route, you can easily construct the rest of your object and know for certain that 345 can only ever belong to menu_id=123 which can only even belong to restaurant_id=...).
This has the benefits of :

*

*not providing information the parent models already have

*allowing specific selection of a singular object "downwards" (e.g. give me item where id=338)

*allowing universal selection downwards (e.g. give me all items where category_id=123)


text:
Q: Can I use a gitolite repository on a non-default port from windows? I'm trying to set up some git repositories on my linux server for sharing with some friends working on a Java project. I sniffed around a little and found gitolite was supposed to be a good administration layer, so after looking at their docs I decided to follow this tutorial:
http://sites.google.com/site/senawario/home/gitolite-tutorial
Everything went well until step 6. There, the syntax used for the repository path wasn't working because sshd on the server isn't listening on the default port and that syntax doesn't like non-default ports, so after some more research I quickly discovered git supports ssh://etc. The only issue would be that it requires the full repository path to be included in the URL.
When I reached step 7 and the admin repository failed to push, I discovered that gitolite doesn't like full paths. I was advised by the troubleshooting section to create a host alias like so:
http://sitaramc.github.com/gitolite/sshhostaliases.html
This would supposedly allow me to use hostalias:reponame as the path. Despite the annoyance of requiring every user to do this, we went with that method, only to find out that it's not working at all. Our users are running windows and msysgit.
To summarize:

*

*The server's sshd listens on a non-default port; this cannot be changed.

*gitolite seems to require relative paths. Relative paths are only available on the default port or using host aliases.

*Our users are running windows 7 (not changeable) and msysgit (changeable, if there's anything better out there?). Our setups don't seem to like host aliases.

Is there a solution for this or do we have to drop gitolite and find something else?

A: See if editing ~/.ssh/config (from msysgit) works for each user. Add something like the following to the ~/.ssh/config file:
Host gitserver
Port 9999

The file ~/.ssh/config is optional and is used by ssh if it exists. Also, the ~/.ssh directory must not be readable to others (chmod 700 ~/.ssh).
When accessing git repo serverd using gitolite you're actually using the ssh transport. To be sure that ssh (and indirectly, git) uses the file ~/.ssh/config you can try the following diagnosis:
$ ssh -v gitserver

The first few lines that start with the debug1: prefix will tell you if ssh is using the ~/.ssh/config file - it will show you the full path the the config file that it uses.