text:
Q: Pandas dataframe plot 's' argument I have the statement and I really don't understand the s= part.  I know it sets the area of the plot but is it taking the data from pop_2007 and raising it to 1^6 to create the area ?
df.plot(kind='scatter', x='gdp_2007', y='lifeExp_2007', s=df['pop_2007']/1e6)

I'm trying to understand the area of a plot better and the s=

A: The 's' parameter in the pandas dataframe plot function is changing the size of the markers in your scatter plot. See these two outputs where I change the 's' value from 1 to 100. So right now, your plot is taking the value in the df['pop_2007'] column and dividing it by 1e6 to get your value for the marker size.
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('data.csv')

df.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=1)

plt.show()

#Two  lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

Plot with s=1
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('data.csv')

df.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=100)

plt.show()

#Two  lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

Plot with s=100
Test it out here: https://www.w3schools.com/python/pandas/trypandas.asp?filename=demo_pandas_plot_scatter2


text:
Q: Are the numerical parameters of TranslateAnimation in dp or px? I was reading through the documentation of TranslateAnimation and I saw that this is one of the many constructors of the TranslateAnimation class:
public TranslateAnimation (float fromXDelta,
            float toXDelta,
            float fromYDelta,
            float toYDelta)

Reading further on what each of the parameters denote, I saw that fromXDelta means:

Change in X coordinate to apply at the start of the animation

[...and so on for the other parameters.]

Question:
I understand what these parameters imply but I do not know how to represent them. What's the metric and reference point? Are they meant to be in dp or pixels?

A:
Like @Mike M. said, most dimensions on the code side are in
  Pixel.

However, this is not a hindrance as you can still convert easily from dp to px and back. Here are two functions you can use to achieve this:

dp to px:
public float convertDpToPixel(float dp, Context context) {
    return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

px to dp
public float convertPixelsToDp(float px, Context context) {
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

PS:
If you need your returned dp value in int rather than float, you can just pass the value inside Math.round().
I hope this helps someone out there. Merry coding!

redpajama_set_name: RedPajamaStackExchange


text:
Q: urxvt add padding (distance between text and border) Is it possible to increase the space between text and border in urxvt, and if so, how? I can't find any resources on it online.

A: You are looking for the internalBorder value:
URxvt.internalBorder:  4
From man urxvt:
internalBorder: number
     Internal border of number pixels. This resource is limited to 100;
     option -b.


text:
Q: "Sep 2013" in csv is autoformatted as date, and I want it as a text format I have a problem in csv. Whenever I set the cell to "Sep 2013", after closes the csv file and reopens it, the "Sep 2013" is always formatted to Date.
I want the "Sep 2013" is set as text not on Date.
Can someone help me? thanks


text:
Q: Exporting files from docker volume to another directory I have a python code which reads data from the file and do some calculation and save the result to the output file. The code also saves the logs in log file. So in my current directory, I have below files:
1. code.py  --> The main python application
2. input.json --> This json file is used to take input data
3. output.json --> The output data is saved in this file.
4. logfile.log --> This file saves the log.

All the above file is inside the directory Application. Full path is /home/user/Projects/Application/. Now when I am running the code.py I am getting the expected results. So I converted the above code into docker by using below Dockerfile:
FROM python:3

ADD code.py /

ADD input.json /

ADD output.json /

ADD logfile.log /

CMD [ "python3", "./code.py" ]

When I am running the docker container, it is running fine but I cannot see the output data and logs in output.json and logfile.log. Then I searched for these file in the file system and found these files in below directory:
/var/lib/docker/overlay2/7c237c143f9f2e711832daccecdfb29abaf1e37a4714f34f34870e0ee4b1af07/diff/home/user/Projects/Application/
and all my files were in that directory. I checked for the logs and the data, it was there. Then I understood that all the files will be saved inside the docker volumes and not in our current directory.
Is there any way I can keep the files and all the data in my current directory /home/user/Projects/Application/ instead of docker because in this way it will be easy for me to check the outputs.
Thanks

A: The files are located under the docker overlay volume because you didn't do volume mounting. To overcome this, you can modify your Dockerfile to look similar to this:
FROM python:3
RUN mkdir /app
ADD code.py /app
ADD input.json /app
ADD output.json /app
ADD logfile.log /app
WORKDIR /app
VOLUME /app
CMD [ "python3", "./code.py" ]

Then in your docker run command, make sure you pass this option:
-v /home/user/Projects/Application:/app

More information about container options can be found at https://www.aquasec.com/wiki/display/containers/Docker+Containers.
If you are using docker compose, you need to add:
volumes:
    - /home/user/Projects/Application: /var/www/app

A: You may try to run your container as below: [you may not need to build your image]
docker run --rm -v /home/user/Projects/Application/:/home/user/Projects/Application/ -d python:3 /home/user/Projects/Application/code.py
-v ; bind mount local folder into your container at /home/user/Projects/Application/.
Feel free to take out --rm if you don't need that.
Please make sure code.py write logs to /home/user/Projects/Application/logfile.log
To verify files and folders are there are not by running command:
docker run --rm -v /home/user/Projects/Application/:/home/user/Projects/Application/ -d python:3 sh
This will drop you in a terminal, you can list files and make sure required files and configs are there.


text:
Q: How to get label's height when text goes multiple lines I am creating a label programatically in a detail view  on table cell click.aI am setting the text accordingly  and set the label height for that. This is my code :
NSString *mytitleString = [discussionData valueForKey:@"Name"];
 CGSize size =  [mytitleString sizeWithFont:[UIFont systemFontOfSize:14.0]  constrainedToSize:CGSizeMake(500, CGFLOAT_MAX)];
 float lbltitleheight = size.height;
 lbltitle.text = mytitleString;

but the problem is i am not able to set the height of lable if it is multiple line. How do i achieve this?

A: You could also use
label.numberOfLines = 0; // allows label to have as many lines as needed
label.text = @"some long text";
[label sizeToFit];
NSLog(@"Label's frame is: %@", NSStringFromCGRect(label.frame));

Where the size will be adjusted accordingly.
Or you simply have to increase the height of your UILabel Dynamically. The sizeWithFont constrainedToSize:lineBreakMode: is the method to use.
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

A: Why you can't set labels size?
Did you try to set label as multiline:
NSString *mytitleString = [discussionData valueForKey:@"Name"];
CGSize size =  [mytitleString sizeWithFont:[UIFont systemFontOfSize:14.0]
                         constrainedToSize:CGSizeMake(500, CGFLOAT_MAX)
                             lineBreakMode:lbltitle.lineBreakMode];
lbltitle.frame = (CGRect){.oririn = lbltitle.frame.origin, .size = size};
lbltitle.numberOfLines = 0;
lbltitle.text = mytitleString;

I also recommend not use method sizeToFit, as when you will call this multiple times - label may become too narrow.

A: please try this:
CGFloat height=[mytitleString sizeWithFont:[UIFont fontWithName:@"Arial" size:14] constrainedToSize:CGSizeMake(500, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap].height;

hope this will help you.

A: Your code is correct but you need to set numberOfLines is 0. Because it is 1 bydefault.
lbltitle.numberOfLines = 0;

A: You can try this
 lbltitle.text = mytitleString;
 lbltitle.numberOfLines=0;
    [lbltitle sizeToFit];

A: try this:
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 34.0)];
[label setBackgroundColor:[UIColor clearColor]];
[label setNumberOfLines:0];
label.adjustsFontSizeToFitWidth = YES;
label.minimumFontSize = 10.0;
[label setTextColor:[UIColor blackColor]];
[label setFont:[UIFont fontWithName:@"YourFont" size:15]];
[label setTextAlignment:UITextAlignmentCenter];
[label setText:yourText];

A: CGRect rect_mission = CGRectMake(0, stringSize.height + stringSize_award.height+ 190, 280, stringSize_mission.height+60);

A: Your code should work correctly.
Try changing the numberOfLines for the label and set it to a max number which it can be extended.

A:     CGFloat height=[yourlable sizeWithFont:[UIFont fontWithName:@"Arial" size:31] constrainedToSize:CGSizeMake(yourlable.frame.size.width,1000) lineBreakMode:UILineBreakModeWordWrap].height;

and you get the dynamic height of label.


text:
Q: Target the XNA framework in ordinary Visual Studio 2012 project I have a C# XNA host project, with an F# client project that will contain all my functionality. It won't build because the F# project has references to mscorlib.dll and System.dll that the XNA project doesn't agree with (the actual error -- well, its really a warning that in my opinion should be an error -- is at the bottom of the post). How can I tell the F# project to target the actual XNA platform (specifically for the Xbox 360)?
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1578,5): warning MSB3268: The primary reference "\\vmware-host\Shared Folders\Projects\FSharp\Whirlygigs\Whirlygigs.Lib\bin\Debug\Whirlygigs.Lib.dll" could not be resolved because it has an indirect dependency on the framework assembly "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0,Profile=Client". To resolve this problem, either remove the reference "\\vmware-host\Shared Folders\Projects\FSharp\Whirlygigs\Whirlygigs.Lib\bin\Debug\Whirlygigs.Lib.dll" or retarget your application to a framework version which contains "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=***".
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1578,5): warning MSB3268: The primary reference "\\vmware-host\Shared Folders\Projects\FSharp\Whirlygigs\Whirlygigs.Lib\bin\Debug\Whirlygigs.Lib.dll" could not be resolved because it has an indirect dependency on the framework assembly "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0,Profile=Client". To resolve this problem, either remove the reference "\\vmware-host\Shared Folders\Projects\FSharp\Whirlygigs\Whirlygigs.Lib\bin\Debug\Whirlygigs.Lib.dll" or retarget your application to a framework version which contains "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=***".

