text:
Q: XML via FTP and Memcache slowing my PHP site down all of a sudden....starting today I have the below PHP on my site.
$xml = $my_memcache->load('the_xml');
if(empty($xml)){
        $username = 'username';
        $password = 'password';
        $host = 'ftp.thirdpartysite.co.uk';
        $file = 'file.xml';
        $xml = file_get_contents("ftp://$username:$password@$host/$file");

        $my_memcache->save( $xml, 'the_xml' , array(), '1800' );

}
$php_array = $this->parseXml($xml);

$html = $this->gatherHtml($php_array);
return $html;

It looks up memcache for the key/value.
It if doesnt find the key it will do an FTP get contents and then save it to memcache for 5 minutes. I only want 1 user having to do this for all users every 5 mins.
Lastly it parses the XML into a php array using my 'parseXml()' function, then turns the PHP array into HTML using my 'gatherHtml()' and returns this.
It has been working for a long time but suddenly it has started making my site really slow. I have not changed the code for a long while. I have it load balanced over 2 servers and the outgoing bandwidth on my internal switch has also shot up.
I have checked the load and it is low also no DOS attack as average under max threads.
Any ideas please (FTP, memcache, PHP, XML) ?

A: hmmm
Well if its nothing on a DNS or Network layer it sounds like it could be something off the third party, in this instance the XML file.
If the XML has increased in size it's possible it is over the 1MB max size of a Memcache value now. Source here. I recommend checking now via an FTP client like Filezilla (or via command line).
If the file IS above 1MB the below could be happening.
Website slow:
If this is the case not only will every user not just not find the key in cache, but will also hammer Memcache to try and store it, every time it will fail as the file is too large and will have to wait for Memcache to timeout before completing the users page request.
Bandwidth high:
I notice you use Memcache, possibly have a node on each web server? If that is true then the data might be trying to write across both Memcache nodes possibly causing spikes in bandwidth on an internal switch.
To confirm this try using tcpdump to check if Memcache is the culprit of the high bandwidth.
#tcpdump -vvxXs 1500 -i bond0 'port 11211'

Substitute bond0 with whatever you call your NIC.
Possible solution:
Try parsing the XML first and THEN once you have what you need write/store that in Memcache. This should ensure that your always keeping under the 1MB value max size for Memcache.
$php_array = $my_memcache->load('the_php');
if(empty($php_array)){
        $username = 'username';
        $password = 'password';
        $host = 'ftp.thirdpartysite.co.uk';
        $file = 'file.xml';
        $xml = file_get_contents("ftp://$username:$password@$host/$file");

        $php_array = $this->parseXml($xml);

        $my_memcache->save( $php_array, 'the_php' , array(), '1800' );
}

$html = $this->gatherHtml($php_array);
return $html;

No idea if thats right but hope that helps


text:
Q: Hiding multiple dynamically-named subdirectories with mod_rewrite in .htaccess I am having difficulty configuring a mod_rewrite rule in my .htaccess file to hide certain subdirectories.
Input:
    https://example.com/hidden_sub1/hidden_sub2/additional_sub/file.php?lang=en-US
Desired output:
    https://example.com/en-US/additional_sub/file
I had code that allowed me to hide something if I specifically name it:
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^GET\ /hidden_sub1/hidden_sub2/ [NC]
RewriteRule ^hidden_sub1/hidden_sub2/(.*) /$1 [L,R=301]
RewriteRule !^hidden_sub1/hidden_sub2/ hidden_sub1/hidden_sub2%{REQUEST_URI} [L]

However, it stopped working once I added in the following language subdirectory code:
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*) $3?lang=$1 [L,QSA]

Besides, the name of the subdirectory is dynamic. "hidden_sub1" might be "random_name243". However, they would always be the first two subdirectories.
So how do I take out the first two randomly-named subdirectories while still keeping the language subdirectory?
I appreciate any help.

A: To change your url from the form

*

*https://example.com/hidden_sub1/hidden_sub2/additional_sub/file.php?lang=en-US
To the form :

*

*https://example.com/en-US/additional_sub/file
You can use the following Rewrite rule
RewriteEngine On
RewriteBase /
#1)externally redirect "/hidden_sub1/hidden_sub2/foo.php?lang=bar" to "/bar/foo"
RewriteCond %{THE_REQUEST} /hidden_sub1/hidden_sub2/([^.]+)\.php\?lang=(.+)\sHTTP [NC]
RewriteRule ^ /%2/%1? [L,R=301]
#2)internally rewrite "/bar/foo" to "/hidden_sub1/hidden_sub2/foo.php?lang=bar"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)/?$ /hidden_sub1/hidden_sub2/$2.php?lang=$1 [NC,L]

Tested on apache 2.2. and 2.4.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Toggle Button with borderless button style - how to get background in checked state? I am trying to get a standard Android ToggleButton to take on a somewhat custom style: in the unchecked state no border/background fill is displayed, in the checked state a background fill is displayed, when pressed (checked or unchecked) a ripple effect is displayed to transition from one state to another.
I've got things working, for the most part using this as my ToggleButton's background:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ripple" android:state_pressed="true"/>
    <item android:drawable="@drawable/checked_bg" android:state_checked="true"/>
    <item android:drawable="@android:color/transparent"/>

</selector>

ripple:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight" >

    <item
        android:id="@android:id/mask">
        <color
            android:color="@android:color/white" />
    </item>

</ripple>

checked_bg:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid
        android:color="?android:attr/colorControlHighlight" />

</shape>

However, when I go from the checked state to the unchecked state, the ripple applies a solid fill to the button that does not match the checked button state fill color, so it appears to "jump" from one color to the next immediately.  I believe this is because I am using colorControlHighlight for both the checked state background fill and the ripple color, so the ripple ends up at the color, and starts at another, slightly lighter color...
However, I can't simply change my checked state background fill to this lighter color, since that will make the case when I check/turn on the button look odd - it will start out at the lighter color, matching the checked background fill, and end up at a darker color, and then immediately jump to the lighter color again.
Is there a clean way to handle this? Or am I stuck with a jump in color change at one end?
Alternatively I could use two different ripples, one for the pressed = true and checked = false and the other for the pressed = true and checked = true case, right?


text:
Q: How to plot a combined bar and line plot in ggplot2 I have the following data which I am trying to plot as combined bar and line plot (with CI)
A data frame of Feature, Count, Odds Ratio and Confidence Interval values for OR

I am trying to get a plot as
A bar plot for count over lapped with a line plot for Odds Ratio with CI bars

I tried to plot in ggplot2 using following code:
ggplot(feat)+
  geom_bar(aes(x=Feat, y=Count),stat="identity", fill = "steelblue") +
  geom_line(aes(x=Feat, y=OR*max(feat$Count)),stat="identity", group = 1) +
  geom_point(aes(x=Feat, y=OR*max(feat$Count))) +
  geom_errorbar(aes(x=Feat, ymin=CI1, ymax=CI2), width=.1, colour="orange",
                position = position_dodge(0.05))

However, I am not getting the CI bars for the line graph, as can be seen in pic: Rather, I am getting them for barplot

Can someone can please help me out to sort this issue.
Thanks
Edit - Dput:
df <- structure(list(Feat = structure(1:8, .Label = c("A", "B", "C",
"D", "E", "F", "G", "H"), class = "factor"), Count = structure(c(2L,
8L, 7L, 5L, 4L, 1L, 6L, 3L), .Label = c("13", "145", "2", "25",
"26", "3", "37", "43"), class = "factor"), OR = structure(c(4L,
2L, 1L, 5L, 3L, 7L, 6L, 8L), .Label = c("0.38", "1.24", "1.33",
"1.51", "1.91", "2.08", "2.27", "3.58"), class = "factor"), CI1 = structure(c(7L,
4L, 1L, 6L, 3L, 5L, 2L, 2L), .Label = c("0.26", "0.43", "0.85",
"0.89", "1.2", "1.24", "1.25"), class = "factor"), CI2 = structure(c(3L,
2L, 1L, 6L, 4L, 7L, 8L, 5L), .Label = c("0.53", "1.7", "1.82",
"1.98", "13.07", "2.83", "3.92", "6.13"), class = "factor")), class = "data.frame", row.names = c(NA,
-8L))

A: Is this what you had in mind?
ratio <- max(feat$Count)/max(feat$CI2)
ggplot(feat) +
  geom_bar(aes(x=Feat, y=Count),stat="identity", fill = "steelblue") +
  geom_line(aes(x=Feat, y=OR*ratio),stat="identity", group = 1) +
  geom_point(aes(x=Feat, y=OR*ratio)) +
  geom_errorbar(aes(x=Feat, ymin=CI1*ratio, ymax=CI2*ratio), width=.1, colour="orange",
                position = position_dodge(0.05)) +
    scale_y_continuous("Count", sec.axis = sec_axis(~ . / ratio, name = "Odds Ratio"))

Edit: Just for fun with the legend too.
ggplot(feat) +
  geom_bar(aes(x=Feat, y=Count, fill = "Count"),stat="identity") + scale_fill_manual(values="steelblue") +
  geom_line(aes(x=Feat, y=OR*ratio, color = "Odds Ratio"),stat="identity", group = 1) + scale_color_manual(values="orange") +
  geom_point(aes(x=Feat, y=OR*ratio)) +
  geom_errorbar(aes(x=Feat, ymin=CI1*ratio, ymax=CI2*ratio), width=.1, colour="orange",
                position = position_dodge(0.05)) +
  scale_y_continuous("Count", sec.axis = sec_axis(~ . / ratio, name = "Odds Ratio")) +
  theme(legend.key=element_blank(), legend.title=element_blank(), legend.box="horizontal",legend.position = "bottom")

Since you asked about adding p values for comparisons in the comments, here is a way you can do that. Unfortunately, because you don't really want to add **all* the comparisons, there's a little bit of hard coding to do.
library(ggplot2)
library(ggsignif)
ggplot(feat,aes(x=Feat, y=Count)) +
  geom_bar(aes(fill = "Count"),stat="identity") + scale_fill_manual(values="steelblue") +
  geom_line(aes(x=Feat, y=OR*ratio, color = "Odds Ratio"),stat="identity", group = 1) + scale_color_manual(values="orange") +
  geom_point(aes(x=Feat, y=OR*ratio)) +
  geom_errorbar(aes(x=Feat, ymin=CI1*ratio, ymax=CI2*ratio), width=.1, colour="orange",
                position = position_dodge(0.05)) +
  scale_y_continuous("Count", sec.axis = sec_axis(~ . / ratio, name = "Odds Ratio")) +
  theme(legend.key=element_blank(), legend.title=element_blank(), legend.box="horizontal",legend.position = "bottom") +
  geom_signif(comparisons = list(c("A","H"),c("B","F"),c("D","E")),
              y_position = c(150,60,40),
              annotation = c("***","***","n.s."))


