text:
Q: WF4 - Designer - Right Click - ArgumentException - "An item with the same key has already been added" I'm using Visual Studio 2012 Ultimate and getting an ArgumentException when I'm right clicking following a copy\cut and paste operation...
Is this a bug in the designer? What's the easiest way to identify what's wrong here?
Thx!

A: Good news there is now a hotfix for this...
http://support.microsoft.com/kb/2828841


text:
Q: MvvmCross + Xamarin.Android: how to setup MvxRecyclerView inside CardView inside ViewPager? My parent activity contains a ViewPager that hosts 3 fragments.
MainView:
<CoordinatorLayout>
    <AppBarLayout/>
    <ViewPager/>
</CoordinatorLayout>

In one fragment, I have a RecyclerView that displays CardViews as items
Child fragment:
<CoordinatorLayout>
    <MvxSwipeRefreshLayout>
        <MvxRecyclerView
           local:MvxItemTemplate="@layout/child_item">
    </MvxSwipeRefreshLayout>
</CoordinatorLayout>

Inside the child fragment I want each child (a CardView) to host its own RecyclerView that 1) displays its child horizontally and 2) scrollable. But the problem is, even though I have set the layoutManager and the orientation values in XML, it does not work. It displays things vertically and does not scroll.
Child_item
<CardView>
  <MvxRecyclerView
     local:layoutManager="android.support.v7.widget.LinearLayoutManager"
     android:orientation="horizontal"
     local:MvxItemTemplate="@layout/child_child"
     android:background="@color/Red"/>

</CardView>

Child item inside the Cardview child_child.xml:
<LinearLayout android:background="@color/Grey">
    <Button>
</LinearLayout>

Currently, the main ViewPager works fine; I can swipe to change fragments. The child fragment also supports vertical scrolling; I tried adding multiple cardviews so that it has to scroll, and I can do that just fine. Inside the cardview I added a Seekbar to see if child elements were receiving touch inputs, which also worked. Only the RecyclerView inside the card is not receiving any touch inputs, or responding to the orientation = horizontal request.
How it is currently: The "XXXXX" buttons are stacked vertically. Note that there are more than 2 "XXXX" buttons. THe cardview clipped it but ot does not scroll.

What is expected/what I'm trying to achieve: the buttons should be stacked horizontally and should be scrollable.

A: There is a bug in MvxRecyclerView in MvvmCross 4.4.0 that ignores XML atrributes and simply hardcodes a default LinearLayoutManager. Further developments at GitHub issue.
For the time being, for this use case, I hard-coded an MvxRecyclerView subclass to SetLayoutManager(new LinearLayoutManager(context) { Orientation = Horizontal }); and it works.
[Register("bug.droid.components.BugFixRecyclerView")]
public sealed class BugFixRecyclerView : MvxRecyclerView
{
    public BugFixRecyclerView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }

    public BugFixRecyclerView(Context context, IAttributeSet attrs) : this(context, attrs, 0, new MvxRecyclerAdapter())
    {
    }

    public BugFixRecyclerView(Context context, IAttributeSet attrs, int defStyle) : this(context, attrs, defStyle, new MvxRecyclerAdapter())
    {
    }

    public BugFixRecyclerView(Context context, IAttributeSet attrs, int defStyle, IMvxRecyclerAdapter adapter) : base(context, attrs, defStyle, adapter)
    {
        if (adapter == null)
            return;

        var layoutManager = new LinearLayoutManager(context) { Orientation = Horizontal };
        SetLayoutManager(layoutManager);

        var itemTemplateId = MvxAttributeHelpers.ReadListItemTemplateId(context, attrs);
        var itemTemplateSelector = MvxRecyclerViewAttributeExtensions.BuildItemTemplateSelector(context, attrs);

        adapter.ItemTemplateSelector = itemTemplateSelector;
        Adapter = adapter;

        if (itemTemplateSelector.GetType() == typeof(MvxDefaultTemplateSelector))
            ItemTemplateId = itemTemplateId;
    }
}

and in the CardView's RecyclerView, replace the default MvxRecyclerView to use this subclass.

redpajama_set_name: RedPajamaStackExchange


text:
Q: On the Tikz Math Library: Fibonacci sequence On page 704/1318 Tikz manual there is an example to create Fibonacci sequence. I try to repeat as below:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary {math}
\begin{document}
\begin{tikzpicture}

\tikzmath{
% Adapted from
http://www.cs.northwestern.edu/academics/courses/110/html/fib_rec.html
function fibonacci(\n) {
if \n == 0 then {
return 0;
} else {
return fibonacci2(\n, 0, 1);
};
};
function fibonacci2(\n, \p, \q) {
if \n == 1 then {
return \q;
} else {
return fibonacci2(\n-1, \q, \p+\q);
};
};
int \f, \i;
for \i in {0,1,...,20}{
\f = fibonacci(\i);
print {\f, };
};
}
\end{tikzpicture}
\end{document}

But got a blank page.
Do you know how to fix this please?

A: You're not making a diagram in this case, just printing text to the page, so you shouldn't have a tikzpicture environment. Normal text in a tikzpicture is not printed.
Note that there is no tikzpicture in that example in the manual either, but those examples where a diagram is drawn do have the tikzpicture.