A: The problem that you are having is that one of your projects is targeting the Windows versions of the .NET Framework (mscorlib, System) and one of your projects is targeting the Xbox 360 versions of the framework. And, basically, you cannot link together assemblies targeting different core frameworks.
I'm guessing that your F# project is targeting the Windows versions of the assemblies. What you need to do is get your F# project to target the Xbox 360 reference assemblies.
(Note that I've never done this myself - so my answer is just a list of things you could try.)
For your reference, these reference assemblies are installed by default to C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Xbox360\
First of all, you could try using the Portable Class Library. I've heard mixed reports about this.
The way I would probably do this is with some manual MSBuild trickery. A Visual Studio project file is an MSBuild file (which is XML). You can open it up in a text editor and play with it. You'll notice that an XNA project imports the following file:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\XNA Game Studio\Microsoft.Xna.GameStudio.targets" />

So you could try simply adding that import to your project file (and maybe some of the other XNA configuration, like <XnaPlatform>, in the appropriate place). That might do the trick.
If not, you could actually look at these files (they're at C:\Program Files (x86)\MSBuild\Microsoft\XNA Game Studio\v4.0) and try and figure out what they're using to set the path for framework assemblies. I'm not knowledgeable enough with MSBuild to say for sure.
Otherwise, you could just brute-force it. You can turn off the built-in referencing of the core frameworks by adding this to a <PropertyGroup>:
<NoStdLib>true</NoStdLib>

And then manually set the paths for each reference. So you would change this:
<Reference Include="mscorlib" />

To this:
<Reference Include="mscorlib">
  <HintPath>C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Xbox360\mscorlib.dll</HintPath>
</Reference>

And so on for all the other references. I've previously had success with this last method, for doing something similar (manually changing the target framework).


text:
Q: Magento: admin - product search filter I'm working for a client who owns a Magento-based store. It's chock full of products, but the names of said products are a bit messy. He did not stick to one naming convention but used different conventions throughout the years. So whenever he looks up something using the Name filter in the Admin -> Manage Products section, the results leave a lot to be desired.
So I was wondering if there's a way to make the filtering algorithm a bit more lax, specifically in regards to word order. Because if you have a product with a name like 'word1 word2 word3' and you search 'word1 word3' that products doesn't appear in the results.
Any hint would be appreciated. Cheers!
AUG 28 UPDATE: My search led me to the class *Mage_Adminhtml_Block_Widget_Grid*, and more precisely to its protected method *_addColumnFilterToCollection()*. In here you have the $cond variable, which if you print out it gives you something like this:

Array ([like] => Zend_Db_Expr Object([_expression:protected] => '%search term%' ))

Here if I could intercept that search term and make it into '%search%term%' before it gets submitted to the *Zend_Db_Expr* object I'd probably solve my problem. So, any ideas?

A: That would require coding a custom module having some complexity.
The expectation, that filtering for word1 word3 should at least return a subset of the matches, that filtering by word1 word2 word3 does return, is based on the false assumption that Magento does perform OR searches for this grid filter.
This is not the case. Magento does not perform OR, but LIKE searches in this case.
That also explains, why the result sets of a
LIKE name = '%word1 word2 word3%'

usually never* can match the result set of a
LIKE name = '%word1 word3%'

I think Mage_Adminhtml_Block_Catalog_Product_Grid::_prepareCollection() will be the minimum that needs to be overridden by your code, to get you started.
Good luck!

* except word2 == word3, of course

A: You can add 'filter_condition_callback' to any grid in Magento. Create a rewrite for Magento product grid and add this param to 'name' field. Like
$this->addColumn('name',
            array(
                'header'=> Mage::helper('catalog')->__('Name'),
                'index' => 'name',
                'filter_condition_callback' => array($this, 'filter_name_callback'),
        ));

And then determine filter_name_callback method in the same class.
Something like this:
protected function filter_name_callback($collection, $column)
    {
        $names = $column->getFilter()->getValue();
        $namesArray = explode(' ', $names);
        $cond = array();
        foreach ($namesArray as $item)
        {
            $cond[] = 'main_table.name LIKe %'.$item.'%';
        }

        $collection->getSelect()->where("(".implode(' OR ', $cond).")");
    }

The code was not tested, the example is simple, but I think you understand the idea ;) Good luck!

A: OK, here's a solution for this problem. Please note I have not tested this too much, just on my local test magento. So problems may arise.
Our work class is Mage_Adminhtml_Block_Widget_Grid, found in 'app/code/core/Mage/Adminhtml/Block/Widget/Grid.php'. You should copy this file in 'app/code/local/Mage/Adminhtml/Block/Widget/Grid.php', as to not overwrite core classes.
Now, in that file go to the function named _addColumnFilterToCollection. In here, delete everything inside the '} else {' statement and replace with:
$cond = $column->getFilter()->getCondition();
if ($field == "name" && isset($cond)) {
$filterOrig = $cond['like'];
$filterReplaced = str_replace(" ", "%", $filterOrig);
$newZendDbExpr = new Zend_Db_Expr($filterReplaced);
$modifCond = array('like'=>$newZendDbExpr);
$this->getCollection()->addFieldToFilter($field , $modifCond);
} else if ($field && isset($cond)) {
$this->getCollection()->addFieldToFilter($field , $cond);
}

The '$cond' variable is the key here. If you print it you get something like:
Array([like] => Zend_Db_Expr Object([_expression:protected] => '%filter term%'));

That code snippet basically intercepts the filter term that's passed to the Zend_Db_Expr object, passes it through a str_replace() to replace any whitespace with a '%' wildcard and then sends it back to the object.
So now if you have a product with a name like 'word1 word2 word3' and search filter by term 'word1 word3' you will get proper results. I am open to suggestions, this might not be the best approach. I'll update after properly testing this. Cheers!
SEP 06 UPDATE: Well, after some live testing, results are good and exactly what I wanted when. It seems there is no negative performance impact either.
And the interesting fact is that this little modification applies to filtering in every place where you have a product grid in the admin interface (for example when creating a new order manually and you click Add Products, or in the Manage Categories -> whatever category -> Category Products tab)
SEP 06 UPDATE 2: There is an issue. If you're in the Orders grids and try to filter by status it throws an error. I need to make this filter only apply to the Name field. Any ideas?
SEP 06 UPDATE 3: I revised the script to only apply to the Name field of Product grids. Now there are no conflicts with filter products by visibility or orders by status etc.

A: To do wildcard % search for a given column, and if you can override the core Grid.php, then you can do something like this in your grid class:
protected function _prepareColumns()
{
    parent::_prepareColumns();

    // assuming the column is 'name' for product name in the product grid
    $this->getColumn('name')->setFilterConditionCallback([$this, 'allowWildcardInFilter']);
    ...
}

/**
 * Allow wildcard % in column search
 */
public function allowWildcardInFilter($collection, $column)
{
    if ($value = $column->getFilter()->getValue()) {
        if ($field = $column->getFilterIndex() ? $column->getFilterIndex() : $column->getIndex()) {
            /**
             * @var $helper Mage_Core_Model_Resource_Helper_Mysql4
             */
            $helper = Mage::getResourceHelper('core');
            $likeExpression = $helper->addLikeEscape($value, [
                'position' => 'any',
                'allow_string_mask' => true
            ]);
            $collection->addFieldToFilter($field, ['like' => $likeExpression]);
        }
    }
}


text:
Q: How to ensure context listener routine finishes before main exits? Following is a simplified example of a scenario I am running into. Go Playground here.
The main method is periodically calling the process function. The process function acquires a lock that it must release before it returns or before the application is shut down due to an interrupt.
The interrupt is handled by cancelling the context passed to process. In my example, I am simply cancelling the context.
How can I ensure that when context is cancelled the unlocking logic is executed to completion?
ATM, in my tests, the logic is not getting executed to completion. The routine is kicked off, but does not seem to complete before the program exits.
It's as if the main method is exiting, killing the routine half way. Is that possible? How can I ensure that the routine always completes before the program exits? Thanks!
package main

import (
    "fmt"
    "context"
    "time"
    "sync"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    var wg sync.WaitGroup
    wg.Add(1)
    go func(){
        fmt.Println("Started periodic process")
        defer wg.Done()
        ticker := time.NewTicker(20 * time.Millisecond)
        for {
            select {
                case <-ticker.C:
                    process(ctx)
                case <-ctx.Done():
                    ticker.Stop()

            }
        }
        fmt.Println("Finished periodic process")
    }()

    time.Sleep(100 * time.Millisecond)

    // cancel context
    cancel()

    wg.Wait()
}

func process(ctx context.Context) {
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    go func() {
        <-ctx.Done()

        // unlock resources
        fmt.Println("Unlocking resources")

        time.Sleep(20 * time.Millisecond)

        fmt.Println("Unlocked resources")
    }()

    // do some work
    fmt.Println("Started process")

    // acquire lock, in actual process
    // acquiring lock will fail unless
    // it was released be previous process
    // run
    fmt.Println("Acquired lock")

    time.Sleep(10 * time.Millisecond)

    fmt.Println("Finished process")

}

A: As it stands your program will never exit. This is because the for loop in the goroutine started in main never exits (you stop the ticker when ctx.Done() but do not exit the loop).
A second issue is that in process the goroutine is cancelled when the function exits (via defer cancel()) but, due to the delay, the goroutine will continue to run for a period. The solution here depends upon whether you need the 'unlocking' to occur asynchronously (I have assumed this is not important).
The following (playground) resolves both issues and ensures that process does not return before the resources are free; if you need these to be freed in parallel then one option is to pass the WaitGroup to the function)
package main

import (
    "fmt"
    "context"
    "time"
    "sync"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    var wg sync.WaitGroup
    wg.Add(1)
    go func(){
            fmt.Println("Started periodic process")
        defer wg.Done()
        ticker := time.NewTicker(20 * time.Millisecond)
        for {
            select {
                case <-ticker.C:
                    process(ctx)
                case <-ctx.Done():
                    ticker.Stop()
                    fmt.Println("Finished periodic process")
                    return
            }
        }
    }()
    time.Sleep(100 * time.Millisecond)
    cancel()
    wg.Wait()
}

func process(ctx context.Context) {
    ctx, cancel := context.WithCancel(ctx)
    done := make(chan struct{}) // could also use a waitgroup

    go func() {
        <-ctx.Done()
        fmt.Println("Unlocking resources")
        time.Sleep(10 * time.Millisecond)
        fmt.Println("Unlocked resources")
        close(done)
    }()

    // do some work
    fmt.Println("Started process")
    time.Sleep(10 * time.Millisecond)
    fmt.Println("Finished process")

    cancel()
    <-done // Wait for resources to be unlocked
}


text:
Q: Comparing two objects' properties simply in c# I have a class with lots of properties. A shallow copy is enough to fully replicate the object.
I need to compare an object just to check if it contains exactly the same values as another.
My ideas:
The first and most obvious solution is just to create a huge method block that compares each property, one after the other.
The second would be to serialize each object and hash the file or do some sort of md5 checksum on it. (Would this actually work?)
The third is to do some sort of reflection on the object, which would automate the first option, but create an added level of complexity.
Speed isn't really an issue.
I'm interested to hear thoughts, or any other methods I am missing to do such a thing.
Edit:
Thanks all. My solution (Modified to now be recursive on generic items):
public static bool IsSame<T>(T objA, T objB)
{
    var type = typeof(T);
    var properties = type.GetProperties();
    foreach (var pi in properties.Where(a => a.CanRead))
    {
        if (pi.Name == "Item")
        {
            var piCount = properties.FirstOrDefault(a => a.Name == "Count");
            int count = -1;
            if (piCount != null && piCount.PropertyType == typeof(System.Int32))
                count = (int)piCount.GetValue(objA, null);
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    dynamic child1 = pi.GetValue(objA, new object[] { i });
                    dynamic child2 = pi.GetValue(objB, new object[] { i });
                    return IsSame(child1, child2);
                }
            }
        }
        else
        {
            var val1 = type.GetProperty(pi.Name).GetValue(objA, null);
            var val2 = type.GetProperty(pi.Name).GetValue(objB, null);
            if (val1 != val2 && (val1 == null || !val1.Equals(val2)))
                return false;
        }
    }
    return true;
}