text:
Q: Meaning of "gives way"
It is at this point that I am woken by my own screaming. I switch on the light and try to control the desperate gasping for air which always seizes me after the dream. Around me stands the familiar furniture of our bedroom, and, over the bed itself, the family portraits, ikons in their high starched collars and braided coats, Hungarian Baroque and Beidermeier, my all-seeing, all-knowing ancestors. They alone are witness to the number of times I have raced down during the night to open the door to the rescuers and the ambulance; and they alone know how often I have stood there while the silence of the early-morning streets slowly gives way to the sounds of restlessly tossing trees and the cries of prowling cats that flood in through the open door, imagining what would happen if my struggle with the key proved in vain, and the lock failed to turn.

Dose "gives way to" mean: replaces with?
and the whole sentence in bold mean: while little by little the silence of the early morning repleces with sounds of tossing trees and the cries of cats?
Source:The Door
By
Magda Szabó

Translated Len Rix


text:
Q: Swift Test case Falling with Expectation I am trying to run test case for Failure response . I have an empty json file into project and named it FailureResponse . This file is empty . I trying to count the number of array is empty for example ..
XCTAssertTrue(schools.count==0)
It should pass the test because the json file is empty .
same result fields like school name and School location etc but the problem is it showing error ..
testFailure(): Asynchronous wait failed: Exceeded timeout of 6 seconds, with unfulfilled expectations: "waiting for response".
View Model code...
import Foundation
import Combine

class ViewModel {

    private let networkManager = NetworkManager()
    @Published private(set) var school = [School]()

    func getSchools() {
        loadMoreSchools()
    }

    func loadMoreSchools() {

        let newURL = NetworkURLs.baseURL

        networkManager
            .getModel([School].self, from: newURL) { [weak self] result in

                switch result {
                case .success(let schoolResponse):
                    self?.school = schoolResponse
                    print(schoolResponse)
                case .failure(let error):
                    print(error)
                }
            }
    }

    func getSchoolName(by row: Int) -> String {
        let schoolName = school[row]
        return schoolName.schoolName.uppercased()
    }

    func getSchoolLocation(by row: Int) -> String {
        return "\(school[row].location)"
    }

}

Here is my Mock service call ..
class MockService: NetworkManagerProtocol {

    var data: Data?

    func getModel<Model>(_ type: Model.Type, from url: String, completion: @escaping (Result<Model, Alomafire_Project.NetworkError>) -> ()) where Model : Decodable, Model : Encodable {

        if let data  = data {
            do  {
                let result = try JSONDecoder().decode(type, from: data)
                completion(.success(result))
            } catch (let error){
                print(error)

            }
        }
    }

}

Here is code for call the local Jason ..
func getData(json: String) throws -> Data {
        guard let url = Bundle(for: Alomafire_ProjectTests.self).url(forResource: json, withExtension: "json")
        else { return Data() }
        return try Data(contentsOf: url)
    }

Here is the test case ....
func testFailure() throws {

        // Given
        mockService.data = try getData(json: "FailureResponse")
        var schools: [School] = []
        let expectation = expectation(description: "waiting for response")

        // When
        viewModel?
            .$school
            .dropFirst()
            .sink(receiveValue: { result in
                schools = result
                expectation.fulfill()
            })
            .store(in: &subscribers)
       // viewModel?.getSchools()

        // Then
        waitForExpectations(timeout: 10.0)

        XCTAssertTrue(schools.count==0)

    }

Here is the debug result . it return 0 ..

Here is the screenshot of the result ..

A: You mention in the question that "the json file is empty." If that is the case, then this test will fail. The MockService assumes that the Data pulled from the json file will be decodable to the type requested. If it isn't the getModel(_:from:completion:) will never call the completion and the test will not complete in the specified time limit. Solve this by calling the completion closure even when the JSONDecoder response with an error.
Also, even if that mock emits the error properly, your ViewModel doesn't do anything with it that would cause the schools type to update.


text:
Q: Post thumbnail image not showing when share on facebook I am trying to develop this blog http://www.racecarwow.com . I have used youtube video thumbnail for post thumbnail .  In single post , there is a facebook share button. When i click on it, it is not showing the post thumbnail image.  it only show a fix image for all post thumbnail during share. I have used the following code for post thumbnil
 <a class="thumbnail" href="<?php the_permalink(); ?>">
    <img class="img-responsive"  src="http://img.youtube.com/vi/<?php echo $youtube_code; ?>/hqdefault.jpg" alt="<?php the_title()?>" />

Here $youtube_code is coming from custom field. I have also try this following way
 <a class="thumbnail" href="<?php the_permalink(); ?>">
    <?php if($post_img_src){?>
        <img src="<?php echo $post_img_src[0] ?>" alt="<?php the_title();?>" class="img-responsive">

    <?php } else{?>

    <img class="img-responsive"  src="http://img.youtube.com/vi/<?php echo $youtube_code; ?>/hqdefault.jpg" alt="<?php the_title()?>" />
   <?php }?>

And i have used the following code for share post
 <a class="btn btn-block btn-social btn-facebook" href="https://www.facebook.com/sharer.php?u=<?php echo urlencode(get_permalink($post->ID)); ?>&t=<?php echo urlencode($post->post_title); ?>"target="_blank">

   Share on facebook

Please tell me the solution.

A: You need to put your thumbnail image in a meta tag that Facebook can read for each post:
<meta property="og:image" content="http://img.youtube.com/vi/<?php echo $youtube_code; ?>/hqdefault.jpg" />

I think you have a plugin that has the Facebook meta tags, you might need to edit the plugin in order for your custom thumbnails to show with the other meta info.
You can debug your website on Facebook here https://developers.facebook.com/tools/debug


text:
Q: Python or R! - draw histograms for specified raster files I have two raster files (one with big cell size and second with much smaller.)
I have written a Python script which splits these files into pieces limited by bigger cells.
Now I want to draw a histogram for cell values and add value (for example as a line) from the bigger cell. Unfortunately I don't know how to do it in R (it may be useful, because I want to do this operation for many folders)
Could you help me?

A: Without more information, all I can tell you is to look into matplotlib, specifically the hist() function.
http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist

A: In R, it's much the same as in Python:
hist(data)

There is a useful introduction to the raster package in the vignette:
http://cran.r-project.org/web/packages/raster/vignettes/Raster.pdf


text:
Q: Linker error using boost::gregorian::from_string() I used boost for visual studio 2005 with version 1.48.
I am receiving a linker error while attempting to use boost::gregorian::from_string().
#include <string>
#define BOOST_DATE_TIME_SOURCE
#include <boost/date_time/gregorian/gregorian.hpp>
using namespace boost::gregorian;
using namespace std;

void testDate(){
string s("2000-01-10");
date d2 = from_string(s);

}

int main()
{
testDate();
return 0;

}

and get the linker error:
error LNK2019: unresolved external symbol "public: static class boost::shared_ptr<class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,unsigned short,struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,unsigned short> > > > __cdecl boost::gregorian::greg_month::get_month_map_ptr(void)" (?get_month_map_ptr@greg_month@gregorian@boost@@SA?AV?$shared_ptr@V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@GU?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@G@std@@@2@@std@@@3@XZ) referenced in function "unsigned short __cdecl boost::date_time::month_str_to_ushort<class boost::gregorian::greg_month>(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??$month_str_to_ushort@Vgreg_month@gregorian@boost@@@date_time@boost@@YAGABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)

Why?

A: Boost.DateTime is not a header-only library for you since you are using from_string; you need to compile it from source first and then link against it in your project.

A: The date time library

boost_date_time-vc140-mt.lib

was not in the lib folder. I have installed it with vcpakcgae manger and it worked.


text:
Q: Laravel 5 - Pre-Populate form using 'old' I have a form input for editing an existing entry in a Laravel 5 app like this..
<input name="obj_email" type="text" value="{{$myobject->obj_email}}">

This works correctly and when the form loads it pre-populates the value, but if some form validation fails, when the page reloads it loses the email that I entered.
I tried to fix it by doing this..
<input name="obj_email" type="text" value="{{old('obj_email')}}">

This works and it now does not lose the value when validation fails But it does not pre-populate the form on initial load anymore.
Where am I going wrong?

A: You can pass a second parameter to the old() helper to supply a default value. So you can do something like:
<input name="obj_email" type="text" value="{{old('obj_email',$myobject->obj_email)}}">

So if the "old" value is available it will use that, otherwise it will use the default that you supply for the first time the form is loaded.
Here is the doc reference:
https://laravel.com/docs/5.7/helpers#method-old

A: You're doing nothing wrong, but old() will be null initially since there's reallly no "old" data. Try something like this:
<input name="obj_email" type="text" value="{{ old('obj_email')?: $myOjbect->obj_email }}">

A: This is the logic you need to implement.
If there is an old('value') put that value, else put $object->value.
this is how the code may look like
<input name="obj_email" type="text"
    value="old('obj_email') ? old('obj_email') : $myObject->my_email">


text:
Q: height=100% do not work the code below are all height=100%, it works fine in chrome but it displayes very strange in firefox and ie7!it is not exactly the 100% height.anyone knows? thanks a million.
<iframe src ="demoFramesetLeftFrame.jsp" name="treeframe" id="treeframe"
        width=200px height=100% frameborder=0>
</iframe>
 <iframe src="middle.html" name="middle" id="middle"
        width=200px height=100% frameborder=0>
</iframe>
<iframe src="test.html" name="basefrm" id="basefrm"
        width=200px height=100% frameborder=0>
</iframe>

A: You may need a container div, with a min-height property.  Writing 100% height in HTML for some reason is one of the hardest things to do.
Here are some tutorials on how 100% height can be achieved
http://www.dave-woods.co.uk/?p=144
http://www.webmasterworld.com/forum83/200.htm