text:
Q: Check if user completed email verification ReactJS Firebase I have the following code which helps sign up users. Currently trying to integrate email verification and execute the updateProfile callback once that is completed. I'm able to send email using the .sendEmailVerification() method but can't figure how to make the check and execute the other codes. Would appreciate any help on this!
export default function SignUp() {
  const history = useHistory();
  const { firebase } = useContext(FirebaseContext);

  const [firstName, setFirstName] = useState('');
  const [emailAddress, setEmailAddress] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  const isInvalid = firstName === '' || password === '' || emailAddress === '';

  const handleSignup = (event) => {
    event.preventDefault();

    return firebase
      .auth()
      .createUserWithEmailAndPassword(emailAddress, password)
      .then((result) =>
        result.user
          //.sendEmailVerification()
          .updateProfile({
            displayName: firstName,
            photoURL: Math.floor(Math.random() * 5) + 1,
          })
          .then(() => {
            history.push(ROUTES.BROWSE);
          })
      )
      .catch((error) => {
        setFirstName('');
        setEmailAddress('');
        setPassword('');
        setError(error.message);
      });
  };

A: No need to overthink it. When creating an account (createUserWithEmailAndPassword), create another key in the firebase object that flags the user with an unverified state
{
    email: '',
    password: '',
    verified: false
}

After the user clicks on the verification URL and it is a success, flag it as true.
{
    email: '',
    password: '',
    verified: true
}

A: there is already a property on the user to handle this.
https://firebase.google.com/docs/reference/js/firebase.User#emailverified


text:
Q: How to calculate moving / running / rolling arbitrary function (e.g. kurtosis & skewness) using NumPy / SciPy I am working on the time-series data. To get features from data I have to calculate moving mean, median, mode, slop, kurtosis, skewness etc. I am familiar with scipy.stat which provides an easy way to calculate these quantities for straight calculation. But for the moving/running part, I have explored the whole internet and got nothing.
Surprisingly moving mean, median and mode are very easy to calculate with numpy. Unfortunately, there is no built-in function for calculating kurtosis and skewness.
If someone can help, how to calculate moving kurtosis and skewness with scipy? Many thanks

A: Pandas offers a DataFrame.rolling() method which can be used, in combination with its Rolling.apply() method (i.e. df.rolling().apply()) to apply an arbitrary function to the specified rolling window.

If you are looking for NumPy-based solution, you could use FlyingCircus Numeric (disclaimer: I am the main author of it).
There, you could find the following:

*

*flyingcircus_numeric.running_apply(): can apply any function to a 1D array and supports weights, but it is slow;

*flyingcircus_numeric.moving_apply(): can apply any function supporting a axis: int parameter to a 1D array and supports weights, and it is fast (but memory-hungry);

*flyingcircus_numeric.rolling_apply_nd(): can apply any function supporting a axis: int|Sequence[int] parameter to any ND array and it is fast (and memory-efficient), but it does not support weights.

Based on your requirements, I would suggest to use rolling_apply_nd(), e.g.:
import numpy as np
import scipy as sp
import flyingcircus_numeric as fcn

import scipy.stats

NUM = 30
arr = np.arange(NUM)

window = 4
new_arr = fcn.rolling_apply_nd(arr, window, func=sp.stats.kurtosis)
print(new_arr)
# [-1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36
#  -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36 -1.36
#  -1.36 -1.36 -1.36]

Of course, feel free to inspect the source code, it is open source (GPL).

EDIT
Just to get a feeling of the kind of speed we are talking about, these are the benchmarks for the solutions implemented in FlyingCircus:

The general approach flyingcircus_numeric.running_apply() is a couple of orders of magnitude slower than either flyingcircus_numeric.rolling_apply_nd() or flyingcircus_numeric.moving_apply(), with the first being approx. one order of magnitude faster than the second.
This shows the speed price for generality or support for weighting.
The above plots were obtained using the scripts from here and the following code:
import scipy as sp
import flyingcircus_numeric as fcn
import scipy.stats

WINDOW = 4
FUNC = sp.stats.kurtosis

def my_rolling_apply_nd(arr, window=WINDOW, func=FUNC):
    return fcn.rolling_apply_nd(arr, window, func=FUNC)

def my_moving_apply(arr, window=WINDOW, func=FUNC):
    return fcn.moving_apply(arr, window, func)

def my_running_apply(arr, window=WINDOW, func=FUNC):
    return fcn.running_apply(arr, window, func)

def equal_output(a, b):
    return np.all(np.isclose(a, b))

input_sizes = (5, 10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000)
funcs = my_rolling_apply_nd, my_moving_apply, my_running_apply

runtimes, input_sizes, labels, results = benchmark(
    funcs, gen_input=np.random.random, equal_output=equal_output,
    input_sizes=input_sizes)

plot_benchmarks(runtimes, input_sizes, labels, units='s')
plot_benchmarks(runtimes, input_sizes, labels, units='ms', zoom_fastest=8)

(EDITED to reflect some refactoring of FlyingCircus)

A: After playing around, I have come up with a solution that is purely numpy and scipy based. Of course it is using scipy.stats kurtosis and skew.
import numpy as np
from scipy.stats import kurtosis, skew

# Window size
N = 4

# Some random data
m = np.array([2, 3, 10, 11, 0, 4, 8, 2, 5, 9])

# Running Kurtosis
def runningKurt(x, N):
    # Initilize placeholder array
    y = np.zeros((len(x) - (N - 1),))
    for i in range(len(x) - (N - 1)):

         y[i] = kurtosis(x[i:(i + N)])

    return y

# Running Kurtosis

def runningSkew(x, N):
    # Initilize placeholder array
    y = np.zeros((len(x) - (N - 1),))
    for i in range(len(x) - (N - 1)):

         y[i] = skew(x[i:(i + N)])

    return y

kurt = runningKurt(m, N)
print("kurtosis : ", kurt)
# kurtosis :  [-1.93940828 -1.77879935 -1.61464214 -1.40236694 -1.15428571 -1.07626667 -1.42666667]

skw = runningSkew(m, N)
print("skew : ", skw)
# skew :  [ 0.         -0.1354179  -0.26356495 -0.13814702  0.43465076  0.32331615 -0.36514837]


text:
Q: Getting an array from one to many relationship in Laravel using a custom key I'm learning Laravel right now and I'm stumped on how to get an array of records from one table that belong to a record on another table based on a key.
I have two tables:
titles
-------------------
id | title_name | created_at | updated_at

posts
-------------------
id | titles_id | content

I have the route /{title_name} being controlled by the read() method on my PagesController.php
public function read($title){

    $title_name = $title;
    $title_id = Title::find($title)->id;
    $posts = Title::find($title)->posts;

    return view('pages/read')->with([
        'title_name' => $title_name,
        'title_id' => $title_id,
        'posts' => $posts
    ]);
}

But this doesn't seem to output anything. I have my models setup like this:
Title.php
class Title extends Model
{
     // Table Name
     protected $table = "titles";
     // Primary Key
     protected $primaryKey = "title";
     // Timestamps
     public $timestamps = "true";
     // Custom primaryKey
     public $incrementing = false;
     //relationship
     public function posts(){
          return $this->hasMany('App\Post', 'titles_id')->orderBy('created_at', 'desc');
     }
}

Post.php
class Post extends Model
{
     // Table Name
     protected $table = "posts";
     // Primary Key
     protected $primaryKey = "id";
     // Timestamps
     public $timestamps = "true";
     //relationship
     public function titles(){
          return $this->belongsTo('App\Title');
     }
}

I think the problem is that when I do Title::find($title)->post, laravel is trying to find posts where the titles_id = title_name, because I set title_name as the primaryKey, but I need it to be looking for the id column in the Titles table, and not the name...

A: Alright I will give you an example where I explain everything you do wrong.
Tables:
titles
-------------------
id | title_name | created_at | updated_at

posts
-------------------
id | title_id | content

Not titles_id but title_id, eloquent likes this more.
Your controller:
public function read($titleName){
    // The first function argument is the name of the title,
    // not the title model.
    // Also don't use snake_case in laravel(Except helpers) but camelCase.
    // We are not going to use find, you might have set the name as
    // primary key, but the id column still exists.
    // firstOrFail() means get the first result, if there isn't, throw
    // a model not found exception(404).
    $title = Title::where('name', $titleName)->firstOrFail();

    return view('pages/read')->with([
        // You could just do 'title' => $title, and do the rest in the view.
        'title_name' => $title->name,
        'title_id' => $title->id,
        'posts' => $title->posts
    ]);
}

Title model:
class Title extends Model
{
     // $table not needed, laravel knows this(Yes pure magic).

     // No, we don't want name as primary key.

     // Timestamps is true by default, so we don't need it.

     public function posts(){
          return $this->hasMany(\App\Post::class)->orderBy('created_at', 'desc');
     }
}

Post model:
class Post extends Model
{
     // This function should be called title, not titles.
     public function title(){
          return $this->belongsTo(App\Title::class);
     }
}


text:
Q: OpenOPC - Python connection crashes after few hours I have simple python script for logging data from OPC to MySQL.
import OpenOPC
import MySQLdb
import json
import time, datetime, threading

opc = OpenOPC.open_client('localhost')
opc.connect('MyOPCServer.OPC')

while True:
    temp11 = "R1_33"
    value1 = opc.read(zmienna1)
    db = MySQLdb.connect("localhost","root","","test")
    cursor = db.cursor()
    sql = "INSERT INTO test1(name, value, time) VALUES('%s', '%d', '%s')" % \
    (temp11, value1[0], value1[2])
    try:
        cursor.execute(sql)
        db.commit()
    except:
        db.rollback()

    db.close()

    time.sleep(6)
opc.close()

After few hours of working script crashes with this error:
Traceback (most recent call last):
  File "pcs4.py", line 16, in <module>
    value1 = client.read(zmienna1, include_error=True)
  File "C:\Python27\lib\site-packages\pyro-3.16-py2.7.egg\Pyro\core.py", line 38
1, in __call__
    return self.__send(self.__name, args, kwargs)
  File "C:\Python27\lib\site-packages\pyro-3.16-py2.7.egg\Pyro\core.py", line 45
6, in _invokePYRO
    return self.adapter.remoteInvocation(name, Pyro.constants.RIF_VarargsAndKeyw
ords, vargs, kargs)
  File "C:\Python27\lib\site-packages\pyro-3.16-py2.7.egg\Pyro\protocol.py", lin
e 497, in remoteInvocation
    return self._remoteInvocation(method, flags, *args)
  File "C:\Python27\lib\site-packages\pyro-3.16-py2.7.egg\Pyro\protocol.py", lin
e 572, in _remoteInvocation
    answer.raiseEx()
  File "C:\Python27\lib\site-packages\pyro-3.16-py2.7.egg\Pyro\errors.py", line
72, in raiseEx
    raise self.excObj
OpenOPC.OPCError

After that, even Matrikon OPC explorer won`t get tags from server. I must restart OS then script works for few hours again. Any ideas for that?


text:
Q: Delete specific row from database I am trying to delete a specific row in database. Using the following query:
    Uri myUri = Uri.parse("content://com.idan.datastorageprovider/maps");
    this.getContentResolver().delete(myUri, "ROUTE_NAME="+routeName,null);

In my database I have 2 columns: ROUTE_NAME,ROUTE_PATH.
I want to delete a row by the column ROUTE_NAME, while I give it a value of which row in that column I want to delete.
I don't errors, but the row is still there..
What am I doing wrong?
Thanks.
Idan.

A: I've found the solution:
String where="ROUTE_NAME" + "=?";
this.getContentResolver().delete(myUri,where, new String[] {nameOfValInColumn});


text:
Q: AngularJS: ngIf and ngRepeat I am using ngRepeat and ngIf to filter/sort(?) some data.  I originally considered using ngSwitch instead of ngIf for this, but couldn't find a good example.  After fumbling around with the slightly more complex ngSwitch, I decided to give it a go with ngIf.  It only took about 5 minutes to figure out how to implement what I wanted with ngIf, so that's a big plus!  However, I am needing to use ngRepeat and ngIf twice to achieve my desired output.  I would like to get it down to one ngRepeat if possible, since I think that is the more expensive directive.
The main html is as follows:

City1

                {{place.name}}

City2

                {{place.name}}

The output looks like:
City1

Place1
Place3

City2

Place2

You can see that I am using a boolean property for each element of the places variable.  I can provide more code if needed.
Is there a way to get the desired output without using two ng-repeat directives?  Would ngSwitch be better than ngIf?
EDIT:
Controller code:
(function() {

    'use strict';

    angular
        .module('app')
        .controller('Controller2', Controller2);

    function Controller2() {

        this.places = places;
    }

    var places = [
        {
            name: 'Place1',
            city1: true,
        },
        {
            name: 'Place2',
            city1: false,
        },
        {
            name: 'Place3',
            city1: true,
        }
    ];
})();

A: You could use filters in your ng-repeats and get rid of the ng-ifs:

City1

        {{place.name}}

City2

        {{place.name}}


text:
Q: Parent mount becomes inaccessible after mounting child into subdir? Im installing arch.  Upon installation, after partitioning my drives, right when I go to chroot to begin the fun stuff, I get an error
mount:mount point mnt/etc/resolv.conf does not exist
chroot: failed to run command /bin/sh: no such file or directory.

What this error is caused by in my particular case is the /mnt/etc filesystem being not available even though it shows as mounted, and was just mounted.
/dev/sda2 /mnt
/dev/sda3 /mnt/home

I mount /dev/sda2 to /mnt which works and files are accessible. Then I mount /dev/sda3/ to /mnt/home, and BLAM, blows up the mount for /dev/sda2 /mnt.
It still shows up in # mount, but when changing directory to /, then back to /mnt, its empty realestate inside all subdirs (proc is existant but empty, etc existent but empty, etc..)
Access was lost just as soon as dev/sda3 is mounted to /mnt/home.
Whats the likely issue here, is it filesystem issues, partition problem maybe, or something lame simple maybe?
Edit: complete sequence of commands being
# mount /dev/sda2 /mnt
# mount /dev/sda3 /mnt/home
# arch-chroot /mnt
#error message shows, i can reboot, its rinse and repeat

if i try to mount it to a different dir (the 2nd mount), e.g. /mnt/homey it mounts fine, just the same, which im not sure if i made clear, it mounts fine, just then i lose contents of all dirs inside /mnt, e.g. etc/ becomes empty...

A: There was alot of random errors, if you notice, and the problem was fairly unforseen.  I was using an old install medium, therefore it was exibiting various bugs, from incompatibilites.  Wow, no wonder that was so hard to troubleshsoot.
i was using arch 2015.01.01
Solution:
Download and use a fresh copy of install medium.


text:
Q: How to scroll two textboxes at the same time The goal here is to scroll the richtextbox2 while scrolling richtextbox1 at the same time.
I tried ...
Dim currentLine As integer=0
Dim index As integer=0

Private sub richtextbox1_textChanged(s as sender,e as eventArgs)handles richtextbox1.textChanged
index=richtextbox1.selectionStart
currentLine=richtextbox.GetLineFromCharIndex(index)
End sub

 Private sub richtextbox1_vscroll()  handlesrichtextbox.vscroll
Dim i=currentLine+1
Richtextbox2.select(i,1)
Richtextbox2.scrollToCaret()
End sub


text:
Q: Python & lxml / xpath: Parsing XML I need to get the value from the FLVPath from this link : http://www.testpage.com/v2/videoConfigXmlCode.php?pg=video_29746_no_0_extsite
from lxml import html

sub_r = requests.get("http://www.testpage.co/v2/videoConfigXmlCode.php?pg=video_%s_no_0_extsite" % list[6])
sub_root = lxml.html.fromstring(sub_r.content)

for sub_data in sub_root.xpath('//PLAYER_SETTINGS[@Name="FLVPath"]/@Value'):
     print sub_data.text

But no data returned

A: You're using lxml.html to parse the document, which causes lxml to lowercase all element and attribute names (since that doesn't matter in html), which means you'll have to use:
sub_root.xpath('//player_settings[@name="FLVPath"]/@value')

Or as you're parsing a xml file anyway, you could use lxml.etree.

A: You could try
print sub_data.attrib['Value']

A: url = "http://www.testpage.com/v2/videoConfigXmlCode.php?pg=video_29746_no_0_extsite"
response = requests.get(url)

# Use `lxml.etree` rathern than `lxml.html`,
# and unicode `response.text` instead of `response.content`
doc = lxml.etree.fromstring(response.text)

for path in doc.xpath('//PLAYER_SETTINGS[@Name="FLVPath"]/@Value'):
     print path


text:
Q: Run a Task, do something and then wait? I am familiar with the basic of Tasks, asyn/await etc but I haven't done much advance stuff and I a little stuck on an issue. I have a method which does communication to a camera system. The camera code runs on its own thread using a Task.
    public Task<bool> DoCameraWork()
    {
       bool Result = true;

       return Task.Run<bool>(() =>
         {
             for (int i = 0; i < 10; i++)
             {
                 // Do something which will set Result to True or False

                 if (Result)
                     break;
                 else
                     Task.Delay(1000);
             }

            return Result;
         });
    }

What I want to be able to do is start the task (DoCameraWork), update UI, call another method and then wait for the task to finish before continuing.
Whats the best way to achive this? Here is a mock up method which I hope explains a bit more. Yes code is poor but its just to explain what I want to achieve.
// Running on UI Thread
public async void SomeMethod()
{
   DoCameraWork();  // If I do await DoCameraWork() then rest of code won't process untill this has completed

   TextBox.Text = "Waiting For camera work";
   SendData(); // Calls a method to send data to device on RS232, notthing special in this method

   // Now I want to wait for the DoCameraWork Task to finish

   // Once camera work done, check result, update UI and continue with other stuff

   // if result is true
   // TextBox.Text = "Camera work finished OK";
   // else if result is false
   // TextBox.Text = "Camera work finished OK";
   // Camera work finished, now do some more stuff
}

A: Sounds like you just want to await later in the method:
public async void SomeMethod()
{
   var cameraTask = DoCameraWork();

   TextBox.Text = "Waiting For camera work";
   SendData();

   var result = await cameraTask;
   TextBox.Text = result ? "Camera work finished OK"
                         : "Eek, something is broken";
   ...
}


text:
Q: Sentry.NLog not logging to Sentry Trying to get Sentry wired up via NLog, and not having much luck.
Packages:
<package id="Sentry" version="3.0.5" targetFramework="net462" />
<package id="Sentry.NLog" version="3.0.5" targetFramework="net462" />

Both latest.
NLog.config:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="true"
      internalLogLevel="Debug"
      internalLogFile="c:\temp\nlog-internal.txt"
      internalLogToConsole="true"
      throwConfigExceptions="true">

  <extensions>
    <add assembly="Sentry.NLog" />
  </extensions>

  <targets>
    <target xsi:type="Sentry"
            name="sentry"
            dsn="https://secret"
            environment="test"
            includeEventProperties="True"
            layout="${message}"
            breadcrumbLayout="${message}"
            minimumBreadcrumbLevel="Debug"
            ignoreEventsWithNoException="False"
            includeEventDataOnBreadcrumbs="False"
            includeEventPropertiesAsTags="True"
            minimumEventLevel="Error" />
  </targets>

  <rules>
    <logger name="*" minlevel="Error" writeTo="sentry" />
  </rules>

</nlog>

Things I've checked:

*

*DSN. Copied and pasted from the Sentry portal, so i know it's correct

*No filters on 'environments' in Sentry.

*Nlog log file shows no errors. In fact in shows Sentry being wired up.

*Added other targets to NLog (e.g console, file, etc), they work fine.

Any ideas?
Thanks

A: Did you opt out of InitializeSdk?
https://github.com/getsentry/sentry-dotnet/blob/6ce7f933f64bd517677b5e837d6c7e8cc37b4217/src/Sentry.NLog/SentryTarget.cs#L148-L155
Could that be the issue?
Unless you're using another integration which already initialized Sentry, of if you call SentrySdk.Init yourself though.
But by default the DSN alone should be enough to init the SDK.
You can set the SDK to debug mode to see what's happening.
There's a sample project in the repo:
https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.NLog

A: Sentry is sending data over the network, and propbably has an artificial delay to optimize for batching and to reduce network-traffic.
Did you remember to flush?, and wait for the data to arrive at destination.


text:
Q: Test if ProtoBuf value is using default I have a ProtoBuf object. I'd like to detect when a particular field is using the default, versus explicitly supplied.
message vector_measurement
{
    measurement x = 1;
    measurement y = 2;
    measurement z = 3;
}
...
message measurement
{
    ...
    float value = 2;
    ...
}

When I use HasField it returns True, yet this is clearly not the case:
c = my_vector

print(c)
# x {
#   value: 60.3813476562
# }
# y {
#   value: 0.444311201572
# }
# z {
# }

print(c.x)
# value: 60.3813476562

print(c.z)
#

print(c.z==None)
# False

print(c.z.value)
# 0

print( c.HasField('x'), c.HasField('z') )
# (True, True )

print (c.z.HasField('value') )
# ValueError: Protocol message has no non-repeated submessage field "value"

The string representation seems to know that z is using a default value; how can I detect this myself?

A: You can check if a message is the default by calling ByteSize() on the message:
print(c.x.ByteSize())
# 5

print(c.z.ByteSize())
# 0

However, note that this is true for every default value, not just those not sent with the message. In other words, if each component value is explicitly set to exactly match the default, it will then report ByteSize()==0:
print(c.x, c.x.ByteSize())
#myBool: true
#stdDev: 1.06
#value: 14.32
# 12

c.x.myBool = False
print(c.x, c.x.ByteSize())
#stdDev: 1.06
#value: 14.32
# 10

c.x.value = 0
print(c.x, c.x.ByteSize())
#stdDev: 1.06
# 5

c.x.stdDev = 0
print(c.x, c.x.ByteSize())
# 0

There is no difference in ProtoBuf3 between an empty message and a message that has default values.


text:
Q: How to improve the speed of this code? I'm trying to import all googlebooks-1gram files into a postgresql database. I wrote the following Java code for that:
public class ToPostgres {

    public static void main(String[] args) throws Exception {
        String filePath = "./";
        List<String> files = new ArrayList<String>();
        for (int i =0; i < 10; i++) {
            files.add(filePath+"googlebooks-eng-all-1gram-20090715-"+i+".csv");
        }
        Connection c = null;
        try {
            c = DriverManager.getConnection("jdbc:postgresql://localhost/googlebooks",
                    "postgres", "xxxxxx");
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (c != null) {
            try {
                PreparedStatement wordInsert = c.prepareStatement(
                    "INSERT INTO words (word) VALUES (?)", Statement.RETURN_GENERATED_KEYS
                );
                PreparedStatement countInsert = c.prepareStatement(
                    "INSERT INTO wordcounts (word_id, \"year\", total_count, total_pages, total_books) " +
                    "VALUES (?,?,?,?,?)"
                );
                String lastWord = "";
                Long lastId = -1L;
                for (String filename: files) {
                    BufferedReader input =  new BufferedReader(new FileReader(new File(filename)));
                    String line = "";
                    while ((line = input.readLine()) != null) {
                        String[] data = line.split("\t");
                        Long id = -1L;
                        if (lastWord.equals(data[0])) {
                            id = lastId;
                        } else {
                            wordInsert.setString(1, data[0]);
                            wordInsert.executeUpdate();
                            ResultSet resultSet = wordInsert.getGeneratedKeys();
                            if (resultSet != null && resultSet.next())
                            {
                                id = resultSet.getLong(1);
                            }
                        }
                        countInsert.setLong(1, id);
                        countInsert.setInt(2, Integer.parseInt(data[1]));
                        countInsert.setInt(3, Integer.parseInt(data[2]));
                        countInsert.setInt(4, Integer.parseInt(data[3]));
                        countInsert.setInt(5, Integer.parseInt(data[4]));
                        countInsert.executeUpdate();
                        lastWord = data[0];
                        lastId = id;
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

However, when running this for ~3 hours it only placed 1.000.000 entries in the wordcounts table. When I check the amount of lines in the entire 1gram dataset it's 500.000.000 lines. So to import everything would take about 62.5 days, I can accept that it imports in about a week, but 2 months? I think I'm doing something seriously wrong here(I do have a server that runs 24/7, so I can actually run it for this long, but faster would be nice XD)
EDIT: This code is how I solved it:
public class ToPostgres {

    public static void main(String[] args) throws Exception {
        String filePath = "./";
        List<String> files = new ArrayList<String>();
        for (int i =0; i < 10; i++) {
            files.add(filePath+"googlebooks-eng-all-1gram-20090715-"+i+".csv");
        }
        Connection c = null;
        try {
            c = DriverManager.getConnection("jdbc:postgresql://localhost/googlebooks",
                    "postgres", "xxxxxx");
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (c != null) {
            c.setAutoCommit(false);
            try {
                PreparedStatement wordInsert = c.prepareStatement(
                    "INSERT INTO words (id, word) VALUES (?,?)"
                );
                PreparedStatement countInsert = c.prepareStatement(
                    "INSERT INTO wordcounts (word_id, \"year\", total_count, total_pages, total_books) " +
                    "VALUES (?,?,?,?,?)"
                );
                String lastWord = "";
                Long id = 0L;
                for (String filename: files) {
                    BufferedReader input =  new BufferedReader(new FileReader(new File(filename)));
                    String line = "";
                    int i = 0;
                    while ((line = input.readLine()) != null) {
                        String[] data = line.split("\t");
                        if (!lastWord.equals(data[0])) {
                            id++;
                            wordInsert.setLong(1, id);
                            wordInsert.setString(2, data[0]);
                            wordInsert.executeUpdate();
                        }
                        countInsert.setLong(1, id);
                        countInsert.setInt(2, Integer.parseInt(data[1]));
                        countInsert.setInt(3, Integer.parseInt(data[2]));
                        countInsert.setInt(4, Integer.parseInt(data[3]));
                        countInsert.setInt(5, Integer.parseInt(data[4]));
                        countInsert.executeUpdate();
                        lastWord = data[0];
                        if (i % 10000 == 0) {
                            c.commit();
                        }
                        if (i % 100000 == 0) {
                            System.out.println(i+" mark file "+filename);
                        }
                        i++;
                    }
                    c.commit();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

I reached 1.5 million rows in about 15 minutes now. That's fast enough for me, thanks all!

A: JDBC connections have autocommit enabled by default, which carries a per-statement overhead. Try disabling it:
c.setAutoCommit(false)

then commit in batches, something along the lines of:
long ops = 0;

for(String filename : files) {
    // ...
    while ((line = input.readLine()) != null) {
        // insert some stuff...

        ops ++;

        if(ops % 1000 == 0) {
            c.commit();
        }
    }
}

c.commit();

A: If your table has indexes, it might be faster to delete them, insert the data, and recreate the indexes later.
Setting autocommit off, and doing a manual commit every 10 000 records or so (look into the documentation for a reasonable value - there is some limit) could speed up as well.
Generating the index/foreign key yourself, and keeping track of it should be faster than wordInsert.getGeneratedKeys(); but I'm not sure, whether it is possible from your content.
There is an approach called 'bulk insert'. I don't remember the details, but its a starting point for a search.

A: Write it to do threading, running 4 threads at the same time, or split it up in sections (read from config file) and distribute it to X machines and have them get the data togeather.

A: Use batch statements to execute multiple inserts at the same time, rather than one INSERT at a time.
In addition I would remove the part of your algorithm which updates the word count after each insert into the words table, instead just calculate all of the word counts once inserting the words is complete.

A: Another approach would be to do bulk inserts rather than single inserts. See this question Whats the fastest way to do a bulk insert into Postgres? for more information.

A: Create threads
String lastWord = "";
    Long lastId = -1L;
    PreparedStatement wordInsert;
    PreparedStatement countInsert ;
    public class ToPostgres {
        public void main(String[] args) throws Exception {
            String filePath = "./";
            List<String> files = new ArrayList<String>();
            for (int i =0; i < 10; i++) {
                files.add(filePath+"googlebooks-eng-all-1gram-20090715-"+i+".csv");
            }
            Connection c = null;
            try {
                c = DriverManager.getConnection("jdbc:postgresql://localhost/googlebooks",
                        "postgres", "xxxxxx");
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (c != null) {
                try {
                    wordInsert = c.prepareStatement(
                        "INSERT INTO words (word) VALUES (?)", Statement.RETURN_GENERATED_KEYS
                    );
                    countInsert = c.prepareStatement(
                        "INSERT INTO wordcounts (word_id, \"year\", total_count, total_pages, total_books) " +
                        "VALUES (?,?,?,?,?)"
                    );
                    for (String filename: files) {
                        new MyThread(filename). start();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    class MyThread extends Thread{
        String file;
        public MyThread(String file) {
            this.file = file;
        }
        @Override
        public void run() {
            try {
                super.run();
                BufferedReader input =  new BufferedReader(new FileReader(new File(file)));
                String line = "";
                while ((line = input.readLine()) != null) {
                    String[] data = line.split("\t");
                    Long id = -1L;
                    if (lastWord.equals(data[0])) {
                        id = lastId;
                    } else {
                        wordInsert.setString(1, data[0]);
                        wordInsert.executeUpdate();
                        ResultSet resultSet = wordInsert.getGeneratedKeys();
                        if (resultSet != null && resultSet.next())
                        {
                            id = resultSet.getLong(1);
                        }
                    }
                    countInsert.setLong(1, id);
                    countInsert.setInt(2, Integer.parseInt(data[1]));
                    countInsert.setInt(3, Integer.parseInt(data[2]));
                    countInsert.setInt(4, Integer.parseInt(data[3]));
                    countInsert.setInt(5, Integer.parseInt(data[4]));
                    countInsert.executeUpdate();
                    lastWord = data[0];
                    lastId = id;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


text:
Q: Which OAuth protocol version does WebAccountManager use? I'm trying to read a document about exposing OAuth permissions but it starts out by saying:

Before you get started, you sould [sic] have a firm understanding of which version(s) of the OAuth protocol your permission should work with.

...and gives the options as

*

*The MSA v1 OAuth 2.0 protocol

*The AAD v1 OAuth 2.0 protocol

*The converged v2.0 OAuth 2.0 protocol

However, the only criteria the documentation gives for figuring out which one you are using is based on the URL to which the client sends requests (e.g. https://login.microsoftonline.com/tenant/oauth2/authorize).
I don't know what URL our application uses for auth, and thus don't know what version it uses. Our UWP app uses the WebAuthenticationCoreManager class to handle authentication. We specify "https://login.microsoft.com" as the AccountProvider and "organizations" as the authority (to the WebAuthenticationCoreManager.FindAccountProviderAsync method). We don't obviously specify an endpoint or protocol version anywhere.
What version are we using?

A: You'll want to register an Azure AD v1.0 application in the Azure portal.
Here's an excellent code sample that integrates the Web Account Manager into a Windows Universal app.


text:
Q: Hamburger menu indication does not show up in toolbar I am working on what is really my first Android app and am having issues making the hamburger menu indicator/button display on the top left. Despite the lack of the icon, swiping left in the app will open the navigation drawer. What's missing?
The toolbar.xml file:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="?attr/colorPrimaryDark">

The MainActivity.class
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBarDrawerToggle;

public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;
    private ActionBarDrawerToggle drawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        nvDrawer = (NavigationView) findViewById(R.id.nvView);
        // Setup drawer view
        setupDrawerContent(nvDrawer);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerToggle = setupDrawerToggle();

        // Tie DrawerLayout events to the ActionBarToggle
        mDrawer.addDrawerListener(drawerToggle);

    }
    private ActionBarDrawerToggle setupDrawerToggle() {
        return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open,  R.string.drawer_close);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // `onPostCreate` called when activity start-up is complete after `onStart()`
    // NOTE! Make sure to override the method with only a single `Bundle` argument
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        return true;
                    }
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass;
        switch(menuItem.getItemId()) {
            case R.id.nav_first_fragment:
                fragmentClass = CompareFragment.class;
                break;
            case R.id.nav_second_fragment:
                fragmentClass = BuildFragment.class;
                break;
            case R.id.nav_third_fragment:
                fragmentClass = VideosFragment.class;
                break;
            default:
                fragmentClass = CompareFragment.class;
        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();

        // Highlight the selected item has been done by NavigationView
        menuItem.setChecked(true);
        // Set action bar title
        setTitle(menuItem.getTitle());
        // Close the navigation drawer
        mDrawer.closeDrawers();
    }
    public void onClick(View v) {
        Class fragmentClass;
        Fragment fragment = null;
        final int id = v.getId();
        switch (id) {

            default:
                fragmentClass = CompareFragment.class;
                break;
        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    }

}

The styles.xml:
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#3F51B5</item>
        <item name="colorPrimaryDark">#303F9F</item>
        <item name="colorAccent">#FF4081</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>

    </style>
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark" />

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

</resources>

For adding this toolbar, I have mostly been following an online tutorial, as I do not quite understand toolbars quite yet. Let me know if anything else is needed. I appreciate any help that can be provided!


text:
Q: Why won't my Scanner take input when the main method is called by another class? My program is supposed to be able to execute java code given a file. However when I try to test it with my test class including a scanner, the scanner doesn't take any input. Right now it only prints, "What is your name?".
What is wrong?
Here is the method for execution:
public void execute()
{
    String fileName = file.substring(0, file.indexOf('.'));
    String[] args = null;
    Class c;
    Object o;
    Method main;
    try
    {
        c = Class.forName(fileName);
        o = c.newInstance();
        main = c.getDeclaredMethod("main", String[].class);
        Thread t = new Thread(new Runnable()
        {
            public void run()
            {
                try
                {
                    main.invoke(o, (Object)args);
                }
                catch(Exception e){}
            }
        }
        );
        t.start();
    }
    catch(Exception e){e.printStackTrace(System.out);}
}

Here is the code for the test class:
import java.util.Scanner;
public class Test
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        System.out.println("What is your name?");
        String name = s.nextLine();
        System.out.println("Your name is " + name);
        System.out.println("testing");
    }
}


text:
Q: how can i render table inside table by their associated id in rails hey i want to render sub_task table inside task table by their associated id. currently i am able to render all sub_task inside different task.
projects_controller.rb
  def show
    @project = Project.includes(stages: :tasks).find(params[:id])
    @stages = @project.stages
    @sub_tasks = SubTask.all
  end

routes.rb
  resources :projects do
    resources :stages do
      resources :tasks do
        resources :sub_tasks
      end
    end
  end

A: def show
  @project = Project.includes({stages: {tasks: :sub_tasks}}).find(params[:id])
  @stages = @project.stages
  @sub_tasks = SubTask.all
end

This should do the job


text:
Q: Reset laptop battery data or interface battery chip? My battery consists of 5 parallel strings of 2 cells in series. One conductor broke and therefore the measured capacity of the battery decreased dramatically, so that the capacity meter went down a lot.
I have now repaired the battery and I get the battery time I got before it broke but the battery meter still thinks that my battery has the lower capacity resulting in that i can not know how much energy is left in the battery at a specific time. I can run the computer for several hours after the battery states 0% left.
The problem is the same in both Windows XP and Ubuntu 10.04. The computer is an Asus eee 1000H. I have tried to completely drain and recharge the battery and then fully charge it to reset the battery stats but it did not work.
Is there another way for me to reset the data in the battery supervising chip or write data to it. Or as a bad solution, ignore the battery data and just numerically integrate the power over time giving the full energy and then use that instead of the data that the battery provides.

A: How to reset a battery is a well kept secret, I have done several unfruitful searches, but I only found irrelevant information on programs that show the battery charge capacity and actual charge, or how to discharge the battery for a longer life, but never how to reset the chip in the battery.
My original battery cells show a good charge level, when tested with a multimeter, but, the chip ensures that the battery will never be usable again.
I found a guide (PDF) that teaches how the battery control system works in some apple models.
I am not a hardware expert, but it seems a good document for those with knowledge in electronics.


text:
Q: Python Pandas Dataframe - how to groupby year and summarize multiple columns in a table I have the following code that summarizes revenue by year and the number of new customers acquired
min_dates = df.groupby(['Customer ID'])['Date'].min()
df['First Purchase Date'] = df.apply(lambda row: min_dates.loc[row['Customer ID']], axis=1)
df['New Customer'] = df['Date'] <= df['First Purchase Date']

#summarize data by year and total revenue.
df['revenue'] = pd.to_numeric(df['revenue'])
df['Year'] = df['Date'].dt.year
number_new_customers = df.groupby(df['Year'])['New Customer'].sum()
number_existing_customers = df.groupby(df['Year'])['New Customer'].sum()
print(df['number new customers'])

I want the results to summarize revenue and number of customers in the same row but the data is currently being presented as two separate summaries.  Any ideas on how i can combine these?
OUTPUT
    >>> print(number_new_customers, total_revenue)
    Year
    2014    135
    2015    458
    2016    146
    2017    174
    2018    121
    2019    33
    Name: New Customer, dtype: float64 Year
    2014    342.74
    2015    651,227.71
    2016    3251.26
    2017    232396.94
    2018    230,087.80
    2019    2342.52
    Name: revenue, dtype: float64
    >>>

A: I mocked up some data real fast, the date is in epoch time.
Date,Customer ID,First Purchase Date,revenue
1339088342,4112,902531671,5.91
1539868917,3145,1256488196,9.65
1356452277,3513,1139574500,3.33
1202597342,1915,1334993455,3.90
1141307061,350,1519053454,8.43
1008402214,2096,980405444,6.83
1409224498,2606,1413988517,8.74
1372252082,3195,1127686807,3.27
1021345993,1141,1487182332,2.44
1597193200,2765,656097735,6.40

Use the below to convert to datetime columns
df['Date'] = pd.to_datetime(df['Date'], unit='s')
df['First Purchase Date'] = pd.to_datetime(df['First Purchase Date'], unit='s')

Using your code to setup your columns and the below group by you can get the output provided.
print(df.groupby(["Year"])["New Customer", "revenue"].sum())

Output:
        New Customer  revenue
Year
2000           4.0    13.56
2001           2.0    14.96
2002          11.0    54.23
2003           1.0     7.13
2004           6.0    31.55
2005           5.0    20.49
2006           7.0    41.29
2007           3.0    25.11
2008           6.0    23.51
2009           1.0     4.76

Hope this helps.


text:
Q: GUI not responding while fetching data My application often fetch data from a webpage using WebRequest, but it isn't possible to click buttons etc while it's fetching. I've understood that I have to use threads/a backgroundworker, but I can't get it to work properly; it doesn't make the GUI more respondable.
The code I want to apply some kind of threading on, so that it stops making my application unresponding:
public string SQLGet(string query)
{
    string post = "q=" + query;
    WebRequest request = WebRequest.Create("http://test.com");
    request.Timeout = 20000;
    request.Method = "POST";
    byte[] bytes = Encoding.UTF8.GetBytes(post);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = bytes.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();

    WebResponse response = request.GetResponse();
    requestStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(requestStream);
    string ret = reader.ReadToEnd();

    reader.Close();
    requestStream.Close();
    response.Close();

    return ret;
}

Edit: Thank you, lc, I had tried something pretty similar to that. But my problem with using the backgroundworker like that is; how do I get the queryResult back to the function which called (in my case SQLGet, and in your case) StartQuery?
In my example, the returned string is going to be used as a local variable in the void the string is called inside.
And there may be many queries at the same time, so I don't want to risk assigning it to a global variable.

A: Here's a simple example of how to use the BackgroundWorker as it applies to your code:
private void StartQuery(string query)
{
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    backgroundWorker1.RunWorkerAsync(query);
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = SQLGet((string)e.Argument);
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    queryResult = (string)e.Result;
}

You may also wish to allow cancellation, provide error details, or provide robust feedback as it fetches data. Take a look at the example on the MSDN page for more details.
The result of your query will show up in the BackgroundWorker.RunWorkerCompleted event as e.Result (I've stored it as an instance variable in this case). If you're going to run many of these at the same time, you'll need a way to differentiate which query is which. So you should pass more than just a string to the method. Take this example:
private int NextID = 0;

private struct QueryArguments
{
    public QueryArguments()
    {
    }

    public QueryArguments(int QueryID, string Query)
        : this()
    {
        this.QueryID = QueryID;
        this.Query = Query;
    }

    public int QueryID { get; set; }
    public string Query { get; set; }
    public string Result { get; set; }
}

private int StartQuery(string query)
{
    QueryArguments args = new QueryArguments(NextID++, query);

    BackgroundWorker backgroundWorker1 = new BackgroundWorker();
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    backgroundWorker1.RunWorkerAsync(args);

    return args.QueryID;
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    QueryArguments args = (QueryArguments)e.Argument;
    args.Result = SQLGet(args.Query);
    e.Result = args;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    QueryArguments args = (QueryArguments)e.Result;
    //args.Result contains the result

    //do something
}

A: BackgroundWorker is a good solution, with some built-in support for cancellation and progress.  You can also just use HttpWebRequest.BeginGetResponse, rather than GetResponse, to initiate an asynchronous web request operation.  This ends up being quite simple and you can set up a progress callback.
For an exact example of what you're trying to do, see:
Using HttpWebRequest for Asynchronous Downloads

A: Here is a quick solution, should be easy to take what you need from it.
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            BackgroundWorker b = new BackgroundWorker();
            b.DoWork += new DoWorkEventHandler(b_DoWork);
            b.RunWorkerCompleted += new RunWorkerCompletedEventHandler(b_RunWorkerCompleted);
            b.RunWorkerAsync("My Query");

            while(b.IsBusy)
            {

            }
            Console.ReadLine();
        }

        static void b_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if(e.Result is string)
            {
                Console.WriteLine((string)e.Result);
            }
        }

        static void b_DoWork(object sender, DoWorkEventArgs e)
        {
            if (e.Argument is string)
            {
                string post = "q=" + (string) e.Argument;
                WebRequest request = WebRequest.Create("http://test.com");
                request.Timeout = 20000;
                request.Method = "POST";
                byte[] bytes = Encoding.UTF8.GetBytes(post);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                WebResponse response = request.GetResponse();
                requestStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(requestStream);
                string ret = reader.ReadToEnd();
                reader.Close();
                requestStream.Close();
                response.Close();
                e.Result = ret;
            }
        }
    }
}


text:
Q: How to check if string contains specific hex value Im having trouble with a BASH script
I have a variable that gets populated with a string from at curl command, this string is often two words with a space. The space is not \x20 but \x0A in hex, which results in a carriage return which i would like to counter.
I have no control of the returned string as is gets the data from Google
Is there a simple way of checking if the string variable contains \x0A hex ?
And is it possible to manipulate the string, changing \x0A value to \x20
Thanks in advance ;)

A: You can use bash's built-in parameter expansion to convert all white space to plain spaces:
a=$' a\rb\nc'
$ echo "$a"
ba
c
$ a="${a//[[:space:]]/ }"

On other shells you can use tr to do the same, at the expense of calling external processes and creating subshells:
$ a=$(printf '%s' "$a" | tr '[:space:]' ' ')

In either case, the result is:
$ echo "$a"
 a b c

A:
Is there a simple way of checking if the string variable contains \x0A hex ? And is it possible to manipulate the string, changing \x0A value to \x20

Yes and yes.
As Tom suggests, you can manipulate the string using parameter expansion in bash or tr in any shell.
If you first want to check whether a string contains a special character, bash's built in test capabilities will do the job.
$ s=$'a\rb\r'; [[ $s == *$'\n'* ]] && echo "Yes"
$ s=$'a\rb\n'; [[ $s == *$'\n'* ]] && echo "Yes"
Yes


text:
Q: rails carrierwave generated url for STI I have 1 STI class inherits from User class
class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end

class Staff < User

end

but when I looping all the staffs user including the image url like this:
controller
@staffs = Staff.all

view

<% @staffs.each do |staff| %>

  <%= staff.name %>
  <%= image_tag staff.avatar_url(:small) %>

<% end %>

this code:
<%= image_tag staff.avatar_url(:small) %>

it will generate upload url like this:
/uploads/user/avatar/44/avatar1.jpg

instead of
/uploads/staff/avatar/44/avatar1.jpg

How to do this? thank you

A: mount the uploader also inside the Staff.
The Problem is, that the Uploader ins mounted on the User. Even if you STI the Staff, for CW its still a user.


text:
Q: Generating WordML Reports Using Templates and XPath using ASP.Net I need to know how we can Generate WordML Reports Using Templates and XPath using ASP.Net.
What are its advantages.
A Simple How To Tutorial is what I require.

A:
I need to know how we can Generate WordML Reports Using Templates and XPath using ASP.Net. ... A Simple How To Tutorial is what I require.

Create (using Word) a document in WordML format which you'll use as a template.
Look at your WordML template: see that it's in XML format. Have Microsoft's WordML reference documentation, so that you understand what it means and how to modify it.
Define XPath expressions which identify the locations in your template which you want to modify (where "modify" probably means "insert data at run time").
At runtime use an API like http://www.google.com/search?hl=en&q=c%23+xpath

What are its advantages.

Its advantages over what alternative?
The benefit is that the output is a Word document, whose content is based on a template plus modifications made at runtime.

A: I would recommend you to use Content Controls and Custom XML for the purpose of report generation. Here's a sample:
http://blogs.msdn.com/erikaehrli/archive/2006/08/11/word2007DataDocumentGenerationPart1.aspx
You might also want to have a look at Microsoft's OpenXML SDK v2.0


text:
Q: How do I get permissions to run WireShark in Kali Linux AWS? I have a Kali Linux instance in AWS. I login via SSH using a key-pair file with ec2-user. I've configured VNC server for GUI access and I can connect.
However, whenever I try to run Wireshark, I'm presented with a box "Authentication is required to run /usr/bin/wireshark" as root. I have 2 options
Debian (ec2-user)
Kali
Debian doesn't have a password associated as AWS uses a key-pair and I've set the Kali password, but that doesn't load WireShark.
What do I need to do?
Thanks

A: https://www.kali.org/docs/introduction/default-credentials/ is typically what you should consider. That being said, the ssh_key may not be established for a variety of reasons.
Assuming current ssh/vnc have enough privilege to do this, run
sudo passwd kali

If you do not, I would recommend setting the password for kali in the user data script when you fire up the server.


text:
Q: flask showing error when using emit function I am receiving data from a TCP server and I am passing it to client using websocket for which it is showing working outside of request context
The code is something like this
def recv(msg):
     data=msg
     emit('info',{'data': data})

and my html script code is
 <script type ='text/javascript'>
 var socket = io.connect('http://' + document.domaiin + ':' + location.port)

 socket.on('info', function(msg){
         console.log(msg);
    });

But there is no output on the console.


text:
Q: One additional duplicate file gets uploaded I have my FileUpload Controller like this:
@PostMapping("/uploadFile")
public AppUserDocumentUploadResponse uploadFile(@RequestParam("file") MultipartFile file) {
    AppUserDocument dbFile = appUserDocumentStorageService.storeFile(file);

    String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/downloadFile/")
            .path(dbFile.getId().toString())
            .toUriString();

    return new AppUserDocumentUploadResponse(dbFile.getDbfileName(), fileDownloadUri,
            file.getContentType(), file.getSize());
}

@PostMapping("/uploadMultipleFiles")
public List<AppUserDocumentUploadResponse> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
    return Arrays.asList(files)
            .stream()
            //.peek(fileBeingProcessed -> log.info("Processing File (PEEK2): {} ", fileBeingProcessed))
            .map(file -> uploadFile(file))
            .collect(Collectors.toList());
}

My Service is:
public AppUserDocument storeFile(MultipartFile file) {

    String fileName = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (fileName.contains("..")) {
            throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
        }
        AppUserDocument dbFile = new AppUserDocument(UUID.randomUUID().toString(), fileName, file.getContentType(),
                file.getSize(), file.getBytes());

        return dbFileRepository.save(dbFile);
    } catch (IOException ex) {
        throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
    }
}

Model goes like this:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "AppDBFiles")
@Table(name = "app_db_files")
public class AppUserDocument extends Auditable<String>  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "dbfileuuid", unique = true)
    @GenericGenerator(name = "uuid", strategy = "uuid4")
    private String dbfileuuid;

    @Column(name = "dbfilename")
    private String dbfileName;

    @Column(name = "dbfiletype")
    private String dbfileType;

    @Column(name = "dbfilesize")
    private long dbfileSize;

    @Lob
    @Column(name = "dbfiledata")
    private byte[] dbfileData;

    @Version
    @Column(name="optlock")
    private Integer version;

    public AppUserDocument(String dbfileName, String dbfileType, long dbfileSize, byte[] dbfileData) {
        super();
        this.dbfileName = dbfileName;
        this.dbfileType = dbfileType;
        this.dbfileSize = dbfileSize;
        this.dbfileData = dbfileData;
    }

    public AppUserDocument(String dbfileuuid, String dbfileName, String dbfileType, long dbfileSize, byte[] dbfileData) {
        super();
        this.dbfileName = dbfileName;
        this.dbfileType = dbfileType;
        this.dbfileSize = dbfileSize;
        this.dbfileData = dbfileData;
    }

}

And my (vanilla) JS goes like this:
function uploadMultipleFiles(files) {
    var formData = new FormData();
    for (var index = 0; index < files.length; index++) {
        formData.append("files", files[index]);
    }
    const fileField = document.querySelector('input[type="file"]');

    //formData.append('filecusomName', 'abc123');
    formData.append('files', fileField.files[0]);

    fetch('/uploadMultipleFiles', {
        method: 'POST',
        body: formData
    })
        .then((response) => response.json())
        .then((response) => {
            console.log('Success:', response);
            multipleFileUploadError.style.display = "none";
            var content = "
All Files Uploaded Successfully
";
            document.getElementById("multipleFileUploadInput").value = null;
            for (var i = 0; i < response.length; i++) {
                content += "
DownloadUrl : " + response[i].fileDownloadUri + "
";
            }
            multipleFileUploadSuccess.innerHTML = content;
            multipleFileUploadSuccess.style.display = "block";
        })
        .catch((error) => {
            multipleFileUploadSuccess.style.display = "none";
            multipleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
            console.error('Error:', error);
        });
}

All goes well except one additional file gets uploaded which is duplicate of the first file.
This is what my console logs show:
Success:
(3) [{…}, {…}, {…}]
0
:
fileDownloadUri
:
"http://localhost:8080/downloadFile/39"
fileName
:
"sample.pdf"
fileType
:
"application/pdf"
size
:
357896
[[Prototype]]
:
Object
1
:
fileDownloadUri
:
"http://localhost:8080/downloadFile/40"
fileName
:
"sample2.pdf"
fileType
:
"application/pdf"
size
:
357896
[[Prototype]]
:
Object
2
:
fileDownloadUri
:
"http://localhost:8080/downloadFile/41"
fileName
:
"sample.pdf"
fileType
:
"application/pdf"
size
:
357896
[[Prototype]]
:
Object
length
:
3

And my DB looks like this:

Uncommenting the .peek(fileBein in my controller also shows this (twice for the duplicate file):
2022-12-07T00:23:25.971-05:00  INFO 11344 --- [nio-8080-exec-2] c.c.s.c.AppUserDocumentRestController    : Processing File

What I am doing wrong here? Also not sure where to debug this situation. Any pointers/directions will be greatly appreciated.

A: Please once go through your JS file:
function uploadMultipleFiles(files) {
    var formData = new FormData();
    for (var index = 0; index < files.length; index++) {
        formData.append("files", files[index]);
    }
    const fileField = document.querySelector('input[type="file"]');

    //formData.append('filecusomName', 'abc123');
    formData.append('files', fileField.files[0]);

    fetch('/uploadMultipleFiles', {
        method: 'POST',
        body: formData
    })
...
...
}

The 9th line formData.append('files', fileField.files[0]); is adding duplicate of First file in FormData.


text:
Q: Passing data from a form to a table on another page (html) Good morning/afternoon,
I'm attempting to create a html website for people to participate in a psychological study. It is mostly created, however, I cannot move any form data to my table in the results page. In addition, I've tried to automatically add a ne row to the table every time a participant enters their data in. I've started with the "age" and "gender" fields with no luck. I want to do this for two more pages but I haven't bothered since I cannot get these two to work. I've tried multiple sources but have come empty-handed. If anyone can give me a solution, it would be helpful.
P.S.: I'm currently using Sublime Text 4, but I've also used Visual Studio Code.
Link to video: https://www.youtube.com/watch?v=0eV-tf-W2rQ&t=184s
Link to multiple videos: https://www.youtube.com/watch?v=e0ihEHxd6vI&list=TLPQMjIxMTIwMjFNmOKj8JKu0A&index=1
Here is the html code for my form and the javascript for the submit code:

And here is the html of the results page, wth some css and javascript:


text:
Q: JQuery selection problem With this html:
<label for="DateOfBirth">
    <span>* </span>
    Date Of Birth:
</label>

How do I select and remove the span element using JQuery?

A: Like this:
$("label[for='DateOfBirth'] span").remove();

This selector matches all <span> elements inside <label> elements that have a for attribute of DateOfBirth.
You could also write span:has('*') to only match <span> elements that contain a * in their text.

A: Actually there are many ways I guess. Question is which one is faster -and maybe more readable.
But remember, if you add more spans there
$("label[for='DateOfBirth'] span").remove();

will remove all of them. So if you want to be more specific you can give an id to your span and reach it with the id you passed.
Or you can use an indexer to reach the first span in your label.
see:
http://docs.jquery.com/Selectors/eq#index


text:
Q: Any good online source of information about Lync SDK Client Automation programming in .NET? Is there any good source of information about the Lync SDK in gerenal, and about Lync Client Automation in general?
Free online sources are preferable, but if there are none that you know of, I'll settle for a good book (please recommend only one you've made use of).

A: The SDK documentation and sample apps are a great place to start.
There are the MSDN Technical Articles, a good collection of general Lync resources, and the Training Kit.
This book is really useful.
Also, keep an eye on my blog, CodeLync. It's relatively new, but i'm actively adding more content


text:
Q: Child grid custom command button I have a question based on my current situation, I have a grid with ClientDetail / Child grid inside of it. In my parent grid there is a custom command button, let say...
"columns.Command(
   command => { command.Custom("Edit").Click("showEdit"); command.Destroy();
 }).Width(160);"

and also i had my custom command button as well in my child grid, let say...
"columns.Command(
 command => { command.Custom("Edit").Click("showSubEdit"); command.Destroy();
 }).Width(160);"

Those 2 custom command should call different function which is "showEdit" & "showSubEdit". The problem is, every time custom command in child grid triggered, it always calls its parent's function which is "showEdit", however the child grid should call "showSubEdit".
Is there something i missed ?
NB :
function showEdit(e) {
...
}
function showSubEdit(e) {
...
}

Grid Code :
<div>
    @(Html.Kendo().Grid<ActivityModel>()
        .Name("GridActivity")
        .Columns(columns =>
        {
            //columns.Template(t => { }).Title("No").ClientTemplate("#= renderNumber(data) #").Width(50);
            columns.Bound(c => c._id).Visible(false);
            columns.Bound(c => c.ActivityType.TypeTitle).Title("Type").Width(80);
            columns.Bound(c => c.ActivityTitle).Title("Title").Width(120);
            columns.Bound(c => c.DependenciesStr).Title("Dependencies").Width(120);
            columns.Bound(c => c.ResourcesStr).Title("Resources").Width(120);
            columns.Bound(c => c.FromStr).Title("From");
            columns.Bound(c => c.ToStr).Title("To");
            columns.Bound(c => c.Status).Title("Status").Width(90).Format("{0:0.00} %").Width(85);
            columns.Bound(c => c.Weight).Title("Weight").Format("{0:0.00} %").Width(85);
            columns.Command(command => { command.Custom("Edit").Click("showEdit"); command.Destroy(); }).Width(160);
        })
        .HtmlAttributes(new { style = "height: 290px;" })
        .Groupable()
        .Scrollable()
        .Sortable()
        .Filterable()
        .ClientDetailTemplateId("template")
        .Pageable(x => x.PageSizes(new int[] { 10, 20 }).Refresh(true))
        .Resizable(resize => resize.Columns(true))
        .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(10)
            .Model(c => c.Id(p => p._id))
            .Read(read => read.Action("ProjectActivities_Read", "Project", new { projectId = ViewBag.ProjectId }))
            .Destroy(destroy => destroy.Action("ProjectActivities_Destroy", "Project", new { projectId = ViewBag.ProjectId }))
        )
        .Events(x => x.DataBound("resetRowNumber"))
    )
</div>

<script id="template" type="text/kendo-tmpl">
    @(Html.Kendo().TabStrip()
            .Name("TabStrip_#=_id#")
            .SelectedIndex(0)
            .Animation(animation => animation.Open(open => open.Fade(FadeDirection.In)))
            .Items(items =>
            {
                items.Add().Text("Sub Activity").Content(@<text>
                    @(Html.Kendo().Grid<ActivityModel>()
                        .Name("GridChild_#=_id#")
                        .Columns(columns =>
                        {
                            columns.Bound(x => x._id).Visible(false);
                            columns.Bound(x => x.ActivityType.TypeTitle).Title("Type");
                            columns.Bound(x => x.ActivityTitle).Title("Title").Width(150);
                            columns.Bound(x => x.DependenciesStr).Title("Dependencies").Width(150);
                            columns.Bound(x => x.ResourcesStr).Title("Resources").Width(150);
                            columns.Bound(x => x.FromStr).Title("From");
                            columns.Bound(x => x.ToStr).Title("To");
                            columns.Bound(x => x.Status).Title("Status").Width(90).Format("{0:0.00} %").Width(85);
                            columns.Bound(x => x.Weight).Title("Weight").Format("{0:0.00} %").Width(85);
                            columns.Command(command => { command.Custom("Edit").Click("showEditSub"); command.Destroy(); }).Width(160);
                        })
                        .Pageable(x => x.PageSizes(new int[] { 5, 10 }).Refresh(true))
                        .Resizable(resize => resize.Columns(true))
                        .DataSource(dataSource => dataSource
                            .Ajax()
                            .PageSize(5)
                            .Model(x => x.Id(y => y._id))
                            .Read(read => read.Action("ProjectSubActivities_Read", "Project", new { projectId = ViewBag.ProjectId, activityId = "#=_id#" }))
                            .Destroy(destroy => destroy.Action("ProjectSubActivities_Destroy", "Project", new { projectId = ViewBag.ProjectId, activityId = "#=_id#" }))
                        )
                        .Pageable()
                        .Sortable()
                        .ToClientTemplate())
                </text>
                );
            }).ToClientTemplate())
</script>

A: I got around the bubbling by checking if the element shown by the first command event is visible:
function showDetailsLevel(e) {
    e.preventDefault();
    originatingId = this.dataItem($(e.currentTarget).closest("tr")).Id

    var wnd = $("#Details").data("kendoWindow");

    if (!$("#Details").is(":visible")) {
        wnd.center();
        wnd.open();
        var grid = $("#DetailGrid").data("kendoGrid");
        grid.dataSource.read();
    }
}


text:
Q: Computation: better to truncate before insertion or let MySQL truncate? Difficult question to phrase, so let me explain.
As part of an RSS caching system I'm inserting a lot of rows into a DB, several times a day. One of the columns is 'snippet', for the description node in the RSS feeds.
Sometimes this node is far longer than I want, since the corresponding DB column is type "tiny text" (max: 255 chars).
So, in terms of computation/memory, is it better for me to truncate via PHP before insertion, or just feed the whole, too-long string to MySQL and have it do the truncation?
Both of course work, but I wondered if one was better practice than the other.

A: In cases like this it's probably best to measure. If you don't notice a difference then it doesn't matter.
My intuition tells me that, since your snippet size is very small and the plain text can be very big it would be better to truncate before hand. Take the performance hit in PHP so you don't spend a lot of time sending a large query to MySQL.
For readability and code clarity it would also be better to do the truncation in PHP because that makes it explicit. You can even do clever truncating by word or by sentence.


text:
Q: Reply to an outlook mail using powershell I am trying to automate some replies to email that I get on my outlook. I have tried sending mail from my outlook (normal mail) using powershell and it worked successfully. Now I am trying to reply on mail using powershell. This is my current code as of now:
$o = New-Object -com Outlook.Application
$all_mail = $o.Session.Folders.Item($myEmailId).Folders.Item("Inbox").Items
foreach ($mail in $all_mail) {
    if ($mail.subject -match "Re: Testing") {
        $reply = $mail.reply()
        $reply.body = $reply.body + "Adding this extra info in mail."
        $reply.send()
    }
}
#myEmailId is my emailId, if trying this script, replace it with yours.

When I run this, I am getting the following error
Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
At line:7 char:13
+             $reply.send()
+             ~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

I have printed the logs in between while debugging and found that it is successfully picking up all the emails in my outlook. The if condition where it matches the mail subject is also working fine. I tried going through various resource on internet but could not find any resolution for this. Any help or direction will be really helpful.

A: Helping myself with the Microsoft Dev Blog :
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
Add-type -assembly "System.Runtime.Interopservices"

try
{
$outlook = [Runtime.Interopservices.Marshal]::GetActiveObject('Outlook.Application')
    $outlookWasAlreadyRunning = $true
}
catch
{
    try
    {
        $Outlook = New-Object -comobject Outlook.Application
        $outlookWasAlreadyRunning = $false
    }
    catch
    {
        write-host "You must exit Outlook first."
        exit

    }
}

$namespace = $Outlook.GetNameSpace("MAPI")

$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)

$mails = $inbox.Items | Where-Object {$_.Subject -like "ABC TEST*"}

foreach($mail in $mails) {
    $reply = $mail.reply()
    $reply.body = "TEST BODY"
    $reply.send()
    while(($namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderOutbox)).Items.Count -ne 0) {
        Start-Sleep 1
    }
}

# Kill Process Outlook (close COM)
Get-Process "*outlook*" | Stop-Process –force

The while loop on the Items.Count  is used to check if the OutBox is empty or not. If you close the Outlook Process before it's done, your mail won't be sent.


text:
Q: python TypeError : unbound method UpdateVideoEntry() must be called with YouTubeService instance I'm trying to update an entry using the youtube api.  Here is my error i'm struggling with:

Traceback (most recent call last):   File "", line 1, in

      updated_entry = gdata.youtube.service.YouTubeService.UpdateVideoEntry(YTVentry.id)
  TypeError: unbound method UpdateVideoEntry() must be called with
  YouTubeService instance as first argument (got NoneType instance
  instead)

Here is my code:
    import gdata.youtube
    import gdata.youtube.service
    import gdata.youtube.data
client = gdata.youtube.service.YouTubeService()
...
videos_feed = client.GetYouTubeVideoFeed(uri)
    for entry in videos_feed.entry:
    print entry.title.text
        YTentry = entry._GDataEntry__GetId
        YTVentry = gdata.youtube.YouTubeVideoEntry(YTentry)
        YTVentry.media.title = '09.11.2012 Hold me close'
        YTVentry.media.description = '09.11.2012 : Hold me close section'
        updated_entry = gdata.youtube.service.YouTubeService.UpdateVideoEntry(YTVentry.id)

According to the google gdata youtube docs:

To update video meta-data, simply update the YouTubeVideoEntry object
  and then use the YouTubeService objects' UpdateVideoEntry method. This
  method takes as a parameter a YouTubeVideoEntry that contains updated
  meta-data.

thanks in advance.

A:     updated_entry = gdata.youtube.service.YouTubeService.UpdateVideoEntry(YTVentry.id)

should be
    updated_entry = client.UpdateVideoEntry(YTVentry.id)

gdata.youtube.service.YouTubeService.UpdateVideoEntry(YTVentry.id)
  TypeError: unbound method UpdateVideoEntry() must be called with
  YouTubeService instance as first argument (got NoneType instance
  instead)

The error is complaining because you are trying to call UpdateVideoEntry from the class rather then the client object you created. You've created a YouTubeService object, client and you need to use that rather then calling the classes' method directy.

A: You're calling the method on the YouTubeService class, not on an instance of that class. In other words, you should be calling client.UpdateVideoEntry(...) instead of YouTubeService.UpdateVideoEntry(...) as with your other calls to the API.
The documentation even says you should call the method on a YouTubeService object, not on the class.
The error message indicates that you can call the class method directly, but you must pass an instance of the class as the first parameter. This is done implicitly when you call the method on an instance, but must be done explicitly when calling the method on the class. Otherwise Python won't know what instance the method should operate on (i.e., what self is).


text:
Q: Different notions of differentiability The following is somewhat unclear to me. Let $X$, $Y$ be locally convex vector spaces, let $f: X \supseteq U \longrightarrow Y$ be a (nonlinear) continuous map. Then one can say that $f$ is $C^1$ if
a) the difference quotient
$$ Df(x)\xi := \lim_{\epsilon \longrightarrow 0} \frac{f(x + \epsilon \xi) - f(x)}{\epsilon}$$
exists for all $x \in U$, $\xi \in X$ and if
$$Df: U \times X \longrightarrow Y$$
is continuous; or
b) $f$ maps $C^1$ curves in $X$ to $C^1$ curves in $Y$.
Question: Are the notions a), b) equivalent?
As far is understood, they are not in general, right? But for which spaces are they equivalent?
Addition: If $X$ and $Y$ are not Banach spaces, it seems too strong a notion to require the map $Df$ to be continuous from $X$ to $L(X, Y)$. Why is this so?

A: b) does not imply a) even when $X=Y=\mathbb R^2$. It's easier to describe the counterexample in complex notation:
$$f(r\exp(i\theta))  = r\exp(i\theta+i\sin 2\theta),\quad r,\theta\in\mathbb R  \tag1$$
It is important to notice that (1) applies both when $r<0$ and when $r>0$, giving consistent result because $\sin 2\theta$ is $\pi$-periodic.
The map (1) is not differentiable at the origin, because it is degree 1 homogeneous but not linear.
On the other hand, it maps $C^1$ curves to $C^1$ curves. Indeed, let $\Gamma:(-1,1)\to \mathbb R^2\approx \mathbb C$ be a $C^1$-curve. For definiteness assume $\Gamma(0)=0$. Let $\rho e^{i\phi}=\Gamma'(0)$; here $\rho>0$. Write $\Gamma(t)=t \rho e^{i\phi}+o(t)$ and plug this into $f$. Since $f$ is Lipschitz, we gave $$f\circ \Gamma(t)=f(t \rho e^{i\phi})+o(t) = t\rho e^{i\phi+i\sin 2\phi}+o(t) \tag2 $$  Hence, $f\circ \Gamma$ has a tangent at $t=0$.  Its tangent at the points where $\Gamma\ne 0$ has argument $\arg \Gamma'(t)+2\sin \arg \Gamma(t)$ which is consistent with (2): that is, the tangent direction is continuous along the curve.


text:
Q: Realization of Simplicial Sets respects Product My question refers to an argument in the the proof of thm 11.6 in Laures' and  Szymik's "Grundkurs Topologie" (page 227). Sorry, but there exist only a German version. Here the relevant excerpt:

The problem occurs in Step 2 ("Schritt 2"):
We use following notations:
If $K$ is a simplicial set then $\vert K \vert := \coprod_{n \ge 0}K_n \times \Delta^n_{top}$ is the realization of $K$, $\Delta^n_{top}$ is the standard $n$-simplex and $\Delta^n= Hom_{\Delta}(-, [n])$.
The aim (in "Schritt 2")is to show that for all simplicial sets $X$ (= functors from $\Delta$ to $(Set)$) the canonical map
(*)$$\vert X \times \Delta^n \vert = \vert X \vert \times \vert \Delta^n \vert$$ is homeomorphism.
So firsty we fix $X$ and observe that the class $C$ of all $X$ for which (*) is a homeomorphism is closed under pushouts and sums $\coprod$.
Then we consider the category $S(X)$ of all simplicial maps $\Delta^n \to X$.
The morphism of this category are the commutative triangles as given at page 227.
In the next step the author claims that following diagram is a pushout:

Why? I don't see why it has the universal property of a pushout.

A: Let $Y$ be any simplicial set and assume we have two maps $f,g : \displaystyle\coprod_{x: \Delta^n \to X}\Delta^n \to Y$ that make the above diagram commute, that is $f\circ (id, j) = g\circ (id, i)$ .
I will use the following convention : an element of the coproduct $\coprod_{i\in I}X_i$ is denoted $(x,i)$, where $x\in X_i$
Now assume $h: X\to Y$ makes the whole thing commute. Let $x\in X_n$ be an $n$-simplex. Then $x$ corresponds to some $\tilde{x} : \Delta^n \to X$ (by the Yoneda lemma), and so $h_n(x) = f((id_{[n]},\tilde{x}))(=g((id_{[n]},\tilde{x}))$ by commutation of the diagram). Therefore if $h$ exists it is unique.
Now define $h$ degree-wise as above, with $f$ : it is well-defined on each degree by the Yoneda lemma. We must show that it is a simplicial map and that it makes the diagram commute, after this by the uniqueness above we will be done. That it makes the diagram commute is quite obvious, as $(id,i),(id,j)$ are surjective, so since $f\circ (id,j) = g\circ (id,i)$ and $h$ is defined through $f$, so this is clear.
Let's now prove that it is a simplicial map. Let $\varphi : [m]\to [n]$ be nondecreasing and $x\in X_n$. Let me write the action of $\varphi$ on the right, as $X$ is a contravariant functor of $[k]$.
Then $h(x\cdot \varphi) = f((id_{[n]},\widetilde{x\cdot\varphi})$, but $\widetilde{x\cdot \varphi}$ is nothing but $\tilde{x}\circ \overline{\varphi}$ where $\overline{\varphi}$ is the induced map $\Delta^m\to \Delta^n$; for this you have to explicit the Yoneda isomorphism.
Also, $(id_{[n]},\tilde{x}\circ \overline{\varphi}) = (id,j)(id_{[m]}, \overline{\varphi}: \tilde{y}\to\tilde{x})$ where $y = x\cdot \varphi$, therefore $h(x\cdot \varphi) = g((id,i)(id_{[m]}, \overline{\varphi}: \tilde{y}\to\tilde{x})$.
Now $i(id_{[m]}, \overline{\varphi}: \tilde{y}\to\tilde{x}) = (\overline\varphi(id_{[m]}), \tilde{x})$ by definition.
Now if you recall the definition of the induced map $\Delta^m\to \Delta^n$ and of the simplicial structure on $\Delta^n$, you see that $\overline\varphi (id_{[m]}) = id_{[n]}\cdot \varphi$. Therefore $h(x\cdot \varphi) =g((id_{[n]}, \tilde{x})\cdot \varphi) = g((id_{[n]},\tilde{x}))\cdot \varphi = h(x)\cdot \varphi$ : $h$ is simplicial; and we are done.


text:
Q: Want to show just captured photo instead of live view When I capture a photo from camera, I want to show it instead of live view.
Is there anything wrong with the URI or should I write a return page code?
What I am doing so far:
 public void btnTakePhotoClicked(View v) {
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String fullPath = "";
    File imageFile = null;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String pictureName = "IMG_" + timeStamp + ".jpg";

    fullPath = Environment.getExternalStorageDirectory() + "/ImageFolder/" + pictureName;

    File dir = new File(Environment.getExternalStorageDirectory() + "/ImageFolder/");

    imageFile = new File(fullPath);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
}


text:
Q: How to kill a specific thread from an array of threads I am creating an array of threads based on the number of records in a database. Each thread then polls an ipaddress and then sleeps for a time and then repolls again. I periodically check the database for any change in the number of hosts. If there are more hosts I start another thread. If there are less hosts I need to kill the specific thread that was monitoring that host. How do i kill the specific thread.
enter code here protected static void GetThreads()
    {
        Thread[] threads;
        do
        {
            dt = getIP_Poll_status();
            threads = new Thread[dt.Rows.Count];
            Console.WriteLine(dt.Rows.Count + " Threads");
            for (int i = 0; i < threads.Length; ++i)
            {
                string ip = dt.Rows[i][0].ToString();
                int sleep = Convert.ToInt32(dt.Rows[i][1].ToString());
                string status = dt.Rows[i][2].ToString();
                string host = dt.Rows[i][3].ToString();
                Hosts.Add(host);
                string port = dt.Rows[i][4].ToString();
                //Console.WriteLine("starting on " + ip + " delay  " + sleep+".current status "+status);
                threads[i] = new Thread(PollingThreadStart);
                threads[i].Start(new MyThreadParameters(ip, sleep, status, host, port));
                threads[i].Name = host;

            }
            Thread.Sleep(50000);
        }

        while (true);
    }

A: Killing threads forcibly is a bad idea. It can leave the system in an indeterminate state.
You should set a flag (in a thread-safe way) so that the thread will terminate itself appropriately next time it checks. See my threading article for more details and sample code.
I would add that using Sleep is almost always the wrong thing to do, by the way. You should use something which allows for a graceful wake-up, such as Monitor.Wait. That way when there are changes (e.g. the polling thread should die) something can wake the thread up if it's waiting, and it can notice the change immediately.

A: Given that most of your threads will spend the majority of their time doing nothing, your design might be better realised as a single thread that keeps a list of ip addresses and the time they're due to be polled next. Keep it sorted in order of next poll time.
Pseudocode:
What time does the next ip address need to be polled?
Sleep till then
Poll the address.
Update the poll time for that address to now + interval.
Resort the list
Repeat.

Whenever you have a DB update, update the list and then order the thread to re-evaluate when it needs to stop.

A: You don't specify the language you are targetting, but in general you use the same method regardless of the language. Simple use a shared variable that is used to signal the thread when it is time to stop running. The thread should periodically check the value and if it is set it will stop in a graceful fashion. Typically, this is the only safe method to stop a thread.

A: I would say:

*

*Don't kill threads. Ask them to die, nicely (vie Events or some shared flag).

*Be careful when creating exactly one thread per DB entry. This could mean that some unexpected DB activity where suddenly you have many rows translates into killing the OS with too many threads. Definitely have a limit on the number of threads.

A: You could send an interrupt signal to the thead you want to end. The thread that has been signalled would need to catch the ThreadInterruptedException that will be raised, and exit gracefully.
There are other, possibly better, ways to achieve what you want, but they are more complicated...

A: What you are trying to do is a bad idea because of the reasons mentioned above. However you can still give the thread a name which can be the host name. You may find out the thread by checking the name and kill it.


text:
Q: meaning of II symbol in a math equation I have a math equation that has II in it I cannot understand what the II function is and what it does. I really appreciate it if you can explain what it is.

A: It is a Capital i, as "indicator function"
you can also find $\mathbb{1}$ and indicates that the function is 1 for the values in the braces and zero elsewhere

Example,
Suppose you have the following function
$$ y =
\begin{cases}
x,  & \text{if $0<x<1$ } \\
2-x, & \text{if $1\leq x\leq 2$}\\
0, & \text{elsewhere}
\end{cases}$$
you can compact the notation and write
$$y=\{1-|1-x|\}\cdot\mathbb{1}_{[0;2]}(x)$$


text:
Q: SQL Server Select LIKE Regex Equivalent to '?' or '\\s*' I have a short question is there an equivalent to ? in SQL Server SELECT LIKE regex?
I try to select data from table in SQL Server 2012. Example data from column
...
<SOMETHING>
    <UNINTERESTING>test</UNINTERESTING>
    <INTERESTING>searchedString</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...

or
...
<SOMETHING>
    <UNINTERESSTING>test</UNINTERESSTING>
    <INTERESING>searchedString but nevertheless wrong</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...

I can select these with
LIKE '%<INTERESING>searchedString</INTERESTING>%'

everything works fine, but it is possible that the value between <INTERESTING> ends sometimes with one or more spaces
e.g.
<INTERESING>searchedString </INTERESTING>
<INTERESING>searchedString         </INTERESTING>

If I try to select with %, then I got rows, where the search string is found but not between interesting, or between two interestings, or I get the wrong rows like
<INTERESING>searchedString but nevertheless wrong</INTERESTING>

I tried to select with _, %, [ ] but nothing of them get me the correct rows.
Is there an equivalent in SQL Server LIKE regex for ? (none or one-time)
or anything like \s* (whitespaces, can be none, one or more-times)
Thanks in advance
best regards

A: Since you problem is spaces... just replace / remove those and your like statement should work and you can avoid other parsing and worrying about REGEX all together.
where replace(column,' ','') like'%<INTERESING>searchedString</INTERESTING>%'
If you expect TAB or NEWLINE then use replace and CHAR(10) and CHAR(13)
where replace(replace(replace(column,' ',''),char(10),''),char(13),'') like'%<INTERESING>searchedString</INTERESTING>%'

A:
Is there an equivalent in SQL Like Regex

No. You should use SQL Server's XQuery to parse the XML and extract the XML Element values, and then use LIKE for examining the element value.