A: Most serializers are designed to ensure that data retains its integrity during serialization and deserialization, not to produce a consistent serialized format. I would avoid using serialization for this purpose.
You may consider implementing IEquatable, to have each instance capable of comparing itself with instances of the same type. Or a class do do the comparisons for you that implements IEqualityComparer. How they do this comparison may be the 'big method' that compares properties one after the other, or uses reflection.
Reflection can be a fairly quick and simple way to achieve your goal but can cause problems down the line (for example if someone adds a property to your type that should not be included for comparing equality), but obviously the converse is also true (someone adds a property that should be checked for equality, but the equality comparison isn't updated). Which approach you use should generally be decided by how comfortable the team is with each approach in tandem with the context in which the class will be used.
In your case I'd probably recommend using the reflection based approach since you wish to check the result of a shallow clone operation, so all properties should be equal.
As an aside, I'd recommend using the MemberwiseClone method to create the clone, which would lessen the need for such stringent tests.

A: The third option (reflection) would be the slowest, but it would also be the most robust/testable.
The hash code would be very similar to the first option, since you would have to call all of your member variables, so 1 and 2 would require you to update your .Equals(obj) and .GenerateHash() methods every time you modify your member variable lists.
Here is some code to get you started:
foreach (FieldInfo field in this.GetType().GetFields())
{
    if (o[field.Name] == null)
    {
        if (!field.GetValue(this).Equals(o[field.Name]))
            return false;
    }
    else
    {
        return false;
    }
}

return true;

A: Another thought is that if the properties return simple value types you could group them into immutable value types of their own.  For instance, if you have a customer with properties string Address1 string Address2 string City string State string Zip, you could create a value type Address that implements its own equality comparer and use that.
Not sure if this applies to your situation, but I've found that when I have a class with a lot of properties, it is often possible to do this, and it tends to make my classes simpler and easier to reason about.

A: If you serialize you have to specify the serialization order on each Field/Property to ensure that all data is serialized int the same order. But all you would achieve is to implement GetHashCode() in an external class.
GetHashCode() has some examples on how to override it, so look there first.
If your class has a lot of fields, and you don't want to write all the code by hand. You could use reflection to autogenerate the code. If your class changes from time to time then you could create a partial class with the GetHashCode() implementation in a T4 template.


text:
Q: Bootstrap 3 navbar flicker when open and vanish I have this navbar in bootstrap and when i click my hamburger icon it just flickers and open menu then vanish... I cannot understand why really. Feels like i being blind staring at code..

 Stockholm

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navDefault">

            </button>

Bubbles

About

Contact

Below CSS
body {
padding-top:0px;
}

    .navbar-brand
    {
        position: absolute;
        width: 100%;
        left: 0;
        top: 0;
        text-align: center;
        margin: auto;
    }
    .navbar-header {
      float: none;
    }
    .navbar-toggle {
      display: block;
    }
    .navbar-collapse {
      border-top: 1px solid transparent;
      box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }
    .navbar-collapse.collapse {
      display: none!important;
    }
    .navbar-nav {
      float: none!important;
      margin: 7.5px -15px;
    }
    .navbar-nav>li {
      float: none;
    }
    .navbar-nav>li>a {
      padding-top: 10px;
      padding-bottom: 10px;
    }

Example here
http://www.bootply.com/QKMDlXRfP6

A: After some research I found the answers I need to make it work with the latest Bootstrap 3.3.4

      www.raqt.com

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navDefault">

            </button>

Bubbles

About

Contact

CSS
body {
    padding-top:0px;
}

.logo{
  width: 100px;
    height: 24px;
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABKCAYAAABNRPESAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABZhJREFUeNrsXf912jAQFnn8X3eC0glCJ4iZIGSCmAlKJwhMQJkAMgF0AtwJ4kwAnaDuBFSXnFuXyvhOPtniRfeeHq9UtqT7dN/9sEyUCiIqx+NxdqyXXdX1/aDAY6Q/hrrB50C3TLe81+tlXcyn/0ZBAMV/1m2MIJj6HPTHVrelBufgNSClXRXjVwdsmZ58bnkvVbqfOrmv0vdNhazhQbcpofsA+031dXM9/qwNQHrAeYR+a9glum9c2llVkuq+oxqlwPW3CEDEmC+AA8A8cgHS4wLoqxL4XAEKG5k2HOql2Ew3ho1lWsejSc/qSJOxbhti310VEOjwfh5lZI+KIFmG0Lh7pDsbR06R+Iq4O1Y1VlGnEFDcHukiErJuUMxO33tB6LsTGhfG3KCVOxEqIFEDMBJBhZgEOH51LgxtQFMmgXttugbEFowxWpdrSXAsk7/67GC8WN97elGAoDLaAOMPrRqoJHFomQ8uqMulhSwcKqOKVk+txNY6UmxZzXgL6UX0HVpHYqEEUMCv0neUEPIUgHUpzB1YhLZ35UQQA5JFhR8Cqpz7Akh64uiiE6qgylfd5lUJJYI7xQit1uFCf7xXzFzPwZRnQL6j7znCwGRYsQmWJX3cE9YPwH8xfs+MkyGWn5q4E+JziKgwJqfmLFOG1VFj/Rj7r5hrSwi5zN6kE8niIgeQJ6QBivIoSdgTlwY5IMOiORuNmk/VgdkUEKpTz9GcqRVQijN/ZNV4XqkkY4zNyT22xDlUOfrbtqOsCbVoSC1nEJVr2hhKcFMU8oPRd2n4biwVAvcdKOKlCMcFBGtEA1Tk8EzpwoVkTGtaVWTwaVuAcKklJYTFwMc36t8yfleSc9an550a5hx7CQihlHKvGhQqPZHvBkA+eJsYVgCxcEg5bUvmik5dFxcjrMRuPAeDS5m5K0D6LsE4k91etGD2fnEWsukYDI6DvfYF7CtH1jG9pMhJauNI5CJXDsAoTnZwlQfx/RxzGGgfeyfC3PXPjL4DocSuMbAufMiYkSUf1Guld91xslfMe92xVTuhLGpdByzikyMwbAC5F6Cm3EdAhkTLmHAP1TEjoQOOQw59TUd8OGGyxPFTF4BQFrV1CYZlpAWyEmYBvxLDM/LL8jqu4/3GTRDrHpqhFSUVVn+xgLyziN7Yx0C1FW4teH1RdbwWfcfmDA03pvWuAEkYTx+H+HQxsRxra3HNAz5xTAq/gvW4c5WH7xxLrwoMXACSEqmnWLDp+XxUnCfW/3xqGN/bngqJ0ae8PEcnVB64/mpaWm+M650pzsEBapZuccj4CXfkruIgAUdmJro7upX9iXKtxYWF2FBE8ZAqVm6qwnPHFPwodSNxQDD+d60An+YEQcPX0lipV4DgpGbK7hCDS1BmSuARq0GWhpxq6xUgKCPfQNFyJzynrOJVt6V3gOCuGQnvylxoThKgVJ6uQdqa+2YhLwrA9w0nDTJZUOJat48SiiyBsm4Y2o/OlX/QcibcTcR66bOpMjC5uiVEUxm2b5htF9cnhCgspTrWmpPt53QxYay5eE3iRv1/7uyADUB7fpl7l4SO2Xp0wsl5B/OISxtlKAlIEAErljwk7pUPuVCpo+ZhUFH7ViJWSgoWIpRfdGUlARA72voQAGlXnoOFXBZlBR/iGSCK+sQzACIgxKpEAKRlSWv+/zoA8gYSxABItdS9mRsHQPyiLCeOPQBiT1lOaCsA0izSug6A+EVbwUI8o604AOJXpCXu2AMgDSMtadoKgDSPtK4DIH5FWuGRbptC+WW6YCGe0ZakYw+ACERaSvAVigCIZ5FWAEQm0roNamrXsTf+3V9yZBfUXQsGnD2m/K4vnPR/HyjLvVAddsT4aY4gjinrp+nvl9hIP6ibJJ/U648GgIPP8fOH+vt+x0HqT+v9FmAA7gRc8Hw3ruUAAAAASUVORK5CYII=')
  }
.navbar-center
{
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    text-align: center;
    margin: auto;
  height:100%;
}

    .navbar-header {
        float: none;
    }
    .navbar-left,.navbar-right {
        float: none !important;
    }
    .navbar-toggle {
        display: block;
    }
    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }
    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }
    .navbar-collapse.collapse {
        display: none!important;
    }
    .navbar-nav {
        float: none!important;
        margin-top: 7.5px;
    }
    .navbar-nav>li {
        float: none;
    }
    .navbar-nav>li>a {
        padding-top: 10px;
        padding-bottom: 10px;
    }
    .collapse.in{
        display:block !important;
    }

Bootply example


text:
Q: VS Code Debugging problems after last update (1.69.2) After the last update of VS Code to version 1.69.2 i am not able to debug my nodejs - express, project. I am getting unbound breakpoints when i am adding them. My launch.json file :
{
    "configurations": [
    {
        "name": "Attach by Process ID",
        "processId": "${command:PickProcess}",
        "request": "attach",
        "skipFiles": [
            "<node_internals>/**"
        ],
        "type": "node",
        "sourceMaps": false
    }
    ]
}

When i am trying to "troubleshoot the launch configuration" i am getting the error message from vs code : "it looks like your degug session has already ended......" but it is not, it is active.
In my project i am using nodejs - express - javascript mostly (no Typescript thats why i set sourceMaps to false).
I am starting my project with the command :
node --inspect sever.js
and after that i attach by procces the debugger ( to default 127.0.0.1:9229).
Can anyone help me to solve this problem? What has change after the last update and i can't use the degugging of VS Code?
Thanks a lot.

A: Download a previous version.
Also, disable auto updates from Settings -> Update.
https://code.visualstudio.com/updates/v1_68


text:
Q: how to insert a list of items somewhere with Repeater Suppose I have an Item which exposes a items property of type list<Item>, which now is set to:
items: [
    Rectangle {
        width: sz; height: sz
        color: 'red'
    },
    Rectangle {
        width: sz; height: sz
        color: 'green'
    },
    Rectangle {
        width: sz; height: sz
        color: 'blue'
    }
]

how to instantiate that list, e.g. inside a:
Row {
    spacing: 20
    Repeater {
        model: items
        delegate: ...?
    }
}

A: Found the answer in Item.data:
Row {
    spacing: 20
    data: items
}


text:
Q: Make a plot in python based on users input I ask the user 11 answers and give a numerical output based on their answers of how much carbon they use per year.
I would like to add a plot that shows visually the amount of carbon per answer the user put in. So far, i have been able to make a plot which shows the subcategories but I am unable to link this with the user's answers. All of my current values on the plot are at 0, regardless of what the user inputs.
here is a sample of my data frame:
image of my data frame
I want to be able to plot what the user inputs: ie if the user says yes they use a car, I would like to have a bar graph which shows the carbon emission of each subcategory of car. If the user says they use a car and a bike, I would like a bar graph which shows the carbon emission of both the subcategories of the car and the bike
Below is what I have so far for the plot, which returns a 0 value regardless of what the user inputs
plt.ion()
fig, ax = plt.subplots(figsize=(50, 20))
ax.scatter(subcat,m_p,marker='x')
ax.scatter(subcat,m_mp, marker ='x')
ax.set_xlabel("sub-categories")
ax.set_ylabel("carbon mass (g)")
ax.set_title('Carbon consumption per category')
ax.set_xticklabels(subcat,rotation = 45) # rotate labels

fig.savefig("Carbon_consumption.png") # save file as png


text:
Q: Ocultar @Html.ActionLink en @foraech con Razor mi problema es que quiero ocultar el @Html.ActionLink de esta vista:

        @Html.DisplayNameFor(model => model.Subject.Name)

        @Html.DisplayNameFor(model => model.State.Description)

        @Html.DisplayNameFor(model => model.Subject.Exams.FirstOrDefault().StartDate)

@foreach (var item in Model.Subjects) {

        @Html.DisplayFor(modelItem => item.Subject.Name)

        @Html.DisplayFor(modelItem => item.State.Description)

        @Html.DisplayFor(modelItem => item.Subject.Exams.FirstOrDefault().StartDate)

        @if ()
        {
            @Html.ActionLink("Inscribirse", "Register", new { id = item.StudentSubjectId })
        }

}

Que tiene el modelo:
namespace Academica.Models.StudentExamViews
{
[NotMapped]
public class SearchView : StudentSubject
{
    public List<StudentSubject> Subjects { get; set; }
}
}

Y el el controlador la siguiente acción:
public ActionResult Index()
    {
        var student = db.Students.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
        var subjects = db.StudentSubjects.Include(ss => ss.Subject.Exams).Where(ss => ss.StudentCareer.Student.StudentId == student.StudentId &&
                        ss.ExamEnabled == true).ToList();

        var view = new SearchView
        {
            Subjects = subjects,
        };

        return View(view);
    }

y esta el BD:

 Lo que necesito es ocultar el @Html.ActionLink "Inscribirse" cuando tenga un registro en la tabla StudentExams con ese mismo StudentSubjectId que corresponde a cada item del foreach
SeCon el boton inscribirse se guarda los registros en la tabla StudentExams con su respectivo StudentSubjectId (desde otrs accion de l controlador)

A: Lo primero que haria es agregar el include de StudentExams, o sea la linea
.Include(ss => ss.Subject.Exams.StudentExams)

quedando de esta forma
var subjects = db.StudentSubjects
                    .Include(ss => ss.Subject.Exams)
                    .Include(ss => ss.Subject.Exams.StudentExams)
                .Where(ss => ss.StudentCareer.Student.StudentId == student.StudentId &&
                ss.ExamEnabled == true)
                .ToList();

despues no entiendo porque el foreach lo realizas de los subjects y no del examen directamente
@foreach (var item in Model.Subject.Exams) {

            @Html.DisplayFor(modelItem => item.StartDate)

            @if (!item.StudentExams.Any())
            {
                @Html.ActionLink("Inscribirse", "Register", new { id = item.Subject.StudentSubjectId })
            }

}

de esta forma podrias preguntar si hay algun StudentExams relacionado, sino lo hay entonces muestras el link


text:
Q: Is it possible to view multiple Chrome devtools panels at once? Is there a way to view multiple Chrome devtools panels at the same time?  A split window, like this mockup, would be nice:

Or in separate windows.
It would be extremely useful to be able to view the Sources panel and Network panel at the same time, to see exactly when network requests are fired while stepping through code.
The console can be pulled up while inside any other panel by clicking  or pressing esc, so why not the other panels?
I haven't found much by searching, but maybe this is possible with a devtools extension.
Does this exist already?  If not, is it possible?

A: I find this limitation frustrating too, all those other monitors are wasted! Here is poor man's solution:

*

*launch your chrome with --remote-debugging-port=9999 command line parameter

*right click on your page to debug and select 'Inspect Element' - this is your debug window #1

*open a separate chrome window and navigate to chrome://inspect

*click 'Configure...' and add localhost:9999

*within a couple of seconds under 'Remote Targets' you should see tabs you can inspect from your other chrome instance

*click on the tab, and now this is your debug window #2

Unrelated tip: system wide nightmode experience: http://danielsokolowski.blogspot.com/2018/11/windows-10-8-7-night-mode.html

A: As of Chrome Canary 33.0.1732.0, there's a "Show editor in Drawer" experiment. The editor shows up whenever you hit any anchor to the source code in DevTools.


text:
Q: debian LTS : how to keep packages up-to-date with last security fixes using apt What's the best way to keep packages up-to-date (ie with the last security fixes) without worried about major version update ?
For instance, apache2 for squeezeis is  2.2.16 (https://packages.debian.org/source/squeeze/apache2)
However, last apache2 version for the 2.2.x branch is 2.2.27
Test repository can't be used since they use the 2.4.x versions and I'd like to stick on the 2.2.x (to avoid migration issues)
How would you handle this situation and how can I update to 2.2.27 ?

A: Usually just upgrading your packages from native repositories should be enough provided you have security.debian.org repository enabled in /etc/apt/sources.list.
At the moment limited "LTS" support is only available for previous ("oldstable") Debian release codename "squeeze". Read the following page for instructions how to configure your system to pull LTS updates:

*

*https://wiki.debian.org/LTS
From security prospective it is always better to use current Debian release a.k.a. "stable" which perhaps will be better supported than "LTS".
Read more:

*

*https://www.debian.org/doc/manuals/securing-debian-howto/ch4.en.html

*https://security-tracker.debian.org/tracker/

*https://www.debian.org/security/


text:
Q: Issue in webdav on mac machine A user with permission to create folders and components is not able to copy and paste items through WebDAV. This User is using Mac OS X Lion. The error he gets is that he does not have read and write permissions. Is there any resolution?

A: The WebDAV Connector is enabled by default server-side per the SDLLiveContent documentation at least for SDL Tridion 2011.
Only valid items are allowed via WebDAV which includes binaries (multimedia in Tridion), .xml components, and other types.
It seems like the user doesn't have permissions to read and write for a given folder. You can confirm by having them attempt creating folders or components in the same folder in the Content Manager Explorer (CME).

A: Is it possible that the Mac does not authenticate properly to Windows. In this case, you should be able to see the failed connections in your server logs. Is this user (or any other Mac user) able to use webdav successfully in any other folders?

A: As it's been suggested already, you will have to do some detective work to determine what exactly is failing. Tridion permissions do not change based on the client you use, so if they work from one client, they must work from another (excluding authentication issues here).

*

*Go to your Windows Event Viewer, Tridion Content Manager log, check for error messages written to it when you try to copy content from the mac.

*Post the exact error message you're getting. I doubt that Tridion is telling you "user is don't have read and write access"

Bottom line, if it works from Windows and not Mac, the issue is not with the WebDav server, but with the WebDav Client.
I also fail to see the programming question on this one...

A: What version of Tridion are you using? First action which you should do is to check Event Log for error messages (it was already suggested by Peter Kjaer), if you don't have anything there you can try to enable webdav debug logging by modifying cc_crtd_def.xml file which is situated in Tridion\webdav\WebDAVcartridges\Default\ folder. You should change loglevel property (as far as I remember it should be 4 for debug). And then there should be a log file created in the same folder or in webdav folder. You can try to find exact error message in this log file and post it here.


text:
Q: Inserting a Unique ID in Specific Row Locations for Multiple IDs I have a number of identical XML reports stored in excel.  In these reports, each item in one of the tables in each report a unique ID relating that item to a specific entity.  Each entity has multiple items associated with it.  Essentially, the structure of the macro I am looking for is as follows:
1) Excel searches for the ENTITY title tag in the XML report and stores the value contained between the end of the left tag (i.e. >) and the beginning of the right tag (i.e. <).
2) Excel searches for the ITEM title tag (the match must be exact).
3) Excel selects the row below the ITEM title tag and moves it down, and inserts the stored ENTITY value to the now empty cell above.
4) Excel continues to do this for all instances of the ITEM tag until it reaches another ENTITY title tag, at which point it loops.
I am thinking I would just need two loops, the ENTITY loop taking priority over the ITEM loop so that it is constantly looking for a new ENTITY.  Otherwise I have no idea how it will know to start looking for a new entity.
Any help would be appreciated, thanks!
EDIT:
For reference the XML looks like this:
<Results xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Reference>{REFERENCE-HERE}</Reference>
  <FillerTags>Filler</FillerTags>
  <entity>
    <entityName>ABC</entityName>
    <entityId>012345</entityId>
  </entity>
  <Items>
    <Item>
      <FillerTagsAgain>Filler2</FillerTagsAgain>
      <FillerTagsAgain>Filler2</FillerTagsAgain>
      <FillerTagsAgain>Filler2</FillerTagsAgain>
     </Item>
     <AnotherItem>
       <FillerTagsAgain>Filler2</FillerTagsAgain>
       <FillerTagsAgain>Filler2</FillerTagsAgain>
       <FillerTagsAgain>Filler2</FillerTagsAgain>
     </AnotherItem>
   </Items>

and would be modified to look like this:
<Results xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Reference>{REFERENCE-HERE}</Reference>
  <FillerTags>Filler</FillerTags>
  <entity>
    <entityName>ABC</entityName>
    <entityId>012345</entityId>
  </entity>
  <Items>
    <Item>
      <entityId>012345</entityId>
      <FillerTagsAgain>Filler2</FillerTagsAgain>
      <FillerTagsAgain>Filler2</FillerTagsAgain>
      <FillerTagsAgain>Filler2</FillerTagsAgain>
     </Item>
     <AnotherItem>
       <entityId>012345</entityId>
       <FillerTagsAgain>Filler2</FillerTagsAgain>
       <FillerTagsAgain>Filler2</FillerTagsAgain>
       <FillerTagsAgain>Filler2</FillerTagsAgain>
     </AnotherItem>
   </Items>
 <entity>
    .
    .
    .

I have tried to start by defining some variables and trying to set up a basic structure:
Dim entity As String
Dim item As String
Dim i As Long
Dim j As Long
Dim wb As Workbook
Dim LastEntity As Long
Dim LastItem As Long

LastEntity = Cells.CountIf(Range("A1:A438486")), "<Entity>")

With ActiveSheet
    For i = 1 To LastEntity
    Cells.Find(What:="ENTITY(i)", After:=ActiveCell, LookIn:=xlFormulas, _
               MatchCase:=False, SearchFormat:=False).Activate
        For j = 1 To LastItem

The first place I am stuck then is as follows:  How do I tell VBA to cycle through all the values that come up when using the 'Find' function.  For example, if  appears 50 times how do I tell VBA to start with the first entity, then begin the For j = 1 To LastItem loop?  Is the setup above anywhere close to correct?

A: Copy your XML in to a plain text file using Notepad/etc. Then save as an XML file making sure that file type is "All files ."

Then close that XML file.
The following example illustrates how to parse and modify the XML per your question.  I am not going to show you how to do this using Excel worksheets, that is frankly an objectively wrong way of manipulating XML data.
This code successfully modifies the XML from your initial state to the described example output.
Option Explicit
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub ParseResults()
'Requires reference to Microsoft XML, v6.0
'Requires referenc to Microsoft Scripting Runtime
Dim xmlFilePath$, newFilePath$
Dim DOM As MSXML2.DOMDocument
Dim entity As IXMLDOMNode
Dim fso As Scripting.FileSystemObject

'# Define the file you are going to load as XML
xmlFilePath = "C:\users\david_zemens\desktop\results.xml"

'# Define an output path for where to put the modified XML
newFilePath = "C:\users\david_zemens\desktop\updated_results.xml"

'# Create our DOM object
Set DOM = CreateObject("MSXML2.DOMDocument")

'# Load the XML file
DOM.Load xmlFilePath

'# Wait until the Document has loaded
Do
    Sleep 250
Loop Until DOM.ReadyState = 4

'# Get the entityID node
Set entity = DOM.DocumentElement.getElementsByTagName("entityId")(0)

'# Call a subroutine to append the entity to "Item" tags
AppendEntity DOM, "Item", entity
'# Call a subroutine to append the entity to "AnotherItem" tags
AppendEntity DOM, "AnotherItem", entity

'## Create an FSO to write the new file
Set fso = CreateObject("Scripting.FileSystemObject")

'## Attempt to write the new/modified XML to file
On Error Resume Next
fso.CreateTextFile(newFilePath, True, True).Write DOM.XML
If Err Then
    '## Print the new XML in the Immediate window
    Debug.Print DOM.XML
    MsgBox "Unable to write to " & newFilePath & " please review XML in the Immediate window in VBE.", vbInformation
    Err.Clear
End If
On Error GoTo 0

'Cleanup
Set DOM = Nothing
Set fso = Nothing
Set entity = Nothing

End Sub

Sub AppendEntity(DOM As Object, tagName As String, copyNode As Object)
'## This subroutine will append child node to ALL XML Nodes matching specific string tag.
Dim itemColl As IXMLDOMNodeList
Dim itm As IXMLDOMNode

'# Get a collection of all elements matching the tagName
Set itemColl = DOM.DocumentElement.getElementsByTagName(tagName)

'# Iterate over the collection, appending the copied node
For Each itm In itemColl
    If itm.HasChildNodes Then
        '# Insert this node before the first child node of Item
        itm.InsertBefore copyNode.CloneNode(True), itm.FirstChild
    Else
        '# Append this node to the Item
        itm.appendChild copyNode.CloneNode(True)
    End If
Next

Set itm = Nothing
Set itemColl = Nothing

End Sub

UPDATE
Added a busy/waiting loop to (hopefully) ensure that DOM has fully loaded the XML. On a larger file than the simple example, this may take a few seconds to load, and that could raise errors if you attempt to parse the XML before it's ready.


text:
Q: a write function throwing the exception of read access violation in visual studio c++ I tried writing to a file and I am unable to write to it due to "Access violation reading location 0x0000000F" I am able to isolate the problem here is the sample code:
void test_1() {
    std::fstream fio{ "xyz.dat",std::ios::in | std::ios::out | std::ios::binary | std::ios::app };
    if (!fio) {
        std::cerr << "sorry no file";
        return;
    }
    std::string s_test{ "xyz hii \n workf" };
    fio.write( ( char* )(s_test.length()), sizeof( size_t ) );  //the write causing issue
}

A: ( char* )(s_test.length()) is treating the length of the string as though it's a pointer and passing address 15 into write. Since there is no valid character at address 15, this triggers Undefined Behaviour, and the behaviour in this case is the program crashes.
This is always a problem when forced to use such a wide cast to force re-interpretation of a type. You can screw up horribly and all the compiler's defenses have been turned off. I don't have a good solution for this.
You need to pass in a legitimate address containing the length for write to operate on. To get this, you'll need to create a variable you can take the address of. &s_test.length(); isn't good enough here because you cannot take the address of a prvalue returned by a function.
auto len = s_test.length();
fio.write( reinterpret_cast<const char*>(&len), sizeof( len ) );

Note that writing a variable of automatically deduced type or a variable of a type that can change between compiler implementations is risky. It's hard to be sure how many bytes you're going to need to read at the other side.
uint32_t len = x.length();

Would be safer, and probably more compact, but at the risk of overflow with strings greater than 4.4 billion characters in length. That's a risk I'm willing to put up with.
Another concern is endian. It's not as common a problem as it used to be, but both the writer and reader need to agree on the byte order of the integer. htonl and ntohl can help mitigate this threat by guaranteeing a byte order.

A: Assuming that you are trying to write the length of the string to your output file, you can do it like this:
size_t len = s_test.length();
fio.write( ( const char * ) &len, sizeof( size_t ) );


text:
Q: Is there a way to squash a number of commits non-interactively? I'm trying to squash a range of commits - HEAD to HEAD~3.  Is there a quick way to do this, or do I need to use rebase --interactive?

A: Use the following command to squash the last 4 commits within the last commit:
git squash 4

With the alias:
squash = !"f() { NL=$1; GIT_EDITOR=\"sed -i '2,$NL s/pick/squash/;/# This is the 2nd commit message:/,$ {d}'\"; git rebase -i HEAD~$NL; }; f"
sq = !git squash $1
sqpsf = !git squash $1 && git psf

From https://github.com/brauliobo/gitconfig/blob/master/configs/.gitconfig

A: I personally like wilhelmtell's solution:
git reset --soft HEAD~3
git commit -m 'new commit message'

However, I made an alias with some error checking so that you can do this:
g.squash 3 'my commit message'

I recommend setting up aliases that actually run scripts so that it is easier to (a) code up your scripts and (b) do more complex work with error checking.   Below is a script that does the work of squashing. I put that in a scripts folder in my HOME path.
Script for squashing (squash.sh)
#!/bin/bash
#

#get number of commits to squash
squashCount=$1

#get the commit message
shift
commitMsg=$@

#regular expression to verify that squash number is an integer
regex='^[0-9]+$'

echo "---------------------------------"
echo "Will squash $squashCount commits"
echo "Commit message will be '$commitMsg'"

echo "...validating input"
if ! [[ $squashCount =~ $regex ]]
then
    echo "Squash count must be an integer."
elif [ -z "$commitMsg" ]
then
    echo "Invalid commit message.  Make sure string is not empty"
else
    echo "...input looks good"
    echo "...proceeding to squash"
    git reset --soft HEAD~$squashCount
    git commit -m "$commitMsg"
    echo "...done"
fi

echo
exit 0

Then to hook up that squash.sh script to an alias, I add the following to my .zprofile:
export PATH="$PATH:$HOME/scripts" # Add scripts folder to PATH
...
alias g.squash='function _gSquash(){ sh squash.sh $1 $2; };_gSquash'
...

Note: You can make your alias anything you want. I have my a lot of my git shortcuts as g.<myCommand>

A: To add to the answer by wilhelmtell I find it convenient to soft reset to HEAD~2 and then amending the commit of HEAD~3:
git reset --soft HEAD~2
git commit --all --amend --no-edit

This will merge all commits to the HEAD~3 commit and use its commit message. Be sure to start from a clean working tree.

A: Here is a one liner to squash the last 2 commits. In this example, the message of second last commit will be retained. You may change the message as you wish.
git commit -am "$(git log -1 --skip=1 --pretty=%B | xargs && git reset --soft HEAD~2)"

This command will be very useful if you create an alias for this command and use the alias instead.

A: Make sure your working tree is clean, then
git reset --soft HEAD~3
git commit -m 'new commit message'

A: I used:
EDITOR="sed -i '2,/^$/s/^pick\b/s/'" git rebase -i <ref>

Worked quite fine. Just don't try to have a commit log with a line that starts with "pick" :)

A: To squash everything since the branch was forked from master:
git reset --soft $(git merge-base --fork-point master) \
  && git commit --verbose --reedit-message=HEAD --reset-author

A: You can get pretty close with
git rebase --onto HEAD~4 HEAD~ master
This assumes you're on master with a linear history. It's not quite a squash because it discards the intermediate commits. You'd need to amend the new HEAD to modify the commit message.


text:
Q: Authentication Require Enter username and password to http://www I am getting window authentication window popup on some of my views in mvc4. It works fine when I host it on local server. But when I upload my code to my hosting server, all the views works fine except some views.
I am using form authentication in my application. And the views which given me such popups their controller class define with [Authorize] attribute. Is it an issue with IIS on hosted server or something else?
This is the popup message:

A: I suspect that you have Integrated Windows Authentication or Basic Authentication configured in IIS for your website or application (depending on how you are hosting it). Make sure you disable it and enable anonymous access to the website if you want to use Forms Authentication.

*

*Open IIS Manager and navigate to your website or application.

*In Features View, double-click Authentication.

*On the Authentication page, disable Windows authentication and enable Anonymous authentication.


text:
Q: Transferring information between a web server and a Python backend? I have been Googling my problem but haven't been able to come up with anything; here's the situation:

*

*I have a PHP / MySQL website hosted with 1and1.com.

*I also have a Python program that runs on a desktop computer I own.

*I want users to be able to submit files and modify personal information on the website and then have that information transferred to the Python program on my desktop computer (so the desktop will basically have a copy of data being stored in the MySQL database).

*I want to minimize the number of SQL queries, but I also want changes to be reflected in the desktop Python program within a minute or so.

I understand Python can query the MySQL database, but what is an efficient way to have it update its copy of the info stored on the MySQL database?
What I'm thinking is that I can have an "updates_to_db" table that records every change made to the main db, and then have the Python program use that to decide which files / db rows it needs to update.
Or is there a better way?

A: I'd suggest that you look up a Master-Slave mirroring between your offsite MySQL database and one that you can host locally(its not that hard to host one on your desktop).
Why?
Instead of asking python to ask your offsite database every now and then if there are new changes, why not have that database update itself in a local database that you own. That should minimize the number of queries running around and if your python program is going to do something with the data you're pulling, you can safely just query from your local database without worries of accidentally borking something or going over your monthly bandwidth allocation
You can checkout a guide of that here: https://www.digitalocean.com/community/tutorials/how-to-set-up-master-slave-replication-in-mysql
if you have more questions about master-slave database mirroring, you should checkout https://dba.stackexchange.com/


text:
Q: Left Anti join in Spark? I've defined two tables like this:
 val tableName = "table1"
    val tableName2 = "table2"

    val format = new SimpleDateFormat("yyyy-MM-dd")
      val data = List(
        List("mike", 26, true),
        List("susan", 26, false),
        List("john", 33, true)
      )
    val data2 = List(
        List("mike", "grade1", 45, "baseball", new java.sql.Date(format.parse("1957-12-10").getTime)),
        List("john", "grade2", 33, "soccer", new java.sql.Date(format.parse("1978-06-07").getTime)),
        List("john", "grade2", 32, "golf", new java.sql.Date(format.parse("1978-06-07").getTime)),
        List("mike", "grade2", 26, "basketball", new java.sql.Date(format.parse("1978-06-07").getTime)),
        List("lena", "grade2", 23, "baseball", new java.sql.Date(format.parse("1978-06-07").getTime))
      )

      val rdd = sparkContext.parallelize(data).map(Row.fromSeq(_))
      val rdd2 = sparkContext.parallelize(data2).map(Row.fromSeq(_))
      val schema = StructType(Array(
        StructField("name", StringType, true),
        StructField("age", IntegerType, true),
        StructField("isBoy", BooleanType, false)
      ))
    val schema2 = StructType(Array(
        StructField("name", StringType, true),
        StructField("grade", StringType, true),
        StructField("howold", IntegerType, true),
        StructField("hobby", StringType, true),
        StructField("birthday", DateType, false)
      ))

      val df = sqlContext.createDataFrame(rdd, schema)
      val df2 = sqlContext.createDataFrame(rdd2, schema2)
      df.createOrReplaceTempView(tableName)
      df2.createOrReplaceTempView(tableName2)

I'm trying to build query to return rows from table1 that doesn't have matching row in table2.
I've tried to do it using this query:
Select * from table1 LEFT JOIN table2 ON table1.name = table2.name AND table1.age = table2.howold AND table2.name IS NULL AND table2.howold IS NULL

but this just gives me all rows from table1:

List({"name":"john","age":33,"isBoy":true},
  {"name":"susan","age":26,"isBoy":false},
  {"name":"mike","age":26,"isBoy":true})

How to make this type of join in Spark efficiently?
I'm looking for an SQL query because I need to be able to specify columns which to compare between two tables, not just compare row by row like it is done in other recommended questions. Like using subtract, except etc.

A: You can do it with the built in function except
(I would have used the code you provided, but you didn't include the imports, so I couldn't just c/p it :( )
val a = sc.parallelize(Seq((1,"a",123),(2,"b",456))).toDF("col1","col2","col3")
val b= sc.parallelize(Seq((4,"a",432),(2,"t",431),(2,"b",456))).toDF("col1","col2","col3")

scala> a.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a| 123|
|   2|   b| 456|
+----+----+----+

scala> b.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   4|   a| 432|
|   2|   t| 431|
|   2|   b| 456|
+----+----+----+

scala> a.except(b).show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a| 123|
+----+----+----+

A: You can use the "left anti" join type - either with DataFrame API or with SQL (DataFrame API supports everything that SQL supports, including any join condition you need):
DataFrame API:
df.as("table1").join(
  df2.as("table2"),
  $"table1.name" === $"table2.name" && $"table1.age" === $"table2.howold",
  "leftanti"
)

SQL:
sqlContext.sql(
  """SELECT table1.* FROM table1
    | LEFT ANTI JOIN table2
    | ON table1.name = table2.name AND table1.age = table2.howold
  """.stripMargin)

NOTE: it's also worth noting that there's a shorter, more concise way of creating the sample data without specifying the schema separately, using tuples and the implicit toDF method, and then "fixing" the automatically-inferred schema where needed:
import spark.implicits._
val df = List(
  ("mike", 26, true),
  ("susan", 26, false),
  ("john", 33, true)
).toDF("name", "age", "isBoy")

val df2 = List(
  ("mike", "grade1", 45, "baseball", new java.sql.Date(format.parse("1957-12-10").getTime)),
  ("john", "grade2", 33, "soccer", new java.sql.Date(format.parse("1978-06-07").getTime)),
  ("john", "grade2", 32, "golf", new java.sql.Date(format.parse("1978-06-07").getTime)),
  ("mike", "grade2", 26, "basketball", new java.sql.Date(format.parse("1978-06-07").getTime)),
  ("lena", "grade2", 23, "baseball", new java.sql.Date(format.parse("1978-06-07").getTime))
).toDF("name", "grade", "howold", "hobby", "birthday").withColumn("birthday", $"birthday".cast(DateType))

A: you can use left anti.
dfRcc20.as("a").join(dfClientesDuplicados.as("b")
  ,col("a.eteerccdiid")===col("b.eteerccdiid")&&
    col("a.eteerccdinr")===col("b.eteerccdinr")
  ,"left_anti")

A: In SQL, you can simply your query to below (not sure if it works in SPARK)
Select * from table1 LEFT JOIN table2 ON table1.name = table2.name AND table1.age = table2.howold where table2.name IS NULL

This will return all rows of table1 for which join failed


text:
Q: iPhone App replace images I got a little problem. I use some images in my app. Today I wanted to replace them with new ones. But when I build and run the project I still get the old ones. I tried to touch the project and the new images but nothing seems to work. I deleted all references and files and imported the new images, but I still see just the old ones.
Does anyone know how to handle that?

A: Try this: Build -> Clean Targets (i think or something like this)

A: Try cleaning your target and doing a fresh build. Xcode is probably not updating the files in the target properly (I've seen it do that a lot with the Copy Files build phase).

A: Try deleting the app from the simulator or your iOS device and reinstall it.

A: First of all I have to get this question out of the way.... did you make sure that the cases match?
For the answer:
Simulator: clean all targets, clean, Reset the simulator and then try again
Device: clean all targets, clean, delete the app, reinstall


text:
Q: How to find and change color of specific word in string For example if I have
$data = "This is bold and this is italic";
// Guessing to read string with some inbuilt function and replace bold and italic keyword

I want to change the bold to bold and italic to italic in string.
Is this possible?

A: The data you return, assuming this isn't some form of ajax request, is going to be interpreted and rendered as HTML, so take advantage of that by including the tags in the output string.
 Example
$data = "this is bold and this is italic";

And this will render something like..
This is bold and this is italic.
 Extra Reading

*

*Here is a nice explanation of semantic elements in HTML5.

A: $data = str_replace(array('bold', 'italic'),
                    array('bold',
                          'italic'),
                    $data);

Instead of inline styles, you could instead specify classes like 'class="bold"` in the spans, and use CSS to assign the appropriate styles to those classes.


text:
Q: Import png image in android studio I'm trying to import a png image into android studio.
I'm following these steps: res->drawable->new image assets->action bar and tab icons, the problem is that android studio creates 4 images and the biggest of these is 96x96 (it's hard to see on the app) while the original image is 1000x1000, so my question is how can I import and display a 1000x1000 png image?


text:
Q: Ubuntu One stuck on "File Sync Starting" on Windows 8 When I first installed Ubuntu One on my computer it worked fine and synced everything. But after I rebooted it refused to sync anything and is stuck on "File Sync Starting". Can anyone point out how to fix this?

A: In my case it was Windows 7 Professional 64bit with all user profiles and ProgramData moved to D: drive (during Windows 7 installation).
I've checked the logs at:
D:\Users\Wojtek\AppData\Local\xdg\cache\ubuntuone\log
and found this:
exceptions.IOError: [Errno 2] No such file or directory: u'C:\\ProgramData\\ubuntuone-storageprotocol\\UbuntuOne-Go_Daddy_Class_2_CA.pem'

It was obvious that there is no C:\ProgramData\ubuntuone-storageprotocol on my C: drive because it was on D: :)
I've created symlink (with cmd.exe as administrator):
mklink /D C:\ProgramData\ubuntuone-storageprotocol D:\ProgramData\ubuntuone-storageprotocol

and restarted Ubuntu One - and it started to work!

A: We have not started testing Ubuntu One in windows 8 (since it's not released yet ;-). Could you file a bug in the launchpad bug tracker? Maybe we can figure out what's wrong.
Here's the URL to file a bug:
https://bugs.launchpad.net/ubuntuone-client/+filebug

A: I had the same problem on Vista HB. Checking the logs I read something similar to incorrect bytes on some windows shortcuts (.lnk files). I removed the mentioned shortcuts and restarted ubuntu one.
Problem seems to be resolved so far.
Hope this helps, I found my ubuntu one logs from the following location
C:\Users\<user>\AppData\Local\xdg\cache\ubuntuone\log

A: I also had this problem and checking the log at the above directory tree titled "syncdaemon-exceptions.log" I found a reference to a single .lnk file that was causing problems.  I deleted all .lnk files on both my Ubuntu 13.04 netbook (no problems) and my Windows 7 computer that was choking on the .lnk file, restarted UbuntuOne and it synced up immediately.
For me, these .lnk files are littered on my Ubuntu computer when I used MS Office in Wine.  Office seems to make an updated .lnk file every 5 or 10 minutes sometimes, appending with sequential numbering in parentheses, such as filename.docx (4).lnk.  Since I try to sync my netbook with my work computer (Windows 7) via UbuntuOne, they end up causing problems on my Windows computer.


text:
Q: Microsoft Access ODBC Connection Strings Limited to 255 Characters? Microsoft Access 2003 database (.mdb) containing a linked table which connects via ODBC to a backend Microsoft SQL Server 2008 table.
When I enter design view for the linked table, then view the Properties field, I can only see the first 255 characters (specific fields replaced with hyphens):
ODBC;Description=------------------------------------;DRIVER=SQL Server;SERVER=----;APP=--------------------------------;WSID=---------;DATABASE=------------------;StatsLog_On=Yes;StatsLogFile=--------------------------------------------------------------

When I print the DAO field using the VBA Immediate Window (table name ommitted: "print CurrentDb.TableDefs("-----------").Connect"), I see a prefix plus 254 characters (prefix "ODBC;Description=" plus 254 characters, plus, presumably, a one-byte null character):
ODBC;Description=------------------------------------;DRIVER=SQL Server;SERVER=----;APP=--------------------------------;WSID=---------;DATABASE=------------------;StatsLog_On=Yes;StatsLogFile=------------------------------------------------------------------;Trusted_Co

How do I view the entire text of the ODBC connection string?
We experience an issue where the SQL Server server logs show error "Login failed for user "{user}". Reason: Could not find a login matching the name provided. [CLIENT: {ip address}]"
I am attempting to confirm the full string "Trusted_Connection=Yes" is part of the stored string.

A: The problem turned out to be a 255 character Microsoft Access (2003/2010) limitation on the ODBC connection string.
I removed the ODBC references to StatsLog ant re-linked all the tables within the Microsoft Access database. It has been one week and the DBA team reports no further server log errors.

A: Update for Access 2016:
Max length of connect string for

*

*Linked tables: 513 chars

*Pass-through queries: 255 chars

(OP asked about Access 2003 but this question is the only one on this topic.)

A: Try Shift-F2. That's the keyboard shortcut throughout Access for the Zoom box, and it works in most properties as well.


text:
Q: Machine learning book with robust linear algebra approach I am looking for machine learning book - neural network, deep learning etc etc - that use linear algebra in a robust manner. I found satisfactory the old book of Simon Haykin : Neural Networks : A Comprehensive Foundation -1998.
Do you know if exist a text book recently released in the same trace?
Many thanks

A: What about the deep learning book?
It has an entire chapter 2 on the linear algebra although reading it now some concepts are beyond what I learned in an elementary course in university.
The Deep Learning Book is known as a fundamental resource for DL and I guess where DL overlaps with ML, ie. neural networks.


text:
Q: Obtain the result ByteArray of the current playing sounds I am developing an AIR application for desktop that simulate a drum set. Pressing the keyboard will result in a corresponding drum sound played in the application. I have placed music notes in the application so the user will try to play a particular song.
Now I want to record the whole performance and export it to a video file, say flv. I have already succeed in recording the video using this encoder:
http://www.zeropointnine.com/blog/updated-flv-encoder-alchem/
However, this encoder does not have the ability to record sound automatically. I need to find a way to get the sound in ByteArray at that particular frame, and pass it to the encoder. Each frame may have different Sound objects playing at the same time, so I need to get the bytes of the final sound.
I am aware that SoundMixer.computeSpectrum() can return the current sound in bytes. However, the ByteArray returned has a fixed length of 512, which does not fit in the requirement of the encoder. After a bit of testing, with a sample rate 44khz 8 bit stero, the encoder expects the audio byte data array to have a length of 5880. The data returned by SoundMixer.computeSpectrum() is much much shorter than the encoder required.
My application is running at 60FPS, and recording at 15FPS.
So my question is: Is there any way I can obtain the audio bytes in the current frame, which is mixed by more than one Sound objects, and has the data length enough for the encoder to work? If there is no API to do that, I will have to mix the audio and get the result bytes by myself, how can that be done?


text:
Q: struts2: blank page on OGNL error etc In case of problems on page I just get a blank page, no stacktraces in console etc.
Is there a way to fix this, or improve the diagnostics?

A: Have you tried setting devmode=true ?
Can you give us more details (struts2 version, jsp fragment, using sitemesh/tiles or not)?


text:
Q: MySQL replication automation? I was wondering if there are any MySQL replication automators or managers that can take over the tasks of deploying MySQL slaves from a master.
I come from an old school server management background, so I'm familiar with setting up MySQL replication manually. Recently I began working with AWS and was very impressed with how simple RDS made setting up replication slaves.
What I'd like to know is, are there any solutions that can automate the spinning off of slaves from a running master ala Amazon RDS?

A: How about Tungsten Replicator?

A: This command should get you 80% of the way there:
mysqldump $yourdb --master-data --single-transaction | mysql remotehost

As long as your master server has binlogs enabled and both servers have an id assigned in the config file, that should give you a pretty fast start to the day.

A: Well @Kevin, if you're looking for a tool then there's Tungsten replicator as already mentioned before me, and I would also maybe check out DBreplicator (I know there are some other DB replication tools available as well but I haven't had an "on-hands" experience).
Another option is to consider a hosted database solution with auto scaling; this will save you the need to deal with replication manually. I'm familiar with Xeround's http://xeround.com/">cloud database which is also available on EC2, their solution manages the replication to additional slaves as the load on the database grows.


text:
Q: Deduction of $\forall x(\neg p(x)\rightarrow q(x)), \forall z(p(z)\rightarrow r(z))\vdash \forall z(\neg r(z) \rightarrow\exists yq(y))$ I trying to study for my final exam and I can't figure out how to solve this:
$\forall x(\neg p(x)\rightarrow q(x)), \forall z(p(z)\rightarrow r(z))\vdash \forall z(\neg r(z) \rightarrow\exists yq(y))$
This is what I have so far:

*

*$\forall x(\neg p(x)\rightarrow q(x))$

*$\forall z(\neg p(z)\rightarrow r(z))$

*$p(x_0)\rightarrow q(x_0)$ (using 1 and UE($S^x_{x_0}$))

*$p(x_0)\rightarrow r(x_0)$ (using 2 and UE($S^z_{x_0}$))

*$\neg p(x_0)\rightarrow r(x_0)$ (using 3, 4 and Hypothetical syllogism)

*$r(x_0) \vee q(x_0)$ (using 5)

*$\neg r(x_0) \rightarrow q(x_0)$ (using 6)

*$\forall z(\neg r(z)\rightarrow q(z))$ (using Universal Introduction)

But I can't reach $\forall z(\neg r(z) \rightarrow\exists yq(y))$
I can't find any theorem that I can use to put the $\exists$ in the middle of the $\forall$.
Can anyone help me?
Thank you

A: Your proof attempts to use Hypothetical Syllogism immediately after the two Universal Eliminations.
Before you can do that, you will need to use Contraposition, to get two conditionals in the correct form:
$$\lnot r(c)\to \lnot p(c)~,~\lnot p(c)\to q(c)~\vdash~\lnot r(c)\to q(c)$$
So that just leaves you with the steps to derive the required conditional from that.
$$\def\fitch#1#2{\quad\begin{array}{|l} #1\\\hline #2\end{array}}
\fitch{~1.~\forall x~(\lnot p(x)\to q(x))\hspace{5.5ex}\text{Premise}\\~2.~\forall z~(p(z)\to r(z))\hspace{8ex}\text{Premise}}{\fitch{~3.~[~c~]\hspace{17.5ex}\text{Assumption}}{~4.~\lnot p(c)\to q(c)\hspace{8ex}\forall\text{E},1,3\\~5.~p(c)\to r(c)\hspace{9.5ex}\forall\text{E},2,3\\~6.~\lnot r(c)\to\lnot p(c)\hspace{6.5ex}\text{Contraposition},5\\~7.~\lnot r(c)\to q(c)\hspace{8ex}\text{Hypothetical Syllogism},6,4\\{\small\fitch{~8.~\ldots}{~9.~\ldots\\10.~\ldots}}\\11.~\lnot r(c)\to\exists y~q(y)\hspace{3.5ex}\to\!\text{I},8{-}10}\\12.~\forall z~(\lnot r(z)\to \exists y~q(y))\hspace{3ex}\forall\text{I},3{-}11}$$

A: Your attempt so far is very sloppy:

*

*(2) has a negation that shouldn't be there,

*(5) does not follow since the consequent in (3) is $q(x_0)$ and the antecedent in (4) is $p(x_0)$,

*(6) does not at all follow from (5).

I would take a lot more care with these proofs, both in not making mistakes such as above, and in annotating which rules you use (instead of just "using").

Here is a proof:
\begin{align}
1.&\quad \forall x(\lnot p(x)\to q(x))&&
\text{(assumption)}\\
2.&\quad \forall x(p(x)\to r(x))&&
\text{(assumption)}\\
3.&\quad \lnot p(t)\to q(t)  &&
\text{(universal elimination on 1.)}\\
4.&\quad p(t)\to r(t)  &&
\text{(universal elimination on 2.)}\\
5.&\quad \lnot q(t)\to \lnot\lnot p(t)  &&
\text{(contraposition on 3.)}\\
6.&\quad \lnot\lnot p(t)\to p(t)  &&
\text{(double negation elimination)}\\
7.&\quad \lnot q(t)\to p(t)  &&
\text{(hypothetical syllogism on 5. and 6.)}\\
8.&\quad \lnot q(t)\to r(t)  &&
\text{(hypothetical syllogism on 7. and 4.)}\\
9.&\quad \lnot r(t)\to \lnot\lnot q(t)  &&
\text{(contraposition on 8.)}\\
10.&\quad \lnot\lnot q(t)\to q(t)  &&
\text{(double negation elimination)}\\
11.&\quad \lnot r(t)\to q(t)  &&
\text{(hypothetical syllogism on 9. and 10.)}\\
12.&\quad q(t)\to \exists y\,q(y)  &&
\text{(existential introduction)}\\
13.&\quad \lnot r(t)\to \exists y\,q(y)  &&
\text{(hypothetical syllogism on 11. and 12.)}\\
14.&\quad \forall x(\lnot r(x)\to\exists y\,q(y))  &&
\text{(universal introduction on 13.)}\\
\end{align}
Note that in step $14.$ you need to ascertain that $t$ is not a free variable in any of the assumptions ($1.$ and $2.$) and $x$ is not free in formula $13.$
I doubt that "hypothetical syllogism" and "contraposition" are actual derivation rules you are allowed to use, but instead are shortcuts. Similarly I'm not sure if "double negation elimination" and "existential introduction" are axiom schemes that could be used.
To be completely correct, you will have to also show that these shortcuts / theorems can be derived using just the axioms and derivation rules native to your proof system (I don't know which specific system you work with, so I cannot give you a proof of those).


text:
Q: Build my own mvvm project from scratch? I have investigating about MVVM for less than a month. I have also tried a Mvvm framework (Mvvmlight from Laurent Bugnion. It's awesome).
But I am thinking about doing all these stuffs by myself, it means I want to build my project follow mvvm philosophy from scratch (don't use any mvvm framework available).
I want to make it as simple as possible but still have enough functionality and strictly follow mvvm philosophy. That's why I need your advices to help me recognize what I need & what I face & how much time it'll take me?
In almost Mvvm framework, I found they support something belows:

*

*Build a ViewModelBase: which should Implement for INotifyPropertyChanged, INotifyPropertyChanging  -> Support for Binding Properties

*RelayCommand (in Prism it is DelegateCommand): implement for ICommand

*Messenger class

Is it enough to make a Mvvm project?
I know that Mvvm is a model, so there are diverse ways to implement. But with a newbie like me. It's too difficult to know where I should start from.
I'm sorry for a long story but not clear question. Just I try to show my current situation and Ask for advices from you all.
Thanks for your reading & Happy upcoming new year!!!

A: For simple MVVM projects following are sufficient
1. RelayCommand  : For custom commands
2. Messenger (or EventAggregator or MessageBus) :For communication between view models
3. ViewModelBase :Base class for ViewModels. Can also be used as base class for Models (but for that separate base class)
For larger application, Layout support is also needed. This is provided by Prism Regions concept.
Other than that you are good to go.
I would however recommend to use existing MVVM framework. Have a look at this for commonly used MVVM frameworks. They are tried and tested framework (and free). It requires lots of testing effort to build SOLID framework.
I will not say building a framework is big effort, but whatever it is, it is totally unneccesary (until Business/Work environment is very strict and does not allow it).

A: I think that it it important (for first time at least) to implement MVVM design pattern by yourself without using any external MVVM frameworks. It will force you to see and to understand "underwater stones" and different approaches and solutions to solve then.


text:
Q: I am not able to send numeric values in sendkeys using selenium i am trying to send a numeric value to a textbox via selenium sendkey method ,which can not update the page.
driver.getElementByID('#numtext').sendKeys(123);

it gave some error can not send int values..How can i resolve this ..

A: Try to send value using executeScript method
driver.executeScript("document.getElementById('#numtext').setAttribute('value', 123)");

A: sendKeys takes a string that is entered to the text field. Try:
driver.getElementByID('#numtext').sendKeys('123');


text:
Q: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers I'm having trouble figuring out how to sort out the 2 biggest numbers and return them into the sum of squares procedure. I am struggling to write the code out in Scheme's syntax. I'm trying to write it as cleanly as possible, and I keep running circles in my head and on paper trying to do so. the book describes thinking "procedurally" and I think I'm having trouble with that aspect.
The book provides code for the sum-of-squares and square procedures. I would include my pseudo code but I'm severely lost. Here is the code the book provides:
(define (square x) (* x x))

(define (sum-of-squares x y)
  (+ (square x) (square y)))

How to define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers?

A:
How to define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers?

First you need a name for the procedure. Let's called it sum-of-squares-two-largest.
(define (sum-of-squares-two-largest x y z)
   ...)

It can make use of the sum-of-squares function, but it needs to find the two largest numbers out of x,y,z first.
One way to do this would be to get rid of the smallest number. You could define a helper procedure smallest? a b c that checks that a is the smallest of the 3 numbers by doing (and (<= a b) (<= a c)).
(define (sum-of-squares-two-largest x y z)
   (if (smallest? x y z)
       (sum-of-squares y z)
       (if (smallest? y x z)
           ...]

A: Write the code for min-of-three. Its negative (as in photography) is what you need:
(define (negative-min-of-three a b c)
   (if (<= a b)
       (if (<= a c)
           (..... b ... c .....)
           (..... a ... b .....))
       (if (<=
   ..........

You can complete the code, and rename it. The clock is ticking!

A: I created two methods to get the largest and the one in the middle for the time being.
(define (largest x y z)
  (cond ((and (> x y) (> x z)) x)
        ((and (> y x) (> y z)) y)
        (else z))
)

(define (mid x y z)
  (cond ((and (> x y) (< x z)) x)
        ((and (> y x) (< y z)) y)
        (else z))
)

(define (square a)
  (* a a)
)

(define (sum-of-two-largest x y z)
  (+ (square (largest x y z)) (square (mid x y z)))
)

(sum-of-two-largest -12 -4 1)

A: The hard part of this is, if you're reading SICP book, finding the 2nd largest number of the three. You can observe, if we let c < b < a, that:
a = max(a, b) gives the largest of the two numbers
b = max(c, b) gives the largest of the two smaller numbers

But how do we get the variable b on the second line. It can so happen that a is the smaller of the two? We can observe that:
b = min(a, b)

If we substitute min(a, b) for b in the max function on the third line, we get:
b = max(c, min(a, b))

This strategy is implemented in the following code, using only the constructs introduced in the book so far:
(define (square x) (* x x))

(define (max a b) (if (> a b) a b))

(define (min a b) (if (< a b) a b))

(define (sum-of-squares-two-largest a b c)
   (+ (square (max a b)) (square (max c (min a b)))))

(sum-of-squares-two-largest 1 2 3)
(sum-of-squares-two-largest 1 2 1)


text:
Q: Replace All Pipe Characters in a Div I am taking a fairly old site and making it responsive. The developer setup the "nav" like below, no list or anything. The mobile nav will be vertical and I don't want the "|" character. I want to do this without touching the nav HTML or adding a second menu to show on smaller screens.

  Home|
  About|
  Areas of Practice|
  In the News|
  Contact

I've tried this line of jQuery, but it seems to remove the  tags as well as the "|", leaving a string of "HomeAboutAreas of PracticeIn the NewsContact". How would I only remove the "|" and leave everything else as is?
$('#mainNav').text(function(index,text){
  return text.replace(/[|]/g,'');
});

A: Use .html instead of .text so you keep the HTML.
There's also no need to use [] in the regexp when you're just replacing one character. However, you need to escape the pipe character outside a character set, since it means alternation.

$("#doit").click(function() {
  $('#mainNav').html(function(index, text) {
    return text.replace(/\|/g, '');
  });
});

  Home|
  About|
  Areas of Practice|
  In the News|
  Contact

<button id="doit">Remove pipes</button>

A: Can do this with css alone by setting parent font-size to zero and setting the children font size to whatever your default is
#mainNav { font-size:0; }
#mainNav a { font-size:14px; }

DEMO
And for a javascript solution that doesn't replace the elements ( and possibly events bound to them) you can remove the text nodes using:
$('#mainNav').contents().filter(function(){
    return this.nodeType === 3;
}).remove();

DEMO 2

A: Put the 'pipe' characters in a separate  elemenet which you then hide using CSS media queries
HTML:
Areas of Practice |

CSS
@media (max-width: 320px) {
  .mainNav a span {
    display: none;
  }
}

Or you can just give a border-right:1px solid black to your a elements which you will then revert to 0px; using media queries - This completely ditches the | characters and uses plain CSS to achieve your intended result

#mainNav a{
  padding:2px;
  border-right:1px solid black;
}

@media (max-width: 600px) {
  #mainNav a{
    border-right:0px solid black;
  }
}

  Home
  About
  Areas of Practice
  In the News
  Contact</a

A: Demo: https://jsfiddle.net/erkaner/6mtafkek/1/
You can retrieve only the links and append them back to the div:
 var links = $('#mainNav a');

 $('#mainNav').html('').append(links );

 a{
     margin-right:5px;
 }

A: Try this:

$('#mainNav').html(function(index,text){
  return text.replace(/[|]/g,'');
});

  Home|
  About|
  Areas of Practice|
  In the News|
  Contact


text:
Q: I'm having issues with non-consecutive factor levels and their corresponding labels I'm trying to prepare my data and I've run into a problem with mutating factors. I've done this in the past with no problem but I think the non-consecutive nature of the levels may be the issue here. The RSex mutation works perfectly yet the second one, MarStat, brings up an error message:

Error: Problem with mutate() column MarStat.
i MarStat = factor(...).
x unused arguments (5, 8, 9)
Run rlang::last_error() to see where the error occurred.

I've also tried 1:5,8,9 which brings up a different error message:

Error: Problem with mutate() column MarStat.
i MarStat = factor(...).
x invalid 'labels'; length 7 should be 1 or 5
Run rlang::last_error() to see where the error occurred.

Here's the code:
bsasdata <- mutate(bsasdata,
               RSex = factor(RSex,
                             levels = 1:2,
                             labels = c("Male", "Female")),
               MarStat = factor(MarStat,
                                levels = 1,2,3,4,5,8,9,
                                labels = c("Married", "Living as married",
                                           "Separated or divorced after marrying", "Widowed",
                                           "Not married", "Don't know", "Refusal")))

Here's a snippet of the data


text:
Q: Twitter api not returning 'created_at' info for tweets When running the following code using the Python Tweepy library:
query = '$MSFT'
start_time = '2019-01-01T00:00:00Z'
end_time = '2019-02-01T00:00:00Z'
max_results = 10

results = client.search_all_tweets(query=query, max_results=max_results, start_time=start_time, end_time=end_time)

I receive a bunch of tweets. However, these tweets only contain the following data:
tweet.edit_history_tweet_ids
tweet.id
tweet.text

Information like 'created_at' or 'geo' are missing. Anyone have any idea what is going wrong here?

A: Adding tweet_fields parameter with specific field can see created_at but geo usually missed in tweet due to not added by tweeter.
It can't see most case even if passing geo
I can't test it due to no paid account but I can test recent 7 days result.
as attached code and results.
The search_recent_tweets() and  search_all_tweets() almost same parameters.
Here is documentation.

It is matched V2 low level API
in here
GET /2/tweets/search/all

import tweepy

bearer_token ="***** your bearer_token *****"

query = '\$MSFT'
start_time = '2019-01-01T00:00:00Z'
end_time = '2019-02-01T00:00:00Z'
max_results = 10

results = client.search_all_tweets(query=query,
    tweet_fields=['created_at','geo'],
    max_results=max_results,
    start_time=start_time,
    end_time=end_time)

for result in results.data:
    print(result.data)

import tweepy

bearer_token ="***** your bearer_token *****"

client = tweepy.Client(bearer_token=bearer_token)

query="\$MSFT"
results = client.search_recent_tweets(query=query,
            tweet_fields=['created_at','geo'],
            start_time='2023-01-12T00:03:00Z',
            max_results=10
            )

for result in results.data:
    print(result.data)

Result
>python search.py
{'created_at': '2023-01-16T01:27:49.000Z', 'text': '@excel_ranger $MSFT', 'edit_history_tweet_ids': ['1614796530795298817'], 'id': '1614796530795298817'}
{'created_at': '2023-01-16T01:27:26.000Z', 'text': 'Live day trading, detailed analysis on stocks with entry, exit, stop losses, price targets,mentoring and live news\n\nhttps://xxx/LzwYLosqbb\n\n$BIDU $SAVE $WORK $T $AAPL $C $MSFT $SPY $FB $CHWY $PTON $DIS $F $ADBE $CSCO $MGM $XOM $AMD $ZI $Z $BA $DOW $NET $PROP $OSTK  $QCOM $ADM https://xxx/n3T6xDyNNj', 'edit_history_tweet_ids': ['1614796435139993607'], 'id': '1614796435139993607'}
{'created_at': '2023-01-16T01:27:10.000Z', 'text': '$SPY $QQQ $DIS $TSLA $SHOP\n$AMD $AAPL $SQ $AMZN \n$EA $SEDG $MA $V $KO $PYPL $RCL $GOOG $NKLA $DKNG $HD $ROKU $NFLX $FB  $GILD $VXX $MSFT\n\nThanks to the discord group for the traders https://xxx/LzwYLosqbb https://xxx/V3pz7tESOk', 'edit_history_tweet_ids': ['1614796367511035904'], 'id': '1614796367511035904'}
{'created_at': '2023-01-16T01:26:56.000Z', 'text': 'RT @DarthDividend23: Great post by @thedividendclub on IG! \n\n$WMT $APD $JNJ $PG $WBA $GILD $O $MRK $UPS $AAPL $COST $SBUX $TGT $LOW $MSFT $…', 'edit_history_tweet_ids': ['1614796311076769794'], 'id': '1614796311076769794'}
{'created_at': '2023-01-16T01:26:52.000Z', 'text': 'RT @TrendSpider: Do the Markets need a Breather? \n\nPrepare for the week ahead \n\nTickers Covered:\n$SPY 00:00\n$QQQ 01:58\n$IWM 04:57\n$BTC 07…', 'edit_history_tweet_ids': ['1614796291812327428'], 'id': '1614796291812327428'}
{'created_at': '2023-01-16T01:26:46.000Z', 'text': 'Alerted an entry for $METX win of 121%. \nhttps://xxx/LzwYLosqbb\n✅Check us out\n\n\n\n$NAKD $TSLA $AAPL $NIO $SPY $INTC $GE $SNDL $NXTD $KGC $ZOM\n$FCEL\n$FEYE \n$ZM\n$AAL \n$PLTR \n$CCL \n$MSFT \n$PFE\n$PLUG \n$WFC \n$AMD \n$VXX \n$CNSP $QQQ https://xxx/OZFbKDpaHp', 'edit_history_tweet_ids': ['1614796270048010243'], 'id': '1614796270048010243'}
{'created_at': '2023-01-16T01:25:50.000Z', 'text': "STOCK, OPTIONS updates, alerts Free chatroom\nDon't forget to take a trial! \nhttps://xxx/LzwYLosqbb\n\n$SPY $BABA $DVAX $ACB $OSTK $TRIL $LK $CODX $SAVE $GSX $INO $KSS $PENN $NVAX $NIO $AAL $NKLA $MSFT $AAPL $AMZN $TSLA $CCL $BILI $CVNA $DAL $TWTR https://xxx/cT6Lc9Yhpv", 'edit_history_tweet_ids': ['1614796034487603200'], 'id': '1614796034487603200'}
{'created_at': '2023-01-16T01:25:36.000Z', 'text': '$MSFT at $220 feels like stealing candy from a baby.', 'edit_history_tweet_ids': ['1614795972751785985'], 'id': '1614795972751785985'}
{'created_at': '2023-01-16T01:25:16.000Z', 'text': '$DXY Index looks to test 101.60 as odds of less-hawkish Fed bets soar https://xxx/9PYMyxzvpt  $CRM $DXY $NIO $BABA $BTC.X $ETH.X $BLK $COIN $BNB.X $AAPL $TSLA $MULN $CEI $SPY $DJIA $QQQ $WMT $MSFT $PFE $MRNA $AZN $ABNB $AMD $BNTX $BA $COP $PDD $COST $GM $META $AMZN $NFLX', 'edit_history_tweet_ids': ['1614795889251422208'], 'id': '1614795889251422208'}
{'created_at': '2023-01-16T01:24:52.000Z', 'text': '$AAPL Trade idea\nhttps://xxx/LzwYLosqbb\n\n$AMC $SPY $GME $QQQ $MU $MSFT $AMD $PTON $AMZN $CRM $XLF $XLE $TSLA $AAL https://xxx/rDouPd3hNj', 'edit_history_tweet_ids': ['1614795790412648450'], 'id': '1614795790412648450'}


text:
Q: Wrong e-mail addresses in Outlook are hard to detect One of the most annoying features of standalone outlook is the fact that it is hiding the real e-mail addresses in messages.
So it will show
To:Joe Internet

instead of
To:Joe Internet <joe@internet.com>

This coupled with autocomplete and replying to all can lead to lost e-mails with very little possibility to trace them.
For example, if during certain mail exchange, I replied to Joe Internet  it is very hard later to examine exchange from the one side and determine what the problem was because the quoted To will contain only Joe Internet and will not show an error in the e-mail address (missing m).
So, are there any strategies to avoid the above design problem, in particular

*

*is there a way to force outlook validate messages against addressbook (without Exchange server, with LDAP directory and/or with outlook addressbook)

*is there a way to force outlook to show both display name and the raw e-mail address so that it will subsequently be coded
Of course, any other suggestions that would make the issue go away are very welcome.