text:
Q: Pandas not loading in JupyterLab Been working on a data science project for a few weeks in JupyterLab using Python 3 and Pandas w/o any issues. Today I can't load pandas via the standard import pandas as pd . (see error message below)
I've tried checking to make sure pandas is installed in my Anaconda environment. After sourcing my Anaconda environment I've run both pip list and conda list and both show pandas 0.25.0 as installed in the packages list for the Anaconda environment.
Wondering if this might be related to a recent update of JupyterLab to version 1.0.2 and update of Jupyter Notebook to version 6.0.0?
I expect import pandas as pd to work fine but instead I get:
    ---------------------------------------------------------------------------
    UnboundLocalError                         Traceback (most recent call last)
    <ipython-input-2-7dd3504c366f> in <module>
    ----> 1 import pandas as pd

    ~/anaconda3/lib/python3.7/site-packages/pandas/__init__.py in <module>
         40 import pandas.core.config_init
         41
    ---> 42 from pandas.core.api import *
         43 from pandas.core.sparse.api import *
         44 from pandas.tseries.api import *

    ~/anaconda3/lib/python3.7/site-packages/pandas/core/api.py in <module>
         24 )
         25 from pandas.core.arrays import Categorical, array
    ---> 26 from pandas.core.groupby import Grouper
         27 from pandas.io.formats.format import set_eng_float_format
         28 from pandas.core.index import (Index, CategoricalIndex, Int64Index,

    ~/anaconda3/lib/python3.7/site-packages/pandas/core/groupby/__init__.py in <module>
          1 from pandas.core.groupby.groupby import GroupBy  # noqa: F401
    ----> 2 from pandas.core.groupby.generic import (  # noqa: F401
          3     SeriesGroupBy, DataFrameGroupBy, PanelGroupBy)
          4 from pandas.core.groupby.grouper import Grouper  # noqa: F401

    ~/anaconda3/lib/python3.7/site-packages/pandas/core/groupby/generic.py in <module>
         40 import pandas.core.indexes.base as ibase
         41 from pandas.core.internals import BlockManager, make_block
    ---> 42 from pandas.core.panel import Panel
         43 from pandas.core.series import Series
         44

    ~/anaconda3/lib/python3.7/site-packages/pandas/core/panel.py in <module>
       1584                   docs={})
       1585
    -> 1586 ops.add_special_arithmetic_methods(Panel)
       1587 ops.add_flex_arithmetic_methods(Panel)
       1588 Panel._add_numeric_operations()

    ~/anaconda3/lib/python3.7/site-packages/pandas/core/ops/__init__.py in add_special_arithmetic_methods(cls)
        810         special methods will be defined and pinned to this class
        811     """
    --> 812     _, _, arith_method, comp_method, bool_method = _get_method_wrappers(cls)
        813     new_methods = _create_methods(
        814         cls, arith_method, comp_method, bool_method, special=True

    ~/anaconda3/lib/python3.7/site-packages/pandas/core/ops/__init__.py in _get_method_wrappers(cls)
        717         comp_special = _comp_method_FRAME
        718         bool_special = _arith_method_FRAME
    --> 719     return arith_flex, comp_flex, arith_special, comp_special, bool_special
        720
        721

    UnboundLocalError: local variable 'arith_flex' referenced before assignment

Thanks for any help or suggestions.

A: Ultimately I solved this dependency issue by uninstalling and reinstalling Anaconda using this guide. This was in part aligned with @Trenton_M 's suggestion/info above as the reinstall rolled Pandas back from version 0.25.0 to version 0.24.2 while keeping JupyterLab version 1.0.2 and Jupyter Notebook version 6.0.0.
pandas.__version__

output
'0.24.2'

which is the default version listed for Anaconda.


text:
Q: How can I grab a teammate's attention? In 2vs2 game, you often need assistance from teammates such as: asking for minerals, asking for scans, asking for help, etc... When everything is more or less ok, you can just Alt+click on the minimap to take attention or write a text.
However, when a lot of events are going on, your teammate can often miss these indicators.
How can you best grab their attention in absence of a microphone?

A: Pausing is not the best solution, as the other team can unpause the game if they feel so inclined (and often they do).
If you are playing 2v2 (or any team composition) without voice (either in-game voice, or a solution like ventrilo), the game is definitely more difficult.  If you are friends with the person, it helps to establish a concrete opening strategy before the game, and then use small messages while you are macroing and once you see scouting information to decide how to progress into the mid and late games.
If you are doing team games with randoms, it helps to start trying to establish this as soon as the game gets started while you are still creating your first drones.  You'll know right away if you are in it alone, or if you have a very cooperative partner based on how they respond.
Also, give control of your units!  I can't tell you how helpful this is so that both of you can micro at the same time, or help the other player micro when you can't get off something to type to them quick enough.

A: As already stated in many situations it will suffice to ping (Alt+G click) the minimap.
Depending on how good your ally is and how often you have played with him I think the following is a good guideline:

*

*ping once - Look here, I want you to see this.

*rapidly multiple pings - Immediate threat, react fast!

*chat "scan", ping once - I want you to scan here.

*chat "100 min" or "100 gas" - Need 100 minerals or 100 gas.

*chat "gg?" - I have nothing, do you have anything that can change the game?

*chat "i go ..." - I will use ... strategy.

*chat "can i fast expand?" - I want to use the natural, can you cover me?

*chat "scout" - Send a scouting worker, I need my resources.

*chat "push" or "push?" or "push in x" - Asking when to push or indicating you want to push now or soon.

*chat "b" or "back" - You will not commit to this fight and want your ally to back off.

There are many other messages, but these are the ones I use most often.
You should rely on common sense and trust your ally. Assume that if you show him something he will react correctly.

A: After writing the question I've found a possible solution: you just need to "Pause" and write what you need. :)
P.S. Please note, I don't mean to CHAT a lot with teammate during pause... just get his attention for a second... Definitely it is not polite to others to pause game for OWN purposes... but 1 second break should be acceptable from my perspective.


text:
Q: How to redefine a variable on content page's codebehind that was declared on master page? I am building a web application using VS2010 and ASP.NET 4
I have managed to declare and define a variable in a nested master page and call it within the master page. However, how do I change the value of that variable from a content page's codebehind?
Here are the variable declarations from DeckNav.master.cs (nested master page codebehind):
public partial class DeckNav : System.Web.UI.MasterPage
{

    protected void Page_Load(object sender, EventArgs e)
    {
        this.mfrName = "(BRAND)";
        this.modelName = "(MODEL)";
    }

    public string mfrName { get; set; }
    public string modelName { get; set; }
}

This is how I call the 2 variables (default values) in master page (DeckNav.master):
<asp:ContentPlaceHolder ID="brandAndModel" runat="server">
<h1 class="page-header"> <%= mfrName %> <%= modelName %>
</h1>
</asp:ContentPlaceHolder>

In the content page inherited from DeckNav.master, I need to know how to change the values of the variables accordingly for each ASPX content page from the codebehind.
Example:
public partial class DeckRepair : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        mfrName = "Brand 10";
        modelName = "Model 12";
    }

}

The snippet above does not work. Visual Studio alerts me that "The name  does not exist in the current context".

EDIT:
I declared the variables as static on the master page's codebehind to:
public partial class LeftNav : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public static string camMfr { get; set; }
    public static string camModel { get; set; }
}

... and assigned values on the content page's codebehind:
public partial class BrandModel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LeftNav.camMfr = "BRAND 11";
        LeftNav.camModel = "MODEL 11";
    }
}

I'm still having the same problem. It successfully assigns the variable the first time to "BRAND 11", but when I load another content page with its own unique values for camMfr and camModel (i.e. "BRAND 22" , "MODEL 22") it retains the original assigned value ("BRAND 11"). Keep in mind I am NOT assigning a value in the master page, only declaring it.

A: Try
DeckNav.mfrName = "Brand 10";
DeckNav.modelName = "Model 12";


text:
Q: Forcefully setting a field as untouched in angular In angular js i have a select box which has touched validation defined so it comes red color on wrong selection.
Using this form in a modal. SO once reload the modal with this form that field is  still in red color. How can I forcefully set untouched.

A: Please find this example below,check whether this is useful :

.directive('untouch', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, modelCtrl) {
            element.on('focus', function() {
                modelCtrl.$setUntouched();
                scope.$apply();
            });
        }
    };
});


text:
Q: Как удалить все элементы, идущие после максимального элемента? Необходимо осуществить поиск максимального элемента и затем удалить
все элементы идущие после максимального в двумерном массиве 3x3.
Мой код максимальный элемент находит, но я не знаю как удалить элементы после него:
matrix = [
    [3, 7, 5],
    [9, 8, 1],
    [6, 2, 4]
]

mx = matrix[0][0]

for row in matrix:
    mx_ = max(row)
    if mx_ > mx:
        mx = mx_

Что должно получиться в итоге:
matrix = [
    [3, 7, 5],
    [9, 0, 0],
    [0, 0, 0]
]

A: matrix = [
    [3, 7, 5],
    [9, 8, 1],
    [6, 2, 4]
]

row_with_max = max(matrix, key=lambda x: max(x))  # строка с максимальным значением
i_max = matrix.index(row_with_max)                # индекс строки
j_max = row_with_max.index(max(row_with_max))     # индекс столбца
flat_index = i_max*len(matrix)+j_max              # индекс в плоском списке

и "забейте нулями" все, что идет после:
for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        if flat_index < i*len(matrix)+j:
            matrix[i][j] = 0

теперь в matrix:
>>> matrix
[
    [3, 7, 5],
    [9, 0, 0],
    [0, 0, 0]
]

A: В комментариях написали уже алгоритм, в коде примерно так можно реализовать, но думаю найдутся и одно двух строчные варианты)
def get_max(matrix):
    max_in_matrix = 0
    for row in matrix:
        max_in_row = max(row)
        if max_in_matrix < max_in_row:
            max_in_matrix = max_in_row
    return max_in_matrix

def reset_next(matrix, max_el):
    next_null = False
    for row in matrix:
        for i in range(len(row)):
            if next_null:
                row[i] = 0
            elif row[i] == max_el:
                next_null = True
            continue
    return matrix

max_el = get_max(matrix)
matrix = reset_next(matrix=matrix, max_el=max_el)


text:
Q: C# WPF login into to a SQL Server database I have code here where it will check if the entered username and password are correct, my problem is that in my database I have a Username: "ADMIN" and Password: "ADMIN" but whenever I try to input "admin" for both username and password it still allows me to go to the main window which means my bool was true.
Here is my code:
public bool IsAccountValid(string userLogin, string userPassword)
{
     bool flag = false;
     try
     {
         accessToDatabase.OpeningDatabase();
         String query = "SELECT * FROM Users where Username=@Username AND Password=@Password";
         SqlCommand sqlCmd = accessToDatabase.Command(query);

         sqlCmd.CommandType = CommandType.Text;
         sqlCmd.Parameters.AddWithValue("@Username", userLogin);
         sqlCmd.Parameters.AddWithValue("@Password", userPassword);

         if (sqlCmd.ExecuteScalar() != null)
             flag = true;
         else
             flag = false;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         accessToDatabase.ClosingDataBase();
     }

     return flag; //returns false if query does not exists...
 }

A: You can use ExecuteReader on SqlCommand to read values- which you can compare against user provided values. User Name shouldn't be case sensitive though.
My response assumes that username is unique in your user table - which i believe is pretty much valid assumption.
Since you only need username and pwd, you might want to modify your select query to :
SELECT UserName, Password
FROM Users
WHERE Username = @Username AND Password = @Password

Probably your revised snippet in that case would be something like :
public bool IsAccountValid(string userLogin, string userPassword)
    {
        bool flag = false;

        try
        {
            accessToDatabase.OpeningDatabase();
            String query = "SELECT * FROM Users where Username=@Username AND Password=@Password";
            SqlCommand sqlCmd = accessToDatabase.Command(query);

            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.Parameters.AddWithValue("@Username", userLogin);
            sqlCmd.Parameters.AddWithValue("@Password", userPassword);

             var reader = sqlCmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            if(userPassword == reader[0].ToString())
                            {
                                flag = true;
                            }
                        }
                    }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            accessToDatabase.ClosingDataBase();
        }

    return flag; //returns false if query does not exists...
}

Other alternative would be modify your sql query itself to ensure it takes care of case sensitive match in where clause like here
In that case, you need not to make any changes to your ADO.NET code.

A: Better way would be to change query for case sensitive search:
String query = "SELECT * FROM Users where
Username=@Username COLLATE SQL_Latin1_General_CP1_CS_AS
AND Password=@Password COLLATE SQL_Latin1_General_CP1_CS_AS";

Another method is do binary casting:
String query = "SELECT * FROM Users
where CAST(Username as varbinary(100))=CAST(@Username as varbinary(100))
 AND CAST(Password as varbinary(100))=CAST(@Password as varbinary(100))";


text:
Q: OpenCobolIDE and DB2 - Connection I'm currently working on a small COBOL project and I'm using OpenCobolIDE.
I also downloaded DB2 Express and I'm able to use it by running the "Commande line processor"
Now my question is the follow one : How can I make a connection between OpenCobolIDE and DB2 ?
I saw that it was possible to use "esqlOC" but I didn't find a lot of documentation and I'm still lost at the moment.
Kind regards

A: I know that's it's against SO policy, but here is a link; http://db2twilight.blogspot.nl/2014/01/linuxdb2-running-cobol-with-inline-sql.html   The code isn't that long, but I found no disclaimer, so assumed copyright goes to the blogger, Dick Reitveld.  The post is a tutorial on linking DB2 to GnuCOBOL (was OpenCOBOL), and not how to inform the OpenCOBOLIDE how to do the build, but hopefully this fits in with your question.
The build rules are listed in a shell script on the same page.
Basically it comes down to, creating a COBOL source file with EXEC SQL statements, running them  through the DB2 preprocessor, then compiling the generated sources with cobc.
db2 connect to sample
db2 prep program.sqb bindfile target ANSI_COBOL
cobc program.cbl -static -Wall -L/path/to/db2libs/sqllib/lib64 -ldb2 -v -x -save-temps -O
db2 bind program.bnd
db2 connect reset

Where "program" is your filename, with .sqb inputs and will generate .cbl and .bnd, and the
-L/path/to/.../

is the full path to where your DB2 install has placed the DB2 support libraries.


text:
Q: How to preview pdf using active storage and poppler? I'm trying to display a preview of the uploaded pdf in my application but all I get so far is a broken image.
I have installed the poppler gem as suggested in the active storage presentation for preview.
Then i tried different ways but all are returning a broken image.
<%= link_to bank.rib, rails_blob_path(bank.rib, disposition: "preview") %>

or
<%= image_tag bank.rib %>

or
where 'rib' being the attached file (has_one) of the model BankAccount (here bank = BankAccount.find(id))
bank.rib.previewable? returns true.

A: Installing poppler, is just one of the steps you might need, here are some other things you should check:

*

*Rails might be requiring some additional gems installed:

You must have ImageMagick or GraphicsMagick installed

Add this to your Gemfile:
gem 'image_processing', '~> 1.2'

and install imagemagick:
brew install imagemagick

*Another possible issue is that your application cannot reach the /rails/active_storage path, so verify the path is mounted or you do not have a catch_all route that overwrites that path, in case you do, you can exclude rails path with the following:

get "*unmatched_route", constraints: -> (req) { !(req.fullpath =~ /^\/rails\/(active_storage|conductor|action_mailbox)\/.*/) }


text:
Q: Why is count_if giving me the total of texts I was testing the following code, and a bit perplexed as to why count_if is returning me the total of texts?
Match function that takes string of Text as argument and returns true is the Text size is 4
bool Match(string Text)
{
    if (Text.size() == 4)
        return true;
}

numMatchwes produces the total number of Text in a vector
int numMatches(vector<string>Texts, bool (*Match)(string Text))  // Texts is an array
{
    int count = 0;

    for (int i = 0; i < Texts.size(); i++)
    {
    if (Match(Texts[i]) == 1)

// checking every string in vector and returns true
        count++;
    }

    return count;
}

The main function
int main()
{
    vector<string> texts;

    texts.push_back("Bing");
    texts.push_back("Pony");
    texts.push_back("Mil");
    texts.push_back("Sillty");
    texts.push_back("Ballz");
    texts.push_back("Mars");

   cout << Match("Sind") << endl;

cout << "Matches are: " << numMatches(texts, Match) << endl;

    cout << endl;

    int num = count_if(texts.begin(), texts.end(), Match); // count_if is STL function

    cout << num << endl;
}

Now I'm confused as to why count_if is giving me the total of texts?

A: The function  Match has undefined behavior in case when the passed string does not have a length equal to 4.
Define it the following way
bool Match( const std::string &Text )
{
    return Text.size() == 4;
}

Correspondingly the function numMatches can be defined the following way
auto numMatches( const std::vector<std::string> &Texts, bool Match(const std::string & ) )
{
    std::vector<std::string>::size_type count = 0;

    for ( const auto &s : Texts )
    {
        if ( Match( s ) ) ++count;
    }

    return count;
}

Here is your updated program.
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

auto numMatches( const std::vector<std::string> &Texts, bool Match(const std::string & ) )
{
    std::vector<std::string>::size_type count = 0;

    for ( const auto &s : Texts )
    {
        if ( Match( s ) ) ++count;
    }

    return count;
}

bool Match( const std::string &Text )
{
    return Text.size() == 4;
}

int main()
{
    std::vector<std::string> texts;

    texts.push_back( "Bing" );
    texts.push_back( "Pony" );
    texts.push_back( "Mil" );
    texts.push_back( "Sillty" );
    texts.push_back( "Ballz" );
    texts.push_back( "Mars" );

    std::cout << std::boolalpha << Match( "Sind" ) << '\n';

    std::cout << "Matches are: " << numMatches( texts, Match ) << '\n';

    std::cout << '\n';

    auto num = std::count_if( std::begin( texts ), std::end( texts ), Match );

    std::cout << num << std::endl;

    return 0;
}

The program output is
true
Matches are: 3

3


text:
Q: Multiselect in ngForm using HTML I am trying to create a multiselect dropdown which is bound to a dynamic property that is getting data from JSON script using service. I was able to show the data in the dropdown easily but whenever I put multiple attribute inside the select tag, the dropdown just starts behaving abnormally and I also can't multiselect the data.
I tried using another ng-multiselect-dropdown package but it was also getting quite tricky. I would like to do it with simple HTML checkboxes and using ngModel. I am sending data to POST request so basically I am trying to send multiple values at the backend.
How can I make this work?

            <select id="teacherSubjects" #teacherSubjects=ngModel multiple="multiple" required class="validate form-control" name="teacherSubjects" [(ngModel)]="teacher.teacherSubjects"
                    (change)="onSelect($event.target.value)">
                <option style="display:none"></option>
                <option *ngFor="let x of subjects" [value]="x.code">{{x.name}}</option>
            </select>
            Subjects

            Untouched

                    Subject is required

            ok

A: Here is an example for html multiselect example for you.
Stackblitz iam made for you.
https://stackblitz.com/edit/angular-multi-select-example-itmvgc
Html File,
 <select id="teacherSubjects"  multiple="multiple" required class="validate form-control" name="teacherSubjects" [(ngModel)]="teacherSubjects"
  (change)="onSelect($event)">
    <option style="display:none"></option>
    <option *ngFor="let x of myOptions" [value]="x">{{x.name}}</option>
  </select>

or
 <select id="teacherSubjects"  multiple required class="validate form-control" name="teacherSubjects" [(ngModel)]="teacherSubjects"
      (change)="onSelect($event)">
        <option style="display:none"></option>
        <option *ngFor="let x of myOptions" [value]="x">{{x.name}}</option>
      </select>

Typescript File,
teacherSubjects:any;
myOptions = [
    { id: 1, name: 'Car brands', isLabel: true },
    { id: 2, name: 'Volvo', parentId: 1 },
    { id: 3, name: 'Honda', parentId: 1 },
    { id: 4, name: 'BMW', parentId: 1 },
    { id: 5, name: 'Colors', isLabel: true },
    { id: 6, name: 'Blue', parentId: 5 },
    { id: 7, name: 'Red', parentId: 5 },
    { id: 8, name: 'White', parentId: 5 }
];
onSelect(event){
    console.log("Value in 2",this.teacherSubjects);
}

Note:-
Iam created sample variable and use in select function.You can change your conveninent. And also iam get hole value of an object while using this line,
[value]="x"

you can access like your choice, like name, id etc.
[value]="x.name"
[value]="x.id"

like this,
Screenshot,

I hope its helpful for you.


text:
Q: How can I stop direct access of a folder with Apache using .htaccess? I have tried to use

deny from all

So it blocks the whole contains and can be access by the page also..

A: Just create a blank index.html file and upload it to each folder. It's easier and safer..

A: You can use the following code to deny access to the folder:
RedirectMatch 403 ^/folder/?$

just replace folder with name of the folder you want to deny access to.
To deny access to folder and files
You can use :
RedirectMatch 403 ^/folder/.+$

This will show forbidden error for the folder and files.

A:
  Deny from all

  Allow from all

This code is working under .htaccess to solve the above problem
Thanks guys for help...


text:
Q: Creating a JavaScript file which can trigger 2 clicks events to select the web part default view I have spent many hours to try to write a script which allow me to do the following :-

*

*Currently i have a Discussion Board list which contain many items. where inside my site home page i added a new App Part representing the Discussion Board list.

*Now i edit the app part setting and i select the "Subject" as the view.

*So the final result i got is as follow. where there are links named; Recent, What's hot, My discussions... and inside the list menu i got links named; unanswered question, answered questions and Featured, as follow:-

*Now i tried to find a way to set the default view for the app part to be "Featured" instead of "Recent".. but seems inside the app part setting we can not have these settings.

*Now i already know that inside the App part there is a view named "Featured Discussions", but this view will only show the discussion item title and created by, without showing the number of replies or the number of likes..so that why i need to use the "Featured" link inside the "Subject" app part view.

*so i tried this script to mimic clicking on the "..." link >> then clicking on the "Featured" link.

<script type="text/javascript">
var timer1
$(document).ready(function(){
      if($("#MSOZoneCell_WebPartWPQ2").find("a:contains('Featured')").length==0)
      {
        ($("#MSOZoneCell_WebPartWPQ2").find("img.ms-ellipsis-icon")).trigger('click');
        time1= setTimeout(test,1000);
      }

  });

 function test()
 {
   $("a:contains('Featured')").trigger('click');
 }
  clearTimeout(timer1);
</script>

At first i thought the script worked well. but seems with some extra testing it did not, as currently i am facing these issues:-

*

*on google chrome, Firefox and safari the script will work well. where when i first visit the page the list menu will open and the "Featured" view will be selected automatically. but when i open many tabs and refresh them all (where the response time will increase), then on some tabs i have noted that either the list menu is shown without selecting the "Featured" link (as shown in the above picture). and on other tabs the app part will be rendered as white area!!.

*now on IE (currently i am using IE 11), the situation was as follow:-

*

*If i do a hard refresh for the page (CTRL + F5), the list menu menu will be shown, but the "Featured" link will not get clicked.

*If i access the page without doing a hard refresh (CTRL + F5) the script will not have any effect... even the list menu will not get shown.

Now I think that the issue i am facing is that the script will be accessing some components/markups that have not been rendered yet. due to performance delay or due to having 2 .trigger('click'); where one is depending on the other... so i am not sure if i can modify my script to work on a more robust way? and to eliminate the browser differences and performance issues which are breaking the script...
Edit
now based on @Aveenav reply, i added the following script inside a script editor web part:-
<script  type="text/javascript">
(function () {
    // String overrides
    function DiscussionListViewStringOverride() {

    SP.UI.Discussions.SortFilterItem.onPivotControlMenuOptionClick("SortItem4");
    }

    DiscussionListViewStringOverride();
    ExecuteOrDelayUntilScriptLoaded(DiscussionListViewStringOverride, "strings.js");

})();
</script>

but this did not have any effect and still the Recent link will be selected. also i should mention that inside the page i have added 2 app parts for the Discussion Board list. now i need the first app part to have the "Featured" as the default , while for the other app part to keep the "Recent" as the defualt..
Thanks

A: Take a look at sp.ui.discussions.debug.js
Here's one way to trigger Featured link. You may have to use ExecuteOrDelayUntilScriptLoaded or some sort of setTimeOut delay.
$(doucument).ready(function() {
   // SortItem4 is for Featured
   setTimeout(function(){ SP.UI.Discussions.SortFilterItem.onPivotControlMenuOptionClick('SortItem4'); }, 500);
};

A: I think "window.onload" method should do the trick. This should be affected only for the first app part on the page and it should show up Featured items by default while second app part should keep Recent as default. Please give it a try.
<script type="text/javascript">

window.onload = function() {
    SP.UI.Discussions.SortFilterItem.onPivotControlMenuOptionClick('SortItem4');
};

</script>


text:
Q: Is there any difference, performance wise, with these two queries? (Repeating the where clause inside the sub-query) MYSQL I have a query that goes something like this.
Select *
FROM FaultCode FC
JOIN (
    SELECT INNER_E.* FROM Equipment INNER_E

) E USING(EquipmentID)
LEFT JOIN AssetType AT ON AT.id_asset_type = E.id_asset_type AND AT.id_language = 'en-us'
LEFT JOIN Project P ON E.current_id_project = P.id_project
WHERE E.id_organization = 100057 AND E.equipment_status = 'ACTIVE'
    AND FC.code_status = 'OPEN'

As you can see, in the outside query, there is a where clause in the outside main query.
But also, on the inside, we have an Inner Join statement with the line SELECT INNER_E.* FROM Equipment INNER_E. This inner join makes us only retrieve the fault codes that are inside the equipment table (correct me if I'm wrong).
I am trying to optimize this query.
My question is, does it make any difference to do this
Select *
FROM FaultCode FC
JOIN (
    SELECT INNER_E.* FROM Equipment INNER_E
    WHERE INNER_E.id_organization = 100057 AND INNER_E.equipment_status = 'ACTIVE'

) E USING(EquipmentID)
LEFT JOIN AssetType AT ON AT.id_asset_type = E.id_asset_type AND AT.id_language = 'en-us'
LEFT JOIN Project P ON E.current_id_project = P.id_project
WHERE E.id_organization = 100057 AND E.equipment_status = 'ACTIVE'
    AND FC.code_status = 'OPEN'

So repeating the where clause inside the inner sub query, to further limit it before it joins. Or does the optimizer know to do this automatically?
I tried implementing that line in code, and it seemed to only make my query slower strangely enough. Is there any way I can optimize that query above, or since it's pretty simple, is that the best it's going to get without indexes?
I tried running the Explain Select statement, but I have a hard time parsing what it's telling me. Are there any good resources I can look into to learn some tips or techniques to optimize my query?
I don't have any aggregate functions in my Select fields. So is the only real answer Indexes?

A: Why is the first subquery needed?  Perhaps simply
Select  *
    FROM  FaultCode FC
    JOIN  Equipment AS E  USING(EquipmentID)
    LEFT JOIN  AssetType AT  ON AT.id_asset_type = E.id_asset_type
      AND  AT.id_language = 'en-us'
    LEFT JOIN  Project P  ON E.current_id_project = P.id_project
    WHERE  E.id_organization = 100057
      AND  E.equipment_status = 'ACTIVE'
      AND  FC.code_status = 'OPEN';

Likely Indexes:
FC:  INDEX(code_status, EquipmentID)
E:  INDEX(id_organization, equipment_status, EquipmentID,)

Probably unwise to do SELECT * -- It will give you all the columns of all 4 tables.  (Without further details, I cannot suggest any "covering" indexes, which seems likely for AT.)
With my version of the query, your question about repeating the WHERE vanishes.  With your version, it is likely to help.  I don't think the Optimizer is smart enough to catch on to what you are doing.
Show us the EXPLAINs.  We can help some with what the cryptic stuff is saying.  (And what it is not saying.)
"the best it's going to get without indexes" -- Are you saying you have no indexes??!  Not even a PRIMARY KEY for each table?  "So is the only real answer Indexes?"  Every time you write a query against a non-tiny table, you should ask "do the table(s) have adequate indexes for this query?"


text:
Q: Chaining Queueable Apex with Callouts Run Into Loop I have a queueable class that is triggered from a trigger that makes a callout. I wanted to use Queueable for scenarios where I need to insert 3-5k of records and eventually make 3-5k callouts. But the queueable goes into a loop even when I insert only 5 records and  it takes so long to abort the job once it's started. any help is appreciated
trigger LeadTrigger on Lead (before insert, before update) {
    List<Id> userIds =  new List<Id>();
    for (Lead objLead : Trigger.new) {
        if(!System.isFuture() || !System.isQueueable()){
            userIds.add(objLead.Id);
            }
        }
        if (userIds != null && (!System.isFuture() || !System.isQueueable())) {
            System.enqueueJob(new KeyApiQueueable (userIds));
        }
    }

Queueable
public with sharing class KeyApiQueueable implements Queueable, Database.AllowsCallouts {
    public List<Id> recordIds;

    public KeyApiQueueable (list<id> ids){
        this.recordIds = ids;
    }

    public void execute(QueueableContext context) {
        Lead[] leadsToUpdate = new lead[0];
        while(recordIds.size() > 0 && leadsToUpdate.size() < 100) { // Max 100 callouts allowed here
            Id nextId = recordIds.remove(0);
            leadsToUpdate.add(processPayload(nextId));
        }
        update leadsToUpdate;

        if(recordIds.size() > 0) {
            System.enqueueJob(this);
        }
    }

    public static Lead processPayload(Id recordId){
        List<Lead> leadAccount = [SELECT Id, deger1__c, deger2__c FROM Lead WHERE Id =: recordId];
        Lead leadAccounts = leadAccount[0];
        Integer Value2;
        Integer Value3;

        HttpRequest request= new HttpRequest();
        request.setMethod('GET');
        request.setEndPoint('https://api.spoonacular.com/recipes/69095/tasteWidget.json?apiKey=b454430f54a14e');

        try{
            Http http=new Http();
            HttpResponse response=http.send(request);

            if (response.getStatusCode() == 200) {
                Map<String,Object> results = (Map<String,Object>)Json.deserializeUntyped(response.getBody());
                Value2= Integer.valueof(results.get('sweetness'));
                Value3 = Integer.valueof(results.get('saltiness'));
            }
            leadAccounts.deger1__c = Value3;
            leadAccounts.deger2__c = Value2;
        }
        catch(System.CalloutException e){
            system.debug('Error-' + e.getMessage());
        }
        return leadAccounts;
    }
}

A: if (userIds != null && (!System.isFuture() || !System.isQueueable())) {

Is incorrect. If you're in a future call, you won't be in a queueable call, and if you're in a queueable call, you won't be in a future call. Both TRUE || FALSE and FALSE || TRUE will result in a TRUE result every time. You meant to use &&, instead:
if (userIds.size() > 0 && !System.isFuture() && !System.isQueueable()) {

I know this tends to confuse newer programmers, since in normal English, we often say "or" instead of "and" in some places. You may want to refresh your memory on how && and || work with some truth tables. Once you get used to it, you'll hardly ever make that mistake.
Also, note that userIds can't be null, no need to check for that here, but you probably want to check if the list is empty first.


text:
Q: Populate data in spring model I have kept a map in the page model. While invoking the page, am fetching few items from database and will keep that in the map so that i will use it in the JSP. Mainly these items are used for populating options in dropdown.
@RequestMapping(value = "/initSystemPage")
public String initSystemPage(@ModelAttribute("systemModel") SystemModel systemModel, ModelMap modelMap) {

    Map<String, List<DropdownVO>> data = ** fetch items from database **;
    systemModel.setData(data);

    return "system";
}

Upon invoking the screen, i can get the items from the model and populate the values in the dropdown. So far fine. but the issue happens if i do any action like submitting the form. As am not keep an element in the JSP corresponding to the data attribute, upon submitting the form dropdown data is not mapped to model hence it is not available in the JSP after page refresh.
I dont want to populate the items in model in every action methods. if i keep the data in session attributes, is it possible to do the populate in a common method that need to be invoked in all actions? something like init-binder

A: If you want to keep your current design you can make use of @SessionAttributes annotation at class level to ensure that your systemModel attribute is stored in session and is accessible for subsequent requests. However make sure that you clear the attribute when you have completed form processing using SessionStatus. For example
@Controller
@SessionAttributes("systemModel")
public SystemPageController{

@RequestMapping(value = "/initSystemPage" , method = RequestMethod.GET)
public String initSystemPage(@ModelAttribute("systemModel") SystemModel systemModel, ModelMap modelMap) {

    Map<String, List<DropdownVO>> data = ** fetch items from database **;
    systemModel.setData(data);

    return "system";
}
}

Alternatively you can use @ModelAttribute annotation to indicate methods which should be called for every request for the Controller to add model data.
@ModelAttribute("systemModel")
public SystemModel populateSystemModel(){
   //code to populate and return
}

The signature is very flexible. You can include most parameters used with @RequestMapping methods such as HttpServletRequest @RequestParam , @PathVaribale etc


text:
Q: Centennial app targeting .net higher than installed - What will happen? I have .net 4.7.1 installed. What if I build a .net application targeting that version of .net, and then package it as a Centennial app - What if someone with an older version of .net tries to install it (from the Windows Store)?
An official link confirming the answer would be nice, if possible.
EDIT
Since this seems to be unclear. The Windows Store presumably knows about your computer. The question is just what will it do about it. Will it prompt you to install the newer version like Clickonce can do, or just not let you install the app, or something else?

A: It depends. Keep in mind that Centennial is a bridge.
Centennial apps run on Windows 10 Anniversary edition (10.0; Build 14393) or later. On this Windows version the default installed .NET version is 4.6.2. Windows 10 Creators Update comes with .NET 4.7 by default.
So, if someone downloads your application on Windows 10 Anniversary edition and tries to run it, the following can happen:

*

*.NET 4.6.2 is installed, your application doesn't use anything from .NET 4.7.1: your application works properly

*.NET 4.6.2 is installed, your application is using .NET 4.7.1 specific features: your application doesn't work properly

*.NET 4.7.1 is installed, your application doesn't use anything form .NET 4.7.1: your application works properly

*.NET 4.7.1 is installed, your application is using .NET 4.7.1 specific features: your application works properly

You can apply the same logic for the later versions of Windows 10.
Another interesting option would be to package .NET 4.7.1 along with your application. If I understand it correctly, the Centennial apps have a virtual file system, which is basically merged with the real one. So, you should be able to install .NET 4.7.1 with your application and then package it together with your application. Then it will work on Windows 10 Anniversary edition as well on the later editions.


text:
Q: Refreshing parent page after child window is closed dynamics 2011 This is in the context of Microsoft Dynamics 2011. I am opening a webresource using showModalDialog. This question is strictly for IE. I have tried using window.unload to refresh the parent page after modal dialog is closed, using this code:
    window.onunload = refreshParent;
      function refreshParent() {
        window.opener.location.reload();
    }

and have also tried polling the modal page's closed status from the parent page using setInterval, and triggering refresh when it is closed, but none seem to work. Was wondering if anyone had any ideas...

A: First, a word of caution:  showModalDialog() is deprecated in all modern browsers.  And while it does function in IE (including in version 11), it is not supported in Edge.  It's only a matter of time before you will need to change this implementation.  I strongly suggest you consider an alternative solution that does not use this method.
That said, if you do decide to use showModalDialog(), consider assigning the function call to a variable.  From the modal page, you can assign to the window.returnValue property to pass whatever data you'd like.
Within your main page code, you can then check the value of your variable, and take action accordingly.  Here's one way to do that:
Main Page:
var returnedFromModal = window.showModalDialog(/* your options here*/);
if (returnedFromModal) {
    window.location.reload();
}

Modal:
/* ... other modal-related code ...*/
window.returnValue = true;

Further documentation can be found here:  https://developer.mozilla.org/en-US/docs/Web/API/Window/showModalDialog


text:
Q: Laravel local scope:BadMethodExeption namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model {
    public function scopeCompleted($query){
        return $query->where('completed',1);
    }

When I call method:
App\Task::completed()

I get:

BadMethodCallException with message 'Method
  Illuminate\Database\Query\Builder::completed does not exist.'

I created local scope, but i can't use method to search query.
And i called:
$task = App\Task::completed()->get();

same error!


text:
Q: how to use a checkmark as a checkbox in css I have a check mark as shown below, I want to use the check mark to act as a check box, I don't want the tick to appear inside a check box. I want to be able to click on the tick so it gets selected. It should be like a checkbox but with out the box, any suggestions if this can be done in css?

.checkmark {
    display:inline-block;
    width: 22px;
    height:22px;
    -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
}

.checkmark_stem {
    position: absolute;
    width:3px;
    height:9px;
    background-color:#ccc;
    left:11px;
    top:6px;
}

.checkmark_kick {
    position: absolute;
    width:3px;
    height:3px;
    background-color:#ccc;
    left:8px;
    top:12px;
}

A: Customizing checkboxes is hard and requires a checkbox first.
You will need a checkbox to hold the value of the check. And you will need to style the label, and hide the checkbox, so that you will only see the label, and this label will be able to interact with the checkbox.
Try this instead :

.checkmark {
    display:inline-block;
    width: 22px;
    height:22px;
    -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
}

input[type="checkbox"] { display: none; }

.checkmark:before {
    content: '';
    position: absolute;
    width:3px;
    height:9px;
    background-color:#ccc;
    left:11px;
    top:6px;
}

.checkmark {
  cursor: pointer;
}

.checkmark:after {
    content: '';
    position: absolute;
    width:3px;
    height:3px;
    background-color:#ccc;
    left:8px;
    top:12px;
}

input[type="checkbox"]:checked + .checkmark:before,
input[type="checkbox"]:checked + .checkmark:after {
  background-color: green;
}
<input type="checkbox" id="cb">

A: Did you mean it?

.checkmark {
    display:inline-block;
    width: 22px;
    height:22px;
    -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
}

.checkmark_stem {
    position: absolute;
    width:3px;
    height:9px;
    background-color:#ccc;
    left:11px;
    top:6px;
}

.checkmark_kick {
    position: absolute;
    width:3px;
    height:3px;
    background-color:#ccc;
    left:8px;
    top:12px;
}

.checkbox-hidden {
 display: none;
}
.checkbox-hidden:checked + label .checkmark_stem, .checkbox-hidden:checked + label .checkmark_kick {
 background-color: #4caf50;
}
<input type="checkbox" class="checkbox-hidden" id="checkbox">


text:
Q: Show an image of Dropbox <?php
$ch = curl_init ("https://api-content.dropbox.com/1/files/dropbox/Printable/game-of-thrones-poster1.jpg?oauth_consumer_key=3gg0ec7ju39cghr&oauth_token=pmrniz9qif7kbe3&oauth_signature_method=PLAINTEXT&oauth_signature=qcwg77mfetqr4zi%26l8l632jrmw3h80b&oauth_timestamp=1347451716&oauth_nonce=793902999f4dfae87ed757e1c6443f40&oauth_version=1.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3');
$image=curl_exec($ch);
curl_close ($ch);
header("Content-Type: image/jpeg");
echo $image;
?>

With the above code, I want to display an image file on dropbox. But the picture does not display!

I'm using oauth information, dropbox located on a file (image, video, ..) I know how you view your? Saving to the server, I want to show through dropbox.


text:
Q: SQL Server - MERGE duplicate SOURCE rows validation is only evaluated on UPDATE and DELETE clauses I want SQL Server to throw an error at me if my SOURCE table contains duplicates as per the ON clause in every case, including INSERT, but it only does for the UPDATE and DELETE cases. Why doesn't it?
For example, it takes two executions of this statement to get any sort of validation error. First, let's define the table:
--assume this is a permanent table that starts empty:
CREATE TABLE #MyTable(KeyID1 INT, KeyID2 INT, SomeValue REAL)--no primary key on purpose for example

And the MERGE statement I wish would throw the error at me on the first execution:
MERGE #MyTable AS TARGET
USING
(
    SELECT
         KeyID1 = 1
        ,KeyID2 = 1
        ,SomeValue = 1
    UNION ALL SELECT
         KeyID1 = 1
        ,KeyID2 = 1
        ,SomeValue = 2
) AS SOURCE ON
    TARGET.KeyID1 = SOURCE.KeyID1
    AND TARGET.KeyID2 = SOURCE.KeyID2
WHEN MATCHED THEN UPDATE SET
    TARGET.SomeValue = SOURCE.SomeValue
WHEN NOT MATCHED BY TARGET THEN INSERT
    (
         KeyID1
        ,KeyID2
        ,SomeValue
    )
    VALUES
    (
         SOURCE.KeyID1
        ,SOURCE.KeyID2
        ,SOURCE.SomeValue
    );

After the first execution, the contents of #MyTable are

The error message that only comes on the second and subsequent executions:

Msg 8672, Level 16, State 1, Line 4
  The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

The wording of this error message seems to imply my desired validation should be occurring already.
Of course, one obvious thing to do is make the primary key on the TARGET table reject the INSERT, but that is unrelated to my question.
P.S. I came across this list of MERGE bugs that doesn't seem to apply here.

A: On the first run, there are no matches in the conditional check. That is, there are no rows in #MyTable that match the input rows.
Note that the matching in a MERGE does not consider rows inserted during the MERGE itself. If those rows could cause duplication, it is the responsibility of the developer to ensure that there are no potential conflicts in the source data. Since this is the case, and there are no constraints such as a Primary Key to conflict with the data being added, this insert succeeds for both rows.
Of course, on the second run, there are two matching rows, and the MERGE fails with the error you showed.
This is by design, and does speed the processing, as if the MERGE had to validate each row individually as they were considered (as opposed to set based validation performed by the MERGE internally), then the process would be more like using a cursor to handle each row one at a time.
How To Handle Source Duplicates
Using the simple case you have above, I would modify it like this to handle source duplication:
CREATE TABLE #MySource (        -- This represents the actual source of the data in the database
    KeyID1 int,
    KeyId2 int,
    SomeValue bigint
    )
INSERT INTO #MySource

    SELECT
         KeyID1 = 1
        ,KeyID2 = 1
        ,SomeValue = 1
    UNION ALL
    SELECT
         1
        , 1
        , 2

-- Find the duplicates, and set up an error condition / report for them.

    SELECT
        KeyID1,
        KeyId2,
        Count(*) as ct
    INTO #Duplicates
    FROM #MySource
    GROUP BY KeyID1, KeyId2
    HAVING COUNT(*) > 1

    IF EXISTS (Select * FROM #Duplicates)
    BEGIN
        -- handle error here. Perform a Raiserror or THROW, or SELECT
        -- the items from the duplicates and stop processing, or...
        Print 'Error - Duplicates!'
        SELECT *
        FROM #Duplicates
    END

    -- No duplicates, so continue
MERGE #MyTable AS TARGET
USING (
    SELECT *
    FROM #MySource m
    )
) AS SOURCE ON
    TARGET.KeyID1 = SOURCE.KeyID1
    AND TARGET.KeyID2 = SOURCE.KeyID2
WHEN MATCHED THEN UPDATE SET
    TARGET.SomeValue = SOURCE.SomeValue
WHEN NOT MATCHED BY TARGET THEN INSERT
    (
         KeyID1
        ,KeyID2
        ,SomeValue
    )
    VALUES
    (
         SOURCE.KeyID1
        ,SOURCE.KeyID2
        ,SOURCE.SomeValue
    );


text:
Q: No source available for "realloc() " in Eclipse in Ubuntu When I debugging my c codes, I am getting this on the realloc line. How can I solve this? I included stdlib.h

A: If you want to debug libc you need the development libraries
http://packages.ubuntu.com/hardy/libc6-dev
in a console, type:
sudo apt-get install libc6-dev

now in practice, you should not need to debug this function, however it would make the error go away.


text:
Q: Jquery check if browser is IE How would i check if the users browser is IE? i have this code here but it is not working.
if($.browser.msie && $.browser.version <= 9)
{
    alert('You Are Using An Outdated Browser! Switch To Chrome Or FireFox.');
}

A: Test for features, not browsers.  If you use and require FormData like you've stated in your comments, then change your check to:
if ( !("FormData" in window) ) {
   // Tell the user to use a better browser, or whatever
}

A: How about the MS recommended way:
http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx
(And of course the UserAgent can be spoofed... but, if someone is spoofing their UserAgent do you really care about what they see on your site?)
 function getInternetExplorerVersion()
 // Returns the version of Internet Explorer or a -1
 // (indicating the use of another browser).
 {
    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

        if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 );
    }
    return rv;
}

A: Try this solution by James Padolsey:
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie> 7 // IE8, IE9 ...
//     ie <9 // Anything less than IE9
// ----------------------------------------------------------
var ie = (function(){
    var undef, v = 3, div = document.createElement('div');

    while (
        div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
        div.getElementsByTagName('i')[0]
    );

    return v> 4 ? v : undef;
}());

There are other interesting solutions in the comments as well.

A: browser was removed in 1.9.:

Description: Contains flags for the useragent, read from navigator.userAgent. We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.

A: Just a reminder (even thought not directly answers the question); it is always better to user feature detection as opposed to browser detection.
This is why Modernizr is there for;

Why use Modernizr?
Taking advantage of cool new web technologies is great fun, until you have to support browsers that lag behind. Modernizr makes it easy for you to write conditional JavaScript and CSS to handle each situation, whether a browser supports a feature or not. It's perfect for doing progressive enhancement easily.

So you would use it like;
Modernizr.canvas ? showGraph() : showTable();


text:
Q: Hierarchical TreeView from DataSet I'm new in WPF and cant get how to bind that dataset to treeview
Dim dtHDD As New DataTable("Disks")
dtHDD.Columns.Add("ID")
dtHDD.Columns.Add("DiskName")

dtHDD.Rows.Add(1, "Disc1")
dtHDD.Rows.Add(2, "Disc2")

Dim dtFolders As New DataTable("Folders")
dtFolders.Columns.Add("ID")
dtFolders.Columns.Add("DiskID")
dtFolders.Columns.Add("FolderID")
dtFolders.Columns.Add("FolderName")

dtFolders.Rows.Add(1, 2, DBNull.Value, "Music")
dtFolders.Rows.Add(2, 1, DBNull.Value, "Documents")
dtFolders.Rows.Add(3, 1, 2, "Scatches")
dtFolders.Rows.Add(4, 1, 3, "Images")
dtFolders.Rows.Add(5, 1, 3, "Folder1")
dtFolders.Rows.Add(6, 1, 2, "Bin")
dtFolders.Rows.Add(7, 2, DBNull.Value, "Moves")
dtFolders.Rows.Add(8, 1, 5, "Another one")

Dim dtFiles As New DataTable("Files")
dtFiles.Columns.Add("ID")
dtFiles.Columns.Add("FolderID")
dtFiles.Columns.Add("FileName")

dtFiles.Rows.Add(1, 8, "file1")
dtFiles.Rows.Add(2, 2, "file2")
dtFiles.Rows.Add(3, 3, "file3")
dtFiles.Rows.Add(4, 2, "file4")
dtFiles.Rows.Add(5, 5, "file5")
dtFiles.Rows.Add(6, 5, "file6")
dtFiles.Rows.Add(7, 8, "file7")
dtFiles.Rows.Add(8, 8, "file8")
dtFiles.Rows.Add(9, 1, "file9")

Dim ds As New DataSet
ds.Tables.Add(dtHDD)
ds.Tables.Add(dtFolders)
ds.Tables.Add(dtFiles)
ds.Relations.Add("DiskFolder", ds.Tables("Disks").Columns("ID"), ds.Tables("Folders").Columns("DiskID"))
ds.Relations.Add("FolderFolder", ds.Tables("Folders").Columns("ID"), ds.Tables("Folders").Columns("FolderID"))
ds.Relations.Add("FolderFile", ds.Tables("Folders").Columns("ID"), ds.Tables("Files").Columns("FolderID"))

treeTest.ItemsSource = ds.Tables("Disks").DefaultView

So each disk can contain folders only.
Each folder can contain files and folders.
I made the following markup
<TreeView x:Name="treeTest" Margin="380,0,0,0">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding DiskFolder}">
            <TextBlock Text="{Binding DiskName}"/>
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding FolderName}" />
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

But I don't know how to set RowFilter rule for Folder table and how add files in that treeview.

A: You could use a DataTemplateSelector that selects the appropriate template based on the name of the parent table:
Public Class TemplateSelector
    Inherits DataTemplateSelector

    Public Property DiskTemplate As DataTemplate
    Public Property FolderTemplate As DataTemplate
    Public Property FileTemplate As DataTemplate

    Public Overrides Function SelectTemplate(item As Object, container As DependencyObject) As DataTemplate

        Dim drv = CType(item, System.Data.DataRowView)
        Select Case drv.DataView.Table.TableName
            Case "Disks"
                Return DiskTemplate
            Case "Folders"
                Return FolderTemplate
            Case "Files"
                Return FileTemplate
        End Select

        Return Nothing

    End Function

End Class

Usage:
<Window x:Class="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <HierarchicalDataTemplate x:Key="diskTemplate" ItemsSource="{Binding DiskFolder}">
            <TextBlock Text="{Binding DiskName}"/>
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate x:Key="folderTemplate" ItemsSource="{Binding FolderFile}">
            <TextBlock Text="{Binding FolderName}"/>
        </HierarchicalDataTemplate>

        <DataTemplate x:Key="fileTemplate">
            <TextBlock Text="{Binding FileName}"/>
        </DataTemplate>

        <local:TemplateSelector x:Key="TemplateSelector"
                                DiskTemplate="{StaticResource diskTemplate}"
                                FolderTemplate="{StaticResource folderTemplate}"
                                FileTemplate="{StaticResource fileTemplate}"/>
    </Window.Resources>
    <StackPanel>
        <TreeView x:Name="treeTest" ItemTemplateSelector="{StaticResource TemplateSelector}" />
    </StackPanel>
</Window>

A: I have done that way
<HierarchicalDataTemplate x:Key="folderTemplate" ItemsSource="{Binding FolderFolder}">
    <TextBlock Text="{Binding FolderName}"/>
</HierarchicalDataTemplate>

MyWindow
I think the left to add a filter for the rows
RowFilter = "FolderID is null"

But how don't get it...

A: Finally i want see that structure
<disc Name="Disc1">
    <folder Name="Documents">
        <folder Name="Scatches">
            <folder Name="Images"/>
            <folder Name="Folder1">
                <folder Name="Another one">
                    <file Name="file1"/>
                    <file Name="file7"/>
                    <file Name="file8"/>
                </folder>
                <file Name="file5"/>
                <file Name="file6"/>
            </folder>
            <file Name="file3"/>
        </folder>
        <folder Name="Bin"/>
        <file Name="file2"/>
        <file Name="file4"/>
    </folder>
</disc>
<disc Name="Disc2">
    <folder Name="Music">
        <file Name="file9"/>
    </folder>
    <folder Name="Moves" />
</disc>


text:
Q: Custom wiring a micro camera to a USB I've been looking for a micro camera that has UVC support but since I haven't found any, I decided to investigate combining a micro camera with a USB-to-serial(?) cable.
Using camera A (see below for photos), can I remove its cable and replace it with the cable ending in the white connector in camera B (splicing the wires)?
Of course, this is more of a 'what to watch out for' question - I realise there are no guarantees, but as I have little experience with electronics, I'd like to know if there are plausible problems with this, or if this is even possible.
Camera A

.
Camera B

A: No, it cannot (easily) be done. Your "micro camera" clearly has a composite analog output, which would have to be digitized before it could be passed to a USB port as data.
Furthermore, a "USB-to-serial" cable would not have the required bandwidth to support live video anyway.


text:
Q: Using variable second times in function not return the same value? I start learning Scala, and i wrote that code. And I have question, why val which is constant? When i pass it second time to the same function return other value? How write pure function in scala?
Or any comment if that counting is right?
import java.io.FileNotFoundException
import java.io.IOException
import scala.io.BufferedSource
import scala.io.Source.fromFile

object Main{
  def main(args: Array[String]): Unit = {
    val fileName: String = if(args.length == 1) args(0) else ""
    try {
      val file = fromFile(fileName)

      /* In file tekst.txt is 4 lines */
      println(s"In file $fileName is ${countLines(file)} lines")
      /* In file tekst.txt is 0 lines */
      println(s"In file $fileName is ${countLines(file)} lines")

      file.close
    }
    catch{
      case e: FileNotFoundException => println(s"File $fileName not found")
      case _: Throwable => println("Other error")
    }
  }

  def countLines(file: BufferedSource): Long = {
    file.getLines.count(_ => true)
  }
}

A: val means that you cannot assign new value to it. If this is something immutable - a number, immutable collection, tuple or case class of other immutable things - then your value will not change over its lifetime - if this is val inside a function, when you assign value to it, it will stay the same until you leave that function. If this is value in class, it will stay the same between all calls to this class. If this is object it will stay the same over whole program life.
But, if you are talking about object which are mutable on their own, then the only immutable part is the reference to object. If you have a val of mutable.MutableList, then you can swap it with another mutable.MutableList, but you can modify the content of the list. Here:
val file = fromFile(fileName)

/* In file tekst.txt is 4 lines */
println(s"In file $fileName is ${countLines(file)} lines")
/* In file tekst.txt is 0 lines */
println(s"In file $fileName is ${countLines(file)} lines")

file.close

file is immutable reference to BufferedSource. You cannot replace it with another BufferedSource - but this class has internal state, it counts how many lines from file it already read, so the first time you operate on it you receive total number of lines in file, and then (since file is already read) 0.
If you wanted that code to be purer, you should contain mutability so that it won't be observable to the user e.g.
def countFileLines(fileName: String): Either[String, Long] = try {
  val file = fromFile(fileName)
  try {
    Right(file.getLines.count(_ => true))
  } finally {
    file.close()
  }
} catch {
  case e: FileNotFoundException => Left(s"File $fileName not found")
  case _: Throwable => Left("Other error")
}

println(s"In file $fileName is ${countLines(fileName)} lines")
println(s"In file $fileName is ${countLines(fileName)} lines")

Still, you are having side effects there, so ideally it should be something written using IO monad, but for now remember that you should aim for referential transparency - if you could replace each call to countLines(file) with a value from val counted = countLines(file) it would be RT. As you checked, it isn't. So replace it with something that wouldn't change behavior if it was called twice. A way to do it is to call whole computations twice without any global state preserved between them (e.g. internal counter in BufferedSource). IO monads make that easier, so go after them once you feel comfortable with syntax itself (to avoid learning too many things at once).

A: file.getLines returns Iterator[String] and iterator is consumable meaning we can iterate over it only once, for example, consider
val it = Iterator("a", "b", "c")

it.count(_ => true)
// val res0: Int = 3

it.count(_ => true)
// val res1: Int = 0

Looking at the implementation of count
def count(p: A => Boolean): Int = {
  var res = 0
  val it = iterator
  while (it.hasNext) if (p(it.next())) res += 1
  res
}

notice the call to it.next(). This call advances the state of the iterator and if it happens then we cannot go back to previous state.
As an alternative you could try length instead of count
val it = Iterator("a", "b", "c")

it.length
// val res0: Int = 3

it.length
// val res0: Int = 3

Looking at the definition of length which just delegates to size
def size: Int = {
  if (knownSize >= 0) knownSize
  else {
    val it = iterator
    var len = 0
    while (it.hasNext) { len += 1; it.next() }
    len
  }
}

notice the guard
if (knownSize >= 0) knownSize

Some collections know their size without having to compute it by iterating over them. For example,
Array(1,2,3).knownSize  //  3: I know my size in advance
List(1,2,3).knownSize   // -1: I do not know my size in advance so I have to traverse the whole collection to find it

So if the underlying concrete collection of the Iterator knows its size, then call to length will short-cuircuit and it.next() will never execute, which means the iterator will not be consumed. This is the case for default concrete collection used by Iterator factory which is Array
val it = Iterator("a", "b", "c")
it.getClass.getSimpleName
// res6: Class[_ <: Iterator[String]] = class scala.collection.ArrayOps$ArrayIterator

however it is not true for BufferedSource. To workaround the issue consider creating an new iterator each time countLines is called
def countLines(fileName: String): Long = {
  fromFile(fileName).getLines().length
}

println(s"In file $fileName is ${countLines(fileName)} lines")
println(s"In file $fileName is ${countLines(fileName)} lines")

// In file build.sbt is 22 lines
// In file build.sbt is 22 lines

Final point regarding value definitions and immutability. Consider
object Foo { var x = 42 } // object contains mutable state

val foo = Foo // value definition

foo.x
// val res0: Int = 42

Foo.x = -11 // mutation happening here

foo.x
// val res1: Int = -11

Here identifier foo is an immutable reference to mutable object.


text:
Q: Points wrapping to start of OxyPlot chart I have a program which receives a datestamp and a value from an access (.mbd) database and saves them to two lists (dates and dataPoints, respectively). When I use an OxyPlot chart with DateTimeAxis to plot the points, it doubles up on some points which are the same time, but a different date. Is there a way to make OxyPlot take dates into account as well?
public void CreatePlot(List<float> dataPoints, List<DateTime> dates, DateTime fromDate, DateTime toDate, string craneName)
    {
        PlotView plotView = new PlotView();
        this.Controls.Add(plotView);

        PlotModel plotModel = new PlotModel();
        DateTimeAxis xAxis = new DateTimeAxis();
        xAxis.Position = AxisPosition.Bottom;
        //xAxis.Minimum = DateTimeAxis.ToDouble(fromDate);
        //xAxis.Maximum = DateTimeAxis.ToDouble(toDate);
        //Console.WriteLine(xAxis.Minimum.ToString());
        //Console.WriteLine(xAxis.Maximum.ToString());
        plotModel.Axes.Add(xAxis);
        LinearAxis yAxis = new LinearAxis();
        plotModel.Axes.Add(yAxis);
        LineSeries lineSeries = new LineSeries();
        for (int i = 0; i < dataPoints.Count; i++)
        {
            lineSeries.Points.Add(new OxyPlot.DataPoint(DateTimeAxis.ToDouble(dates[i]), dataPoints[i]));
            LogFileHandling.LogWrite(dates[i].ToString() + dataPoints[i].ToString());
        }
        plotModel.Series.Add(lineSeries);
        plotView.Model = plotModel;
    }

A: Never mind, it was the data coming from the database that was causing the issue. Performing a compact and repair on it fixed it.


text:
Q: Remove wildcard matching lines between two files I am trying to remove domains from a list that match in another file of domains I don't want to include. For example: a file containing a list of google subdomains, then another file containing a list of subdomains like: abc.google.com, def.google.com. How can I remove all entries from the first file that end *.abc.google.com, and *.def.google.com
I have seen many answers similar but can't apply any to my situation. Most answers use grep but I read that grep is for small files only and I could potentially be working with large files.

A: I don't think that there's any standard tool that can match a string input against a glob, only the case statement of the shell is able to.
bash possesses an additional construct with this capability, which is [[ $var == $glob ]], so it's possible (but sub-optimal) to do the  filtering in bash:
#!/bin/bash

mapfile -t xglobs < xglobs.txt || exit 1

while IFS='' read -r domain
do
    for g in "${xglobs[@]}"
    do
        [[ $domain == $g ]] && continue 2
    done
    echo "$domain"
done < domains.txt

Example
For a domain list like this:
www.google.us
www.google.com
www.xzy.com
ftp.abc.org

And a glob list like this:
*.google.com
*.abc.org

The code will output:
www.google.us
www.xzy.com

A better solution would be to convert your globs to regexps (for example the equivalent of *.google.com would be
^.*\.google\.com$) and use grep for the filtering:
grep -v -f xregexps.txt domains.txt


text:
Q: Automatic syntax highlighter I'm looking for a good all rounded syntax highlighter written in JavaScript that will auto detect the language used and apply proper syntax highlighting.
I've found a myriad of them from a simple Google search but they all have to have some sort of formatted class on the <pre> element like <pre class="highlight-php">.
I noticed StackOverflow's syntax highlighting manages to do it automatically from within pre blocks, anyone know what library they're using?
Thanks!

A: They are using google prettify.  There are other options, such as highlight.js


text:
Q: create field.val array from class selector I'm very new to jquery and just looking for some help.
current code:
var formData = {
                    'settings'          : $('input[name=settings]').val(),
                    'name'              : $('input[name=name]').val(),
                    'email'             : $('input[name=email]').val(),
                    'superheroAlias'    : $('input[name=superheroAlias]').val()
                };

What im looking to do is instead of declare each individual field is maybe add a class to each input and pick up each field that way.
Im guessing this is possible but I've tried so many diffent ways and i feel im just confusing myself more

A: Yes, it is possible. Use a custom class and each()

var formData = {};

$('.my-class').each(function(){
  formData[$(this).attr('name')] = $(this).val();
  });

console.log(formData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input class="my-class" name="settings" value="1"/>
<input class="my-class" name="name" value="2"/>
<input class="my-class" name="email" value="3"/>
<input class="my-class" name="superheroAlias" value="4"/>


text:
Q: Javascript - sort and manipulate array of dates I'm trying to prep a table which would have a header be an array of months/year. So the table would look roughly like such:
          month1/year, month2/year, month3/year, etc....
field1:
field2:
field3:

The particular months/years are based upon a start and end date provided by a user. Based on some answers here, I have the logic working, however I hit a snag. By the way I've gone about getting the month (using getMonth()), it returns it as the index (so 0 for Jan, etc.). My first thought was just to +1, but clearly I then run into an issue with December -> January. My javascript skills are weak, so my only thought is to write in an if statement and adjust the final array after the fact.
Here's what I have so far:
function dateRange(startDate, endDate, steps = 1) {
   const dateArray = [];
   let currentDate = new Date(startDate);

   while (currentDate <= new Date(endDate)) {
   dateArray.push(new Date(currentDate));
   // Use UTC date to prevent problems with time zones and DST
   currentDate.setUTCDate(currentDate.getUTCDate() + steps);
   }

   console.log("dateArray: ", dateArray)

   const monthSet = dateArray.map(i => `${i.getMonth()}/${i.getFullYear()}`)
   const header = [...new Set(monthSet)]
   return header;
}
const dates = dateRange(isStart, isEnd);
console.log(dates);

A: It's not entirely clear what you're asking, sorry. But if you're wondering how to increment the month index without getting numbers like 13, 14, etc., you can use the modulo operator:
 1 % 12 ===  1;
 2 % 12 ===  2;
 3 % 12 ===  3;
10 % 12 === 10;
12 % 12 ===  0;
13 % 12 ===  1;

You should be safe simply adding 1 to .getMonth(), since that function will only ever yield values 0 though 